
Pytorch란?
Python을 위한 오픈 소스 머신러닝 라이브러리입니다. torch를 기반으로 자연어 처리와 다양한 머신러닝 과제를 수행하는 데 뛰어난 성능을 보이고 있습니다.
텐서(Tensor)란 Pytorch에서 사용하는 자료구조입니다. Pytorch는 tensor를 사용하여 모델의 입력(input)과 출력(output)합니다. Numpy의 ndarray와 유사한 Tensor는 ndarray와 메모리를 공유할 수 있고 ndarray를 Tensor로 Tensor를 ndaaray로 변환할 수 있습니다.
텐서는 자동 미분(Automatic Differentiation)에 최적화 되어 있으며 GPU에서 사용할 수 있습니다. 텐서의 속성은 모양(shape), 자료형(datatype) 및 어느 장치에 저장되는지(GPU or CPU)를 나타냅니다.
텐서를 생성할 수 있는 방법에는 여러가지가 있습니다. 데이터를 직접 텐서로 변환하거나, ndarray를 텐서로 변환시키거나, 다른 텐서로부터 생성하거나, 무작위(random) 또는 상수(constant) 값을 사용할 수 있습니다.
import torch
import numpy as np
# 데이터를 직접 텐서로 변경하는 방법
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
# Numpy array로 텐서를 생성하는 방법
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# 다른 텐서로부터 생성하는 방법
x_ones = torch.ones_like(x_data) # x_data의 속성을 유지합니다.
x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data의 속성을 덮어씁니다.
# 무작위 또는 상수 값을 사용하는 방법
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
Pytorch에서는 100여가지가 넘는 연산을 수행할 수 있습니다. 단순한 산술 연산 뿐만 아니라 transposing, 인덱싱, 슬라이싱 등을 수행할 수 있습니다. 텐서의 연산은 Numpy에서 수행하는 연산과 매우 유사하기 때문에 Numpy에 익숙한 사람이라면 쉽게 연산을 실행시킬 수 있습니다.
# Numpy식 인덱싱과 슬라이싱
tensor = torch.ones(4, 4)
tensor[:,1] = 0
# tensor.cat을 활용한 텐서 합치기
t1 = torch.cat([tensor, tensor, tensor], dim=1)
# 산술연산
# y1, y2, y3은 모두 같은 값을 가짐
y1 = tensor @ tensor.T # tensor.T는 tensor의 역행렬을 반환
y2 = tensor.matmul(tensor.T) # tensor.matmul을 사용한 행렬의 곱 연산
y3 = torch.rand_like(y1) # rand_like는 y1과 동일한 형태의 랜덤 tensor 생성
torch.matmul(tensor, tensor.T, out=y3)
# z1, z2, z3은 모두 같은 값을 가짐
z1 = tensor * tensor
z2 = tensor.mul(tensor) # tensor.mul을 사용한 요소별 곱 연산
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
© 참고