1. PyTorch
1. numpy + autograd
2. numpy의 ndarray와 동일 -> tensorflow의 Tensor와도 동일
3. Tensor 생성 함수도 비슷
2. 실습
1. Tensor 생성
import numpy as np
import torch
# a, b 는 같은 구성의 배열임
a = [[0,1,2,3,4],[5,6,7,8,9]]
b = n_array = np.arange(10).reshape(2,5)
arr1 = torch.FloatTensor(a)
arr2 = torch.FloatTensor(b)
arr3 = torch.tensor(a)
arr4 = torch.tensor(b)
a = np.array(a) # b와 같음
arr5 = torch.from_numpy(a) # torch.from_numpy(b)
print(arr1)
print(arr2)
print(arr3)
print(arr4)
print(arr5)
'''
tensor([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
tensor([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
tensor([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
tensor([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
tensor([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
'''
2. Data Type
기본적으로는 넘파이와 동일하나, GPU를 쓸 수 있는지 없는지에 다라 살짝 다름. GPU 쓸 수 있는 경우 torch.cuda 라는 접두어가 붙음.
3. device
tensor를 GPU에 올릴 것인지, 메모리에 올릴 것인지 확인해주는 property
# GPU에 올라와 있을 때
data.device # device(type='cpu')
# 메모리에 올라와 있을 때
data.deviec # device(type='cuda', index=0)
4. Tensor handling
- view : numpy의 reshape과 비슷. tensor의 shape 변환
- squeeze : 차원의 개수가 1인 차원을 삭제(압축)
- unsqueeze : 차원의 개수가 1인 차원을 추가
- view vs. shape:
1) view : 메모리 할당 시 contiguity(연속성) 보장 -> copy 안함
2) shape : 메모리 할당 시 contiguity(연속성) 보장X -> copy 함
5. squeeze
2*2 행렬 A가 있을 때
A.shape : (2,2)
A.unsqueeze(0) : dim = 0에 차원 추가 -> (1,2,2)
A.unsqueeze(1) : dim = 1에 차원 추가 -> (2,1,2)
A.unsqueeze(2) : dim = 2에 차원 추가 -> (2,2,1)
* numpy에서의 axis가 torch에선 dim임
위의 unsqueeze한 tensor에 대해, squeeze() 실행 시 원래의 tensor A로 돌아옴
6. mm
- 행렬곱 연산 시 torch.mm 사용
- dot은 내적 구할 때만 사용
7. nn.functional
보통 아래와 같이 사용
import torch
import torch.nn.functional as F
8. Autograd
- 자동미분이라는 뜻으로, backward 함수 사용함
- 코드 참고
import torch
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 # tensor([36., 81.])
b.grad # tensor([-12., -8.])
'AI > AITech 3기' 카테고리의 다른 글
[PyTorch] 파이토치 함수 코드 보는 법 (0) | 2022.01.25 |
---|---|
[PyTorch] 3강 PyTorch 프로젝트 구조 이해하기 (0) | 2022.01.24 |
[PyTorch] 1강 Introduction to PyTorch (2) | 2022.01.24 |
[AI Math] 10강 RNN 첫걸음 (0) | 2022.01.23 |
[AI Math] 9강 CNN 첫걸음 (0) | 2022.01.23 |