뉴비에욤

PyTorch 튜토리얼 1 - PyTorch란? 본문

Machine Learning/PyTorch

PyTorch 튜토리얼 1 - PyTorch란?

초보에욤 2018. 4. 30. 14:54

2017/07/13 - [Machine Learning/PyTorch] - 윈도우 10 PyTorch 환경 구성 - 설치



원문 : http://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html#



* 17년도 07월에 초번 번역 후, 파이토치 최신 버전인 0.4.0에 맞추어 갱신 된 번역본

* 최근 갱신일 : 2018-04-30



목 차 ( 초보자 튜토리얼 )

A. 파이토치와 함께하는 딥러닝 : 60분만에 끝장내기!

1. 파이토치란?

- 시작하기

- 텐서

- 연산

- NumPy 변환

토치 텐서를 NumPy 배열로 변경

NumPy 배열을 토치 텐서로 변경

- CUDA 텐서





파이토치란? ( What is PyTorch? )


파이썬을 기반으로 하는 Scientific Computing 패키지며 크게 2가지 목적을 가진다.

  • GPU를 제대로 이용하기 위한 NumPy의 대체제로 사용
  • 최고의 유연성과 스피드를 제공하는 딥 러닝 연구 플랫폼


시작하기 ( Getting Started )

텐서 ( Tensors )

Tensors는 NumPy의 ndarrays와 유사한것으로 계산 속도를 빠르게 하기 위해 GPU 에서 사용할 수 있는 것이라 보면 된다.
- 소스
from __future__ import print_function 
import torch

초기화 되지 않은 5*3 행렬 생성하기

- 소스

x = torch.empty(5, 3)
print(x)

- 결과

tensor(1.00000e-04 *
       [[-0.0000,  0.0000,  1.5135],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000],
        [ 0.0000,  0.0000,  0.0000]])

랜덤으로 초기화 된 행렬 생성하기
- 소스
x = torch.rand(5, 3)
print(x) 

- 결과

tensor([[ 0.6291,  0.2581,  0.6414],
        [ 0.9739,  0.8243,  0.2276],
        [ 0.4184,  0.1815,  0.5131],
        [ 0.5533,  0.5440,  0.0718],
        [ 0.2908,  0.1850,  0.5297]])

0으로 채워지고 long 데이터 타입을 가지는 행렬 생성하기
- 소스
x = torch.zeros(5, 3, dtype=torch.long)
print(x) 
- 결과
tensor([[ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0]])


데이터로부터 직접 텐서 생성하기

- 소스

x = torch.tensor([5.5, 3])
print(x) 

- 결과

tensor([ 5.5000,  3.0000])


혹은, 이미 존재하는 텐서를 기반으로 새로운 텐서를 생성할 수도 있다. 아래와 같은 방법들은 입력 텐서의 속성(데이터 타입 등)들이 사용자에 의해 새롭게 제공되지 않는 이상 기존의 값들을 사용한다.

- 소스

x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size 

- 결과

tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]], dtype=torch.float64)
tensor([[-0.2183,  0.4477, -0.4053],
        [ 1.7353, -0.0048,  1.2177],
        [-1.1111,  1.0878,  0.9722],
        [-0.7771, -0.2174,  0.0412],
        [-2.1750,  1.3609, -0.3322]])


생성 한 텐서의 사이즈 확인하기

- 소스

print(x.size()) 

- 결과

torch.Size([5, 3])

torch.Size는 파이썬의 자료형이기 때문에 튜플과 관련 된 모든 연산을 지원한다.




연산 ( Operations )


연산은 다양한 문법이 존재하는데 예를 들어 더하기 연산은 다음과 같다.


더하기 : 문법 1

- 소스

y = torch.rand(5, 3)
print(x + y) 

- 결과

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])


더하기 : 문법 2

- 소스

print(torch.add(x, y)) 

- 결과

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])


더하기 : 파라미터로 (결과가 저장되는)결과 텐서(output tensor) 이용

- 소스

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result) 

- 결과

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])


더하기 : 제자리(in-place)

- 소스

# adds x to y
y.add_(x)
print(y) 

- 결과

tensor([[-0.1859,  1.3970,  0.5236],
        [ 2.3854,  0.0707,  2.1970],
        [-0.3587,  1.2359,  1.8951],
        [-0.1189, -0.1376,  0.4647],
        [-1.8968,  2.0164,  0.1092]])

텐서를 제자리에서 변조하는 연산은 _ 문자를 이용하여 postfix(연산자를 피연산자의 뒷쪽에 표시)로 표기한다. 예를 들면, x.copy_(y)x.t_()x를 변경시킨다.



물론 NumPy와 같이 표준 인덱싱을 사용할 수도 있다.

- 소스

print(x[:, 1]) 

- 결과

tensor([ 0.4477, -0.0048,  1.0878, -0.2174,  1.3609])


사이즈 변경(Resizing) : 텐서의 사이즈를 다시 변경하거나, 모양(shape)을 변경하고 싶다면 torch.view를 사용하면 된다.

- 소스

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size()) 

- 결과

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])


1개의 요소를 가지는 텐서(one element tensor)가 있다면, .item()을 이용하여 Python에서의 숫자 데이터처럼 값을 얻을 수 있다.

- 소스

x = torch.randn(1)
print(x)
print(x.item()) 

- 소스결과

tensor([ 0.9422])
0.9422121644020081


전치, 인덱스, 슬라이스, 수학적 계산, 선형 대수학, 랜덤 넘버 등등을 포함하여 100가지 넘는 텐서 연산이 존재하는데 시간이 있다면 다음 링크를 참고하여 관련 연산들을 살펴보기 바란다.

http://pytorch.org/docs/stable/torch.html





NumPy 변환 ( NumPy Bridge )


토치 텐서를 NumPy 배열로 바꾸거나, 반대로 하고 싶은 경우에도 손쉽게 수행할 수 있다.

토치 텐서와 NumPy 배열은 근본적으로 메모리 위치를 공유하기 때문에 하나를 변경하면 다른 하나도 변경된다.



토치 텐서를 NumPy 배열로 변경 ( Converting a Torch Tensor to a NumPy Array)


토치 텐서 생성

- 소스

a = torch.ones(5)
print(a) 

- 결과

tensor([ 1.,  1.,  1.,  1.,  1.])


배열로 변경

- 소스

b = a.numpy()
print(b) 

- 결과

[1. 1. 1. 1. 1.]


numpy 배열의 값이 어떻게 변하는지 살펴보기 바란다.

- 소스

a.add_(1)
print(a)
print(b) 

- 결과

tensor([ 2.,  2.,  2.,  2.,  2.])
[2. 2. 2. 2. 2.]



NumPy 배열을 토치 텐서로 변경 ( Converting NumPy Array to Torch Tensor )


np 배열이 토치 텐서로 어떻게 자동으로 변하는지 살펴보기 바란다.


np 배열 생성 후 텐서로 변경

- 소스

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b) 

- 결과

[2. 2. 2. 2. 2.]
tensor([ 2.,  2.,  2.,  2.,  2.], dtype=torch.float64)


CharTensor를 제외한 CPU 레벨의 모든 텐서는 numpy로 변경할 수 있고 다시 원래로 돌릴수도 있다.




CUDA 텐서 ( CUDA Tensors )

 

텐서는 .to 메소드를 이용하여 (CUDA를 지원하는)그 어떠한 디바이스로도 옮길 수 있다.

- 소스

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together! 

- 결과

tensor([ 1.9422], device='cuda:0')
tensor([ 1.9422], dtype=torch.float64)


Comments