Post

[Deep Learning Basic] 01_ 파이토치 시작하기

✏️ Edit
[Deep Learning Basic] 01_ 파이토치 시작하기

아나콘다 설치

  • 아나콘다

    파이썬의 버전 관리 및 여러가지 패키지가 포함되어 있는 파이썬 배포판

    • 가상 환경 구축에도 사용 가능

파이토치

손쉽게 인공 신경망 모델을 만들고 이용할 수 있도록 지원하는 딥러닝 프레임워크

Tensor Data Types
  • Pytorch 텐서는 Python의 number 및 ndarray를 일반화한 데이터 구조

  • dtype: 파이토치로 다루고 있는 데이터 타입
  • CPU tensor: CPU에 올라갈 수 있는 데이터
  • GPU tensor: GPU에 올라갈 수 있는 데이터
Numpy array와 Pytorch tensor의 차이
Numpy arrayPytorch tensor
더 빠른 수학 연산 지원을 위한 numpy 패키지의 핵심 기능CUDA 지원 nvidiaGPU에서도 작동
기계 학습 알고리즘에 사용무거운 행렬 계산이 필요한 딥 러닝에 사용
-- devices_type(계산이 CPU/GPU 중 발생 여부) 및required_grad(도함수 계산)- 동적 계산 그래프 제공

reshape

 viewreshape
메모리단순 형태 변환
-> 메모리 낭비 없음
변환된 tensor를 메모리에 새로 생성
-> 메모리 낭비 있을 수 있음
contiguouscontiguous할 때만 사용 가능contiguous하지 않아도 사용 가능
  • transpose() : 전치행렬로 만들기

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    x
    
    # tensor([[-1.8029, -1.3590, -1.4649, -1.0168],
    #        [-0.9942,  0.5742, -0.4503,  0.4360],
    #        [ 1.9558,  0.4027,  0.5425, -1.2490],
    #        [-0.2884, -1.0451, -1.3425, -1.3281]])
    
    x.transpose(0, 1)
    
    # tensor([[-1.8029, -0.9942,  1.9558, -0.2884],
    #      [-1.3590,  0.5742,  0.4027, -1.0451],
    #      [-1.4649, -0.4503,  0.5425, -1.3425],
    #      [-1.0168,  0.4360, -1.2490, -1.3281]])
    
    x.transpose(0, 1).is_contiguous()
    # False
    
    x.transpose(0, 1).reshape(-1, 8)
      # tensor([[ 0.4818, -1.4290,  1.0269, -2.1406, -1.4894,  0.4422,  0.1748, -0.4759],
      # [ 1.1382,  0.0083,  1.0608,  0.3250,  1.0241, -1.3616,  0.7267, -1.3040]])
    x.transpose(0, 1).view(-1, 8)
     #---------------------------------------------------------------------------
     #RuntimeError                              Traceback (most recent call last)
     #<ipython-input-63-56f6b0949c01> in <cell line: 1>()
     #----> 1 x.transpose(0, 1).view(-1, 8)
     #
     #RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.