* Pytorch 튜토리얼에서 제공하는 내용을 기반으로 작성했습니다.
import pytorch
import numpy as np
pytorch에서 사용하는 기본적인 자료형은 tensor입니다. pytorch에서는 tensor를 이용해 입출력과 매개변수들을 사용합니다.
tensor는 numpy의 ndarray와 거의 유사하고, tensor와 ndarray는 동일한 메모리를 사용할 수 있기 때문에 복수로 데이터를 저장할 필요가 없습니다.
Tensor
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
torch의 tensor를 사용하면 데이터를 이용해 tensor를 생성할 수 있습니다.
np_array = np.array(data)
x_data = torch.from_numpy(np_array)
from_numpy를 사용하면 ndarray를 쉽게 tensor로 바꾸어줄 수 있습니다. 이때 tensor와 ndarray는 동일한 메모리를 사용하기 때문에 하나의 값을 변경하면 다른 값도 변경됩니다.
Tensor 생성
x_ones = torch.ones_like(x_np)
x_rand = torch.rand_like(x_np)
x_zeros = torch.zeros_like(x_np)
torch의 ~_like 함수를 사용하면 동일한 크기를 갖는 tensor를 생서할 수 있습니다.
ones, rand, zeros는 numpy에 있는 함수와 동일한 역할을 합니다.
Tensor 생성2
shape = (4, 5)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
한편 like를 붙이지 않고 rand, ones, zeros를 사용하면 shape을 인자로 받고 shape 크기의 tensor를 생성하게 됩니다.
Tensor 정보
tensor = torch.zeros(4, 3)
print('tensor shape:', tensor.shape)
print('tensor dtype:', tensor.dtype)
print('tensor device:', tensor.device)
shape, dtype, device를 사용하면 각각 tensor의 모양(형태), 자료형 그리고 어느 장치에 저장되어 있는지를 확인할 수 있습니다.
GPU 사용
if torch.cuda.is_available():
tensor = tensor.to('cuda')
gpu를 사용할 수 있는 환경이라면 tensor를 gpu 위에서 사용할 수 있습니다. 큰 크기의 텐서를 장치들 간에 복사하는 것은 메모리 측면에서 많은 비용이 들게 되기 때문에 주의해야 합니다.
Concat
tensor = torch.ones(4, 4)
t1 = torch.cat([tensor, tensor, tensor], dim=1]
print(t1)
cat을 이용하면 tensor를 이어붙일 수 있습니다. numpy의 axis와 비슷하게 dim을 이용해 이어붙일 방향을 정할 수 있습니다.
dim=1을 인자로 주면 tensor를 가로 방향(열이 나아가는 방향)으로 붙일 수 있습니다.
반면 dim=0을 주게 되면 tensor는 세로방향(행이 나아가는 방향)으로 붙일 수 있습니다.
산술 연산
# 두 tensor에 대한 행렬곱 연산
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3) # y3에 결과를 계산 결과를 저장
# 두 tensor의 요소별 곱 연산
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torhc.rand_like(y1)
torch.mul(tensor, tensor, out=z3) # 마찬가지로 z3에 결과를 저장
행렬곱과 곱셈 연산 외에도 사칙 연산을 각 요소들에 대해 계산할 수 있습니다.
sum_tensor = tensor.sum()
item = sum_tensor.item()
tensor에 대해 집계함수를 이용할 수 있고, item을 이용해 저장된 값에 접근할 수 있습니다.
item을 사용하지 않고 sum_tensor의 값을 보면 tensor type임을 알 수 있습니다.
Inplace 연산
tensor.add_(5)
tensor.t_()
연산 이름 뒤에 언더바(_)를 붙이게 되면 inplace 연산이 되어 계산 결과값을 바로 tensor에 저장하게 됩니다.
inplace 연산을 하게 되면 기록이 삭제되어 도함수를 계산할 때 문제가 발생할 수 있기 때문에 권장되지 않는 사용 방법입니다.
Numpy와 Tensor의 변환, Bridge
arr = np.ones(4, 3)
t = torch.from_numpy(arr) # ndarray를 tensor로 변환
n = t.numpy() # tensor를 ndarray로 변환
# t와 n은 동일한 메모리 주소를 공유하기 때문에 하나의 값이 변경되면 나머지 값도 같이 변경된다.
ToTensor
ToTensor를 이용하면 PIL Image나 ndarray를 FloatTensor로 변환하고 이미지 픽셀의 값을 [0., 1.]의 값으로 정규화해줍니다.
from PIL import Image
from torchvision.transforms import ToTensor, ToPILImage
tf_toTensor = ToTensor()
new_img = tf_toTenosr(img) # PIL image를 tensor로 변환, 정규화됨
tf_toPIL = ToPILImage()
old_img = tf_toPIL(new_img) # tensor를 PIL image로 변환, 정규화된 범위를 0~255 범위로 변환
One-hot encoding
from torchvision.transforms import Lambda
targets = Lambda(lambda y: torch.zeros(
10, dtype=torch.float).scatter_(dim=0, index=torch.tensor(y), value=1))
torchvision.transforms에 있는 Lambda를 이용해 lambda 함수를 이용할 수 있습니다. Lambda 함수를 이용하면 one-hot encoding을 적용할 수 있는데 여기서는 zeros를 이용해 class 개수만큼 0을 만들어주고 scatter_를 이용해 정답 y에 해당하는 인덱스 값을 1로 바꿔주는 방식으로 one-hot encoding을 수행해주었습니다.
'Python > Syntax' 카테고리의 다른 글
[Colab] 파이썬 버전 설정(변경) (0) | 2023.06.13 |
---|---|
[Python] pathlib (0) | 2023.04.07 |
[Numpy] hstack (2) | 2023.03.23 |
[Pandas] 함수 정리 (0) | 2023.02.09 |
[Python] while ~ else문 (0) | 2023.01.17 |