Post

2024.07.03

기본 Pytorch를 공부합니다.


PyTorch Basics

pytorch: Dynamic Computation Graph (실행을 하며 그래프 생성)

  • PyTorch 의 특징
    Numpy 구조를 가지는 Tensor 객체로 array 표현
    자동미분(AutoGrad)을 지원해 DL 연산 지원
    다양한 형태의 DL (Dataset, Multi-GPU) 을 지원하는 함수와 모델을 지원
  • Tensor
    다차원 Arrays 를 표현하는 PyTorch class
  • numpy like operations
1
2
3
4
5
6
7
8
9
10
11
12
import torch

data [[3, 5, 20],[10, 5, 50],[1, 5, 10]]
x_data = torch.tensor(data)

x_data[1:]
x_data[:2, 1:]
x_data.flatten()
torch.ones_like(x_data)
x_data.numpy()
x_data.shape
x_data.dtype

< Tensor handling >

  1. view: reshape와 동일하게 tensor의 shape 변환
  2. squeeze: 차원의 개수가 1인 차원 삭제
  3. unsqueeze: 차원의 개수가 1인 차원 추가
  • 행렬곱셈 연산은 함수 dot (x), mm 사용함
    벡터 간 내적을 구할 때, dot 쓰면 되지만
    행렬 간 연산시, mm 사용 (t1.mm(t2))
1
2
3
4
a = torch.rand(5, 2, 3) # 5 batch, 2 by 3
b = torch.rand(3) # 3 by 1
a.mm(b) # 연산 안됨
a.matmul(b) # 연산 됨 <- broadcasting 지원
  • Tensor operations for ML/DL formula
    => nn.functional 모듈 통해 수식 변환 지원
1
2
3
4
5
6
7
8
9
10
11
12
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) # 자동으로 원핫 인코딩
  • torch autograd
    => backward 함수 사용
\[y = w^2\] \[z = 10*y + 25\] \[z = 10*w^{2} + 25\]
1
2
3
4
5
w = torch.tensor(2.0, requires_grad=True)
y = ww**2
z = 10*y + 25
z.backward()
w.grad


네이버 boostcourse의 인공지능 기초 다지기 강의를 참조함

This post is licensed under CC BY 4.0 by the author.