텐서 인덱싱은 텐서에서 특정 요소나 데이터 범위를 선택하고 조작하는 방법. 다차원 데이터를 처리할 때 필수적인 기술이며, 데이터를 효과적으로 선택하고 활용할 수 있도록 돕는다.
PyTorch의 텐서 인덱싱은 NumPy 인덱싱과 매우 유사하다.
# Create a tensor
import torch
x= torch.arange(1, 10).reshape(1,3,3)
x, x.shape

크기 (1, 3, 3)는 다음을 의미한다:
요소 접근하기
인덱싱의 기본 형식: tensor [ 차원_1, 차원_2, ... ]
print(x[0])

print(x[0][0])

print(x[0][2][2])

# 모든 행을 선택하고 첫 번째 열만 가져오기
print(x[:, :, 0]) # 결과: [[1, 4, 7]]
# 첫 번째 텐서의 두 번째 행의 모든 요소 가져오기
print(x[0, 1, :]) # 결과: [4, 5, 6]
# 모든 행에서 마지막 열 가져오기
print(x[:, :, -1]) # 결과: [[3, 6, 9]]
# 첫 번째 텐서의 모든 행과 열 접근
print(x[0, :, :])
# 첫 번째 텐서의 첫 두 행 접근
print(x[0, :2, :])

# 모든 행을 선택하고 두 번째 열만 가져오기
print(x[:, :, 1]) # 결과: [[2, 5, 8]]
PyTorch는 NumPy와 긴밀하게 연동된다. NumPy는 수치 계산을 위한 매우 인기 있는 라이브러리다. PyTorch는 NumPy 데이터로 시작하거나, NumPy 배열을 PyTorch 텐서로 변환하는 기능을 제공한다. 반대로 PyTorch 텐서를 다시 NumPy 배열로 변환할 수도 있다.
torch.from_numpy(ndarray)torch.Tensor.numpy()torch.from_numpy()라는 메서드가 있다.# Numpy array to tensor
import torch
import numpy as np
array = np.arange(1.0, 8.0)
# warning : when converting from numpy => pytorch, pytorch reflects numpy's default datatype of float64 unless specified otherwise
tensor = torch.from_numpy(array).type(torch.float32)
tensor, array

print("NumPy 배열 데이터 타입:", array.dtype) # float64
print("PyTorch 텐서 데이터 타입:", tensor.dtype) # float64
NumPy에서 PyTorch로 데이터를 변환할 때 데이터 타입을 변경할 수도 있다.
# 데이터 타입을 float32로 변환
tensor = torch.from_numpy(array).type(torch.float32)
# Change the value of array, what will this do to `tensor`?
array = array +1
array, tensor

.numpy() 메서드를 사용하여 변환# Create Tensor to Numpy array
tensor = torch.ones(7)
numpy_tensor = tensor.numpy()
tensor, numpy_tensor

# Change the tensor, what happens to `numpy_tensor`?
tensor = tensor + 1
tensor, numpy_tensor

짱이다!!!!!