웹 개발 메모장

1. Pytorch 소개 본문

옛날../pytorch

1. Pytorch 소개

도로롱주 2019. 7. 21. 22:35

 

Pytorch 소개

다음의 목표를 가진 파이썬 기반의 Scientific Computing 패키지입니다.

  • Numpy의 연산을 GPU로 가속화 시키도록 하는 것
  • 딥러닝 연구에 있어서 개발을 좀 더 유연하고 빠르게 할 수 있도록 하는 것

Tensorflow와 Pytorch의 특징을 비교한 표

구분 Tensorflow Pytorch
패러다임 Define and Run Define by Run
그래프 형태 Static graph Dynamic graph
현재 사용자 많음 적음
자체 운영 포럼 없음 있음
한국 사용자 모임 Tensorflow Korea(TF-KR) Pytorch Korea(Pytorch-KR)

Torch의 Tensor

  • Tensor는 pytorch의 자료형으로 다차원 행렬을 뜻합니다.
  • Tensor는 간단한 명령어를 통해 GPU로 연산을 수행하게 만들 수 있습니다.
    ( .cuda()만으로도 GPU로 연산 )
  • Tensor의 종류
Data type CPU tensor GPU tensor
32-bit floating point torch.FloatTensor torch.cuda.FloatTensor
64-bit floating point torch.DoubleTensor torch.cuda.DoubleTensor
16-bit floating point torch.HalfTensor torch.cuda.HalfTensor
8-bit integer (unsigned) torch.ByteTensor torch.cuda.ByteTensor
8-bit integer (signed) torch.CharTensor torch.cuda.CharTensor
16-bit integer (signed) torch.ShortTensor torch.cuda.ShortTensor
32-bit integer (signed) torch.IntTensor torch.cuda.IntTensor
64-bit integer (signed) torch.LongTensor torch.cuda.LongTensor

표 출처: https://pytorch.org/docs/1.0.1/tensors.html

Tensor의 선언

  • torch.Tensor()
    초기화 되지 않은 Tensor를 생성할 수 있습니다.

    >>> import torch
    >>> x = torch.Tensor(3)
    >>> x
    tensor([-6.7794e-18,  4.5911e-41, -6.7794e-18])
    >>> import torch
    >>> x2 = torch.Tensor(2,3)
    >>> x2
    tensor([[0.0000e+00, 0.0000e+00, 1.4013e-45],
            [0.0000e+00, 1.4013e-45, 0.0000e+00]])
  • torch.rand()
    0~1 사이의 uniform distribution random 값으로 선언됩니다.
    (uniform distribution: 모든 값들이 균등하게 분포)

    >>> x = torch.rand(3,3)
    >>> x
    tensor([[0.8071, 0.6329, 0.2046],
          [0.3110, 0.4620, 0.8716],
          [0.9628, 0.7128, 0.0568]])
  • torch.randn()
    0~1 사이의 normal distribution random 값으로 선언됩니다.
    (normal distribution: 평균이 0이고, 분산이 1인 정규 분포)

    >>> x = torch.randn(3,3)
    >>> x
    tensor([[ 1.1694,  0.5604,  1.4982],
          [ 1.1862, -0.7028, -0.8766],
          [-1.1688, -0.3944,  0.0273]])

Numpy To Tensor

  • torch.Tensor()
    Tensor 선언할 때, 아까와 달리 크기 대신에 numpy를 넣어주면 Tensor를 반환합니다.

    >>> import torch
    >>> import numpy as np
    >>> x = np.array([1,2,3,4])
    >>> x = torch.Tensor(x)
    >>> x
    tensor([1., 2., 3., 4.])

Tensor To Numpy

  • torch.Tensor()
    numpy() 메소드 호출 만으로 numpy를 반환할 수 있습니다.

    >>> import torch
    >>> import numpy as np
    >>> x = torch.Tensor(2,4)
    >>> x = x.numpy()
    >>> x
    array([[0.      , 1.984375, 0.      , 2.      ],
         [0.      , 2.015625, 0.      , 2.03125 ]], dtype=float32)

Tensor의 view

  • .view()
    배열의 형태를 reshape 해주는 메소드입니다.

    >>> x = torch.Tensor(2,3)
    >>> x
    tensor([[0.2592, 0.3854, 0.7369],
          [0.5642, 0.6126, 0.4776]])
    >>> x.view(1,6)
    tensor([[0.2592, 0.3854, 0.7369, 0.5642, 0.6126, 0.4776]])
    >>> x.view(1,1,2,3)
    tensor([[[[0.2592, 0.3854, 0.7369],
            [0.5642, 0.6126, 0.4776]]]])

Tensor의 cat

  • torch.cat((Tensor_A, Tensor_B), dim)
    Tensor_A와 Tensor_B를 dim(차원)에 맞춰서 합쳐줍니다.

    >>> x = torch.Tensor(np.array([[1,2,3], [4,5,6]]))
    >>> x2 = torch.Tensor(np.array([[10,20,30], [40,50,60]]))
    >>> x3 = torch.cat((x,x2), 0)
    >>> x3
    tensor([[ 1.,  2.,  3.],
          [ 4.,  5.,  6.],
          [10., 20., 30.],
          [40., 50., 60.]])
    >>> x3 = torch.cat((x,x2), 1)
    >>> x3
    tensor([[ 1.,  2.,  3., 10., 20., 30.],
          [ 4.,  5.,  6., 40., 50., 60.]])

Tensor의 GPU 연산

  • .cuda()
    GPU 연산을 하도록 하는 텐서를 반환합니다.

    import torch
    import numpy as np   
    
    x = torch.Tensor(np.array(\[\[1.,2.\]\]))  
    y = torch.Tensor(np.array(\[\[1.,2.\]\]))
    
    if torch.cuda.is\_available():  
    x = x.cuda()  
    y = y.cuda()
    
    sum = x+y  
    print(sum)

참고: 김군이(https://www.youtube.com/watch?v=VKhFeh92eps)

Comments