참고자료
다양한 DeepLearning Framework 가 나와있다.
Define and Run
)scalability
)Define by Run
)numpy
+ AutoGrad
+ Function
GOAL
- 데이터들의 연산을 위한 Tensor 사용법
- 자동 미분기능 AutoGrad 학습
- Tensor를 학습하여 Custom Network 를 작성할 수 있는 기본 지식 익히기
- AutoGrad 작동 원리를 배워 backward 함수의 내부 동작 확인하기
torch.cuda.DoubleTensor
torch.DoubleTensor
"""
numpy - ndarray
"""
import numpy as np
n_array = np.arange(10).reshape(2,5)
print(n_array)
print("ndim : ", n_array.ndim, "shape : ", n_array.shape)
"""
pytorch - tensor with numpy
"""
import torch
t_array = torch.FloatTensor(n_arra)
print(t_array)
print("ndim : ", t_array.ndim, "shape :", t_array.shape)
"""
pytorch - tensor with list
"""
data = [[3,5], [10,5]]
x_data = torch.tensor(data)
x_data
"""
pytorch - tensor with ndarray
"""
nd_array_ex = np.array(data)
tensor_array = torch.from_numpy(nd_array_ex)
tensor_array
data = [[3,5,20], [10,5,50], [1,5,10]]
x_data = torch.tensor(data)
x_data[1:]
# tensor([[10, 5, 50],
[1, 5, 10]] )
x_data[:2,1:]
# tensor([[5, 20],
[5, 50]])
x_data.flatten()
# tensor([3, 5, 20, 10, 5, 50, 1, 5, 10])
torch.ones_like(x_data)
# tensor([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
x_data.numpy()
# array([[3, 5, 20],
[10, 5, 50],
[1, 5, 10]], dtype=int64)
x_data.shape
# torch.Size([3,3])
x_data.dtype
# torch.int64
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)
tensor_ex = torch.rand(size=(2,3,2))
tensor_ex
"""
tensor([[[0.4805, 0.4049],
[0.1574, 0.7056],
[0.8500, 0.5285]],
[[0.9401, 0.4884],
[0.8762, 0.4487],
[0.4005, 0.8982]]])
"""
# 2x3x2 = 12
# 열의 개수가 6으로 정해서 행의 개수는 2로 추정됨
tensor_ex.view([-1,6])
"""
tensor([[0.4805, 0.4049, 0.1574, 0.7056, 0.8500, 0.5285],
[0.9401, 0.4884, 0.8762, 0.4487, 0.4005, 0.8982]])
"""
값이 메모리에 할당 될 때 view 는 값을 연속적으로 표현하는 것을 보장하지만, reshape 은 보장하지 않음
"""
view
"""
a = torch.zeros(3,2)
b = a.view(2,3)
a.fill_(1)
# a와 b 모두 값이 1로 채워져 있다.
"""
reshape
"""
a = torch.zeros(3,2)
b = a.t().reshape(6)
a.fill_(1)
# a는 값이 1로 채워져 있으나, b는 값이 0로 채워져있다.
tensor_ex = torch.rand(size = (2,1,2))
tensor_ex.squeeze()
"""
tensor([[0.2551, 0.2143],
[0.3940, 0.0090]])
"""
tensor_ex = torch.rand(size = (2,2))
tensor_ex.unsqueeze(0).shape # torch.size([1, 2, 2])
print(tensor_ex.unsueeze(0))
"""
tensor([[[0.2083, 0.2474],
[0.9142, 0.2821]]])
"""
tensor_ex.unsqueeze(1).shape # torch.Size([2, 1, 2])
print(tensor_ex.unsqueeze(1))
"""
tensor([[[0.2083, 0.2474]],
[[0.9142, 0.2821]]])
"""
tensor_ex.unsqueeze(2).shape # torch.Size([2, 2, 1])
print(tensor_ex.unsqueeze(2))
"""
tensor([[[0.2083],
[0.2474]],
[[0.9142],
[0.2821]]])
"""
n1 = np.arange(10).reshape(2,5)
t1 = torch.FloatTensor(n1)
t1 + t1
# tensor([[ 0., 2., 4., 6., 8.],
# [10., 12., 14., 16., 18.]])
t1 - t1
# tensor([[0., 0., 0., 0., 0.],
# [0., 0., 0., 0., 0.]])
t1 + 10
# tensor([[10., 11., 12., 13., 14.],
# [15., 16., 17., 18., 19.]])
dot
대신 mm
을 사용dot
: 내적mm
: matrix multiplicationn2 = np.arange(10).reshape(5,2)
t2 = torch.FloatTensor(n2)
t3 = t1.mm(t2)
"""
t1 = tensor([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
t2 = tensor([[0., 1.],
[2., 3.],
[4., 5.],
[6., 7.],
[8., 9.]])
t3 = tensor([[ 60., 70.],
[160., 195.]])
"""
t1.mm(t2)
"""
tensor([[ 60., 70.],
[160., 195.]])
"""
t1.dot(t2)
# RuntimeError
t1.matmul(t2)
"""
tensor([[ 60., 70.],
[160., 195.]])
"""
a = torch.rand(10)
b = torch.rand(10)
a.dot(b)
# tensor(2.2410)
a = torch.rand(10)
b = torch.rand(10)
a.mm(b)
# RuntimeError
a = torch.rand(5,2,3)
b = torch.rand(3)
a.matmul(b) # broadcasting to (5,2,3)
a[0].mm(torch.unsqueeze(b,1)).squeeze()
#
KEY
- squeeze 와 unsqueeze 의 차이 이해
- numpy 와 pytorch 의 유사성
- mm , dot 그리고 matmul 의 차이
예시로 softmax 연산, one_hot encoding 등을 보여준다.
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)
y_label
# tensor([0, 1, 3, 0, 3, 4, 4, 3, 2, 0])
torch.nn.functional.one_hot(y_label)
"""
tensor([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 0]])
"""
import itertools
a = [1, 2, 3]
b = [4, 5]
list(itertools.product(a,b))
# [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
tensor_a = torch.tensor(a)
tensor_b = torch.tensor(b)
torch.cartesian_prod(tensor_a,tensor_b)
"""
tensor([[1, 4],
[1, 5],
[2, 4],
[2, 5],
[3, 4],
[3, 5]])
"""
자동 미분 지원 : backward
함수
일반적으로 Linear 같은 함수를 사용하는데, 함수들은 기본적으로 `requires_grad 값이 True 로 되어 있다.
w = torch.tensor(2.0, requires_grad = True )
y = w**2
z = 10*y + 25
z.backward()
w.grad
참고
backward의 argument로 전달된 gradient는 값을 전달한 것으로 , 의 기울기를 outut tensor 의 shape 과 동일한 형태로 전달 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.])
이번 강의에선 Jupyter 노트북을 사용하는 것을 넘어서기 위해 PyTorch 학습 프로젝트 구성에 대해 학습합니다. OOP와 모듈의 개념을 통해 프로젝트를 구성하는 방법과 PyTorch에서 구성되는 모듈들을 함께 살펴봅니다.
기본적인 PyTorch 사용법과 함께 VSCode와 SSH로 연결해서 Colab을사용하는 방법등 딥러닝 학습을 위해 환경을 구축하는 방법도 다룹니다.
GOAL
- PyTorch 학습 프로젝트 구성
- OOP 와 모듈의 개념을 이용해 프로젝트를 구성하는 방법
- PyTorch 에서 구성되는 모듈 살펴보기
- 기본적인 PyTorch 사용법, VSCode 와 SSH 로 연결해서 Colab을 사용하는 방법 등 딥러닝 학습을 위해 환경을 구축하는 방법
초기 단계
: 대화식 개발 과정이 유리배포 및 공유 단계
: notebook 공유에 어려움이 있음Week1 Python 강의에서 anaconda 사용을 추천받았다.
아래 내용에 대한 환경 설정을 해보자!
- anaconda 환경에서 pytorch 설정
- git clone 하여 template 구조 확인
- vscode 에서 ssh 연결을 통해 colab 코드 확인
# 새로운 가상환경
conda create -n torch_practice python==3.8
# 가상환경 리스트
conda env list
# 가상환경 삭제
conda env remove -n 가상환경이름
# 가상환경 접속
conda activate torch_practice
conda install tensorflow
conda install pytorch
git clone https://github.com/victoresque/pytorch-template
# clone 한 folder 내에서 실행
python3 new_project.py MyProject
cd MyProject
code . # vscode 실행
프로젝트의 환경을 requirement.txt 로 저장할 수 있다.
위에서 clone 한 template project 에도 requirements.txt 가 포함되어 있기 때문에 패키지 파일들을 모두 설치해주자.
# 현재 가상환경에 깔려있는 라이브러리 버전확인
conda list
# 가상환경 내보내기
conda env export > conda_requirements.txt
# 가상환경 설치하기
conda env create -f conda_requirements.txt
# pip install list 내보내기
pip freeze > requirements.txt
# pip 환경 구축하기
pip install -r requirements.txt
module 'distutils' has no attribute 'version'
pip uninstall setuptools
pip install setuptools==59.5.0
python train.py -c config.json
checklist
- Runtime 설정이 GPU 로 되어 있는지 확인하기
- Google Drive 에 연결하여 사용하기
- SSH 로 VSCode 와 연결하기
# torch 설치
!pip3 install torch
!pip3 install torchvision
# google drive mount
from google.colab import drive
drive.mount('/content/drive')
# template clone
!git clone https://github.com/victoresque/pytorch-template
%cd /content/pytorch-template
!python new_project.py MNIST-example
NGROK_TOKEN = '' # ngrok 토큰
PASSWORD = '' # 비밀번호 설정
!pip install colab-ssh
from colab_ssh import launch_ssh
launch_ssh(NGROK_TOKEN, PASSWORD)
"""
Host google_colab_ssh
HostName 0.0.0.0
User root
Port 11111
"""
ssh root@HostName -p Port
cd content/drive/MyDrive/workspace # mount된 drive 폴더로 이동
cp -r /content/pytorch-template ./
factory pattern 으로 구현되어 있음
__getitem__
: index 를 이용하여 값을 가져올 수 있다. config 파일에 쉽게 접근할 수 있도록 도와줌class Test(object):
def __getitem__(self, items):
print (type(items), items)
# Driver code
test = Test()
test[3]
test[3:63:3]
"""
<class 'int'> 5
<class 'slice'> slice(5, 65, 5)
"""
이 글은 커넥트 재단 Naver AI Boost Camp 교육자료를 참고했습니다.