[PyTorch] 학습 방향 & Tensor Manipulation 1 실습 : 모두를 위한 딥러닝 시즌2
2024. 8. 27. 10:16ㆍArtificial Intelligence/모두를 위한 딥러닝 (PyTorch)
앞으로의 학습 방향
- 강의 목차가 대학에서 수강했던 데이터사이언스와 컴퓨터비전, 졸업논문 참고문헌에서 읽었던 내용과 전반적으로 겹침.
- 2가지 목적: 이전에 학습했던 이론을 꼼꼼히 복습하고, LAB 실습을 통해 코드와 이론이 어떻게 맞물려있는지에 중점을 두고 배운다.
Tensor Manipulation 이론 요약
기본적인 2D 텐서는 batch size와 dim(차원)으로 구성된다. 컴퓨터 비전에서의 텐서는 batch size, width, height로 구성되며, 자연어 처리에서의 텐서는 batch size, length, dim으로 구성된다는 차이가 있다. 자연어 처리에서는 dim과 length가 이루는 하나의 평면이 하나의 문장이다.
NumPy와 PyTorch로 Tensor Manipulation 하는 코드
행렬의 덧셈, 뺄셈 연산을 할 때는 두 텐서 간의 크기가 같아야 한다. 행렬의 곱셈 연산을 할 때는 첫 번째 행렬의 열 개수와 두 번째 행렬의 행 개수가 동일해야 한다. 하지만, 불가피하게 다른 크기의 텐서를 사칙연산 하는 경우가 있다. 이런 경우에 PyTorch에 있는 브로드캐스팅(Broadcasting) 기능을 사용한다. 자동으로 두 텐서의 크기를 맞추는 역할을 한다. Vector + Scalar 예시에서 볼 수 있듯이, 파이토치가 자동으로 Scalar인 [3]을 Vector인 [[3,3]] 로 변환해 주었다.
라이브러리 import
# Libraries
import numpy as np
import torch
NumPy로 Array 다루기
# 1D Array with NumPy
t = np.array([0., 1., 2., 3., 4., 5., 6.])
print(t)
print('Rank of t: ', t.ndim)
print('Shape of t: ', t.shape)
print('t[0] t[1] t[-1] = ', t[0], t[1], t[-1]) # Element
print('t[2:5] t[4:-1] = ', t[2:5], t[4:-1]) # Slicing
print('t[:2] t[3:] = ', t[:2], t[3:]) # Slicing
# 2D Array with NumPy
t = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.], [10., 11., 12.]])
print(t)
print('Rank of t: ', t.ndim)
print('Shape of t: ', t.shape)
PyTorch로 Array 다루기
# 1D Array with PyTorch
t = torch.FloatTensor([0., 1., 2., 3., 4., 5., 6.])
print(t)
print(t.dim()) # rank
print(t.shape) # shape
print(t.size()) # shape
print(t[0], t[1], t[-1]) # Element
print(t[2:5], t[4:-1]) # Slicing
print(t[:-2], t[3:]) # Slicing
# 2D Array with PyTorch
t = torch.FloatTensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.], [10., 11., 12.]])
print(t)
print(t.dim()) # rank
print(t.size()) # shape
print(t[:, 1])
print(t[:, 1].size())
print(t[:, :-1])
Broadcasting
# Broadcasting
# Same shape
m1 = torch.FloatTensor([[3, 3]])
m2 = torch.FloatTensor([[2, 2]])
print(m1 + m2)
# Vector + scalar
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([3]) # 3 -> [[3, 3]]
print(m1 + m2)
# 2 x 1 Vector + 1 x 2 Vector
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([[3], [4]])
print(m1 + m2)
행렬 곱셈과 행렬곱셈의 차이
# Multiplication
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1 * m2) # 2 x 2
print(m1.mul(m2))
# Matrix multiplication
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1.matmul(m2)) # 2 x 1
행렬의 통계
# Mean
t = torch.FloatTensor([1, 2])
print(t.mean())
# Can't use mean() on integers
t = torch.LongTensor([1, 2])
try:
print(t.mean())
except Exception as exc:
print(exc)
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t)
print(t.mean())
print(t.mean(dim=0))
print(t.mean(dim=1))
print(t.mean(dim=-1))
# Sum
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t)
print(t.sum())
print(t.sum(dim=0))
print(t.sum(dim=1))
print(t.sum(dim=-1))
# Max and Argmax
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t)
print(t.max()) # Returns on value: max
print(t.max(dim=0)) # Returns two values: max and argmax
print('Max: ', t.max(dim=0)[0])
print('Argmax: ', t.max(dim=0)[1])
print(t.max(dim=1))
print(t.max(dim=-1))
느낀 점
- 컴퓨터 비전과 자연어 처리 분야에서 3D 텐서가 어떤 요소로 구성되는지 배웠다.
- 비슷한 1D array와 2D array를 NumPy와 PyTorch로 각각 분석해 볼 수 있어서 좋았다.
- Broadcasting에서 동일한 크기의 행렬로 자동 변환되는 것이 유용하다고 느꼈지만, 동시에 에러가 안 나기 때문에 잘못된 연산을 수행하는 것은 아닌지 잘 확인해야겠다고 느꼈다.
*참고 자료
모두를 위한 딥러닝 시즌2 - PyTorch: [PyTorch] Lab-01-1 Tensor Manipulation 1