본문 바로가기

부스트캠프 AI Tech/Pytorch

[02] Pytorch Basics

Tensor


  • 다차원 Arrays를 표현하는 pytorch 클래스
  • 사실상 numpy의 ndarray와 동일 ( = 텐서프로 Tensor와 동일 )
import numpy as np
n_array = np.arange(10) 
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
n_array = n_array.reshape(2,5)  
print("ndim :", n_array.ndim, "shape :", n_array.shape)
#ndim : 2 shape : (2, 5)

import torch
t_array = torch.FloatTensor(n_array)
print("ndim :", t_array.ndim, "shape :", t_array.shape)
# ndim : 2 shape : torch.Size([2, 5])

Array to Tensor


  • Tensor 생성은 list나 ndarray를 사용가능
  • Tensor가 가질 수 있는 data type은 numpy와 동일
#data to tensor
data = [[3,5],[10,5]]
x_data = torch.tensor(data)
# tensor([[ 3,  5],
#         [10,  5]])

#ndarray to tensor
nd_array_ex = np.array(data)
tensor_array = torch.tensor(nd_array_ex)
# tensor([[ 3,  5],
#         [10,  5]], dtype=torch.int32)

numpy like operations


  • pytorch의 tensor는 GPU에 올려서 사용가능
x_data.device
# device(type='cpu')

if torch.cuda.is_available():
    x_data_cuda = x_data.to('cuda')
    x_data_cuda.device
    # device(type='cuda', index=0)
  • numpy와 비슷한 operations

Tensor handling


  • view: reshape과 동일하게 tensor의 shape을 변환
  • squeeze: 차원의 개수가 1인 차원을 삭제 (압축)
  • unsqueeze: 차원의 개수가 1인 차원을 추가
  • mm, matmul: 행렬곱셈 연산 (mm은 matrix 곱의 사이즈가 맞아야만 가능 -> mm 사용하면 실수했는지 확인 가능)

view

tensor_ex = torch.rand(size=(2, 3, 2))
tensor_ex
# tensor([[[0.7466, 0.5440],
# [0.7145, 0.2119],
# [0.8279, 0.0697]],
# [[0.8323, 0.2671],
# [0.2484, 0.8983],
# [0.3228, 0.2254]]])

tensor_ex.view([-1, 6])
# tensor([[0.7466, 0.5440, 0.7145, 0.2119, 0.8279, 0.0697],
# [0.8323, 0.2671, 0.2484, 0.8983, 0.3228, 0.2254]])

tensor_ex.reshape([-1,6])
# tensor([[0.7466, 0.5440, 0.7145, 0.2119, 0.8279, 0.0697],
# [0.8323, 0.2671, 0.2484, 0.8983, 0.3228, 0.2254]])

squeeze

  • size(2,1,2), (1,2,2), (2,2,1) -> (2, 2) // (2,2,2) -> 오류 (차원의 개수가 1인 차원만 삭제)
tensor_ex = torch.rand(size=(2, 1, 2))
# tensor([[[0.7113, 0.5888]],
#        [[0.1318, 0.0977]]])

tensor_ex.squeeze()
# tensor([[0.7113, 0.5888],
#        [0.1318, 0.0977]])

tensor_ex = torch.rand(size=(2, 2))
tensor_ex.unsqueeze(0).shape
# torch.Size([1, 2, 2])
tensor_ex.unsqueeze(1).shape
# torch.Size([2, 1, 2])
tensor_ex.unsqueeze(2).shape
# torch.Size([2, 2, 1])

mm

a = torch.rand(5, 3)
b = torch.rand(3, 2)
a.mm(b)

argmax

  • squeeze 처럼 생각 dim 차원 없앤 사이즈 반환 그 모양에 따라서 최대값 인덱스
  • 2차원 일때는 dim=0 이면 열 기준 dim = 1이면 행기준.. 3차원이면 ... 이런식으로 생각하려니깐 복잡함 위처럼 생각
y = torch.randint(5, (4,3,2))
# tensor([[[4, 3],
#          [1, 4],
#          [1, 3]],

#         [[4, 3],
#          [0, 0],
#          [1, 4]],

#         [[4, 3],
#          [2, 4],
#          [1, 2]],

#         [[4, 0],
#          [3, 0],
#          [1, 0]]])

y.argmax(dim=0) # (4,3,2) -> (3,2) 크기 최대값 인덱스 반환
# tensor([[0, 0],
#         [3, 0],
#         [0, 1]])

y.argmax(dim=1) # (4,3,2) -> (4,2) 크기 최대값 인덱스 반환
# tensor([[0, 1],
#         [0, 2],
#         [0, 1],
#         [0, 0]])

y.argmax(dim=2) # (4,3,2) -> (4,3) 크기 최대값 인덱스 반환
# tensor([[0, 1],
#         [0, 2],
#         [0, 1],
#         [0, 0]])

torch.nn.functional as F


  • softmax()
  • ont_hot()
import torch
import torch.nn.functional as F
tensor = torch.FloatTensor([0.5, 0.7, 0.1])
h_tensor = F.softmax(tensor, dim=0)
h_tensor
# tensor([0.3458, 0.4224, 0.2318])

y = torch.randint(5, (10,5))
y_label = y.argmax(dim=1)
torch.nn.functional.one_hot(y_label)
# tensor([[1, 0, 0, 0, 0],
#         [0, 0, 0, 0, 1],
#         [0, 0, 0, 1, 0],
#         [1, 0, 0, 0, 0],
#         [0, 0, 0, 0, 1],
#         [0, 0, 0, 0, 1],
#         [0, 0, 0, 0, 1],
#         [1, 0, 0, 0, 0],
#         [1, 0, 0, 0, 0],
#         [0, 1, 0, 0, 0]])

AutoGrad


Pytorch의 핵심은 자동 미분을 지원한다. -> backward 함수 사용

w = torch.tensor(2.0,
requires_grad=True)
y = w**2
z = 10*y + 2
z.backward()
w.grad

# tensor(40.)
# z함수 w에 대한 미분은 z' = 20w 이므로 z'(2) = 40

a = torch.tensor([2., 3.], requires_grad=True)
b = torch.tensor([6., 4.], requires_grad=True)
Q = 3*a**3 - b**2

external_grad = torch.tensor([1., 1.])
Q.backward(gradient=external_grad)

a.grad # Q 함수 a에 대한 편미분 9a^2
# tensor([36., 81.])

b.grad # Q 함수 b에 대한 편미분 -2b
# tensor([-12., -8.])

'부스트캠프 AI Tech > Pytorch' 카테고리의 다른 글

[06] Pytorch의 hook  (0) 2022.01.20
[05] named_children, named_modules.  (0) 2022.01.19
[04] nn.parameter  (0) 2022.01.19
[03] nn.Module 이해하기  (0) 2022.01.18
[01] Introduction (Pytorch vs Tensorflow)  (0) 2022.01.17