[PyTorch] PyTorch 기본

Jeonghyun·2022년 9월 26일

PyTorch

목록 보기
1/6

Tensor

  • 다차원 arrays를 표현하는 클래스(객체)
  • numpy와 ndarray와 거의 동일
  • 기본적으로 data 타입은 numpy와 동일

Tensor 생성

import torch
import numpy as np

# data to tensor
data = [[1, 2],[3,5]]
x_data = torch.tensor(data)
# ndarray to tensor
nd_array_ex = np.array(data)
tensor_array = torch.from_numpy(nd_array_ex)

pytorch의 tensor은 gpu에 올려서 사용 가능

x_data.device 
# >>> device(type='cpu')
if torch.cuda.is_avaliable(): 
	x_data_cuda = x_data.to('cuda')
x_data.device 
# >>> device(type='cuda', index = 0)
  • view : reshape와 동일하게 tensor의 shape 변환
    reshape과는 contiguity 보장의 차이
  • squeeze : 차원의 개수가 1인 차원 삭제(압축)
  • unsqueeze : 차원의 개수가 1인 차원 추가

Tensor 연산

  • 기본적인 연산은 numpy와 동일
  • 행렬의 곱셈은 dot이 아닌 mm사용
    t1.mm(t2), t1.matmul(t2)
    matmul은 mm과 다르게 broadcasting 지원

AutoGrad

  • 자동 미분 지원
w = torch.tensor(2.0,requires_grad=True)
y = w ** 2
z = 10 * y + 2
z.backward()
w.grad

Project template

https://github.com/FrancescoSaverioZuppichini/PyTorch-Deep-Learning-Template
https://github.com/PyTorchLightning/deep-learning-project-template
https://github.com/victoresque/pytorch-template

모듈 구성

참고
pytorch 튜토리얼
https://tutorials.pytorch.kr/beginner/blitz/autograd_tutorial.html
autograd
https://gaussian37.github.io/dl-pytorch-gradient/




출처 - 부스트캠프 AI tech 교육자료


[부스트캠프 AI Tech] Week 2 - Day 1

0개의 댓글