pytorch.nn.Module

input, output, Forward, Backward 정의

parameter(tensor) 정의

 

 

대략적인 구조

  • Module 
    • layer
      • function
    • parameter

 

pytorch.nn.Parameter

Tensor 객체의 상속 개체

nn.Module 내에 attribute가 될 때는 required_grad = True로 하습 대상의 되는 Tensor

 

Backward

forward의 결과값 (model의  output = 예측치)과 실제값간의 차이(loss)에 대해 미분을 수행 후 Parameter 업데이트

 

for epoch in range(epochs):
……
# Clear gradient buffers because we don't want any gradient from previous epoch
optimizer.zero_grad()

# get output from the model, given the inputs
outputs = model(inputs)

# get loss for the predicted output
loss = criterion(outputs, labels)

# get gradients w.r.t to parameters
loss.backward()

# update parameters
optimizer.step()
  •  optimizer.zero_grad() - gradient 초기화 -> 다음 epoch 영향 안 미치기 위해
  •  model(input) -> 모델 돌림
  •  loss = criterion(outpus, labels) -> 로스 계산
  •  loss.bacward() -> gradients parameter 계산
  •  optimizer.step() -> 파라미터 업데이트
 

 

pytorch 정리 1

 

대표적으로 사용되는 라이브러리는 PytorchTensorflow다.

 

Tensorflow

  • 구글에서 제공하는 라이브러리이다.
  • Define and run
    • 그래프를 먼저 그리고 난 후에 gradient 계산을 해준다.
    • 이러한 특성으로 인해서 새로운 방식으로 개발할 때에는 불편하게 작용하기도 한다. -> 최근 ai 학회 논문에서 pytorch를 활용한 논문들이 더 많아졌다.
    • Tensorflow 2.x 이후부터는 Pytorch와 같이 Defin by run을 제공하면서 위의 불편함의 개선되었다.
  • Production, 클라우드 연결, multi GPU의 장점이 있다.

 

 

Pytorch

  • 페이스북에서 제공하는 라이브러리이다.
  • Define by run (Dynamic Computation Graph)
    • 실행을 하면서 그때 그때 gradient 를 계산해 준다.
    • 그래프를 먼저 그리지 않고 Dynamic Computation Graph 로 진행하기 때문에 개발하는 과정에서 수정이 용이하다. 이러한 특징으로 최근 ai 학회 논문에서 pytorch를 사용한 논문들이 많이 증가했다.
  • Numpy + Auto Gradient + Function

 

 

Pytorch로 학습하는 이유

  • Defin by Run의 장점 = 즉시 확인 가능 -> pythonic code
  • GPU support, good API and community
  • 사용하기 편한 장점이 크다.
  • Tensorflow는 production 과 scalability의 장점

pytorch , tendorflow 논문 인용 그래프 출처(https://www.exxactcorp.com/blog/Deep-Learning/pytorch-vs-tensorflow-in-2020-what-you-should-know-about-these-frameworks)

pytorch가 CV(Computer Vision) 관련 저널에서 압도적인 상승률을 보이고 있다.

ex)eccv(European Conference on Computer Vision) 


 

Pytorch = Numpy + Auto Gradient + Function

 

  • Numpy  
    • Numpy 라이브러리의 함수 기능들이 많이 사용된다. 다만 torch.view, numpy.reshpae의 차이 등 약간의 차이가 있다. 
    • pytorch에서는 Numpy 형태의 데이터를 Tensor로 사용한다.
  • Function
    • Auto Gradinet를 지원하는 함수와 모델을 지원한다.
  • Auto Gradient 
    • Pytorch 에서 지원하는 자동미분 기능

code

import torch

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)

# 수집된 변화도가 올바른지 확인합니다.
print(9*a**2 == a.grad)
print(-2*b == b.grad)

output

tensor([True, True])
tensor([True, True])

위와 같이 backward function으로 미분을 간단하게 계산하는 것을 확인할 수 있다.

 

 

출처 https://tutorials.pytorch.kr/beginner/pytorch_with_examples.html

 

예제로 배우는 파이토치(PyTorch)

Author: Justin Johnson 번역: 박정환 이 튜토리얼에서는 PyTorch 의 핵심적인 개념을 예제를 통해 소개합니다. 본질적으로, PyTorch에는 두가지 주요한 특징이 있습니다: NumPy와 유사하지만 GPU 상에서 실행

tutorials.pytorch.kr

 

파이썬 정규식 사용

- 문법 자체는 매우 방대하다. -> 기초적인 사용법만 확인

 

Ex) 기초 html 호출 문법 (전화번호, 이메일주소, IP주소 등)

https://zetawiki.com/wiki/%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D_%EC%98%88%EC%8B%9C

 

연습 참고 사이트 

http://www.regexr.com/

 

  • String 에서 숫자 추출 정규식
import re

tmp = "aslkdfjoiweur 12334"

#숫자만 검색하고 싶을 경우

num = re.sub(r'[^\d]', '', input_string)

 

  • Camelcase to underscore or snake case
import re

underscore_str = "___to__camel___case__"

#좌우 값 제거
underscore_str = underscore_str.strip("_").lower()

#중복값 1개로
underscore_str = '_'.join(underscore_str.split("__"))

#(?!^)= 시작하는 단어가 있는데 포함하지 않고/ _([a-zA-Z])=  두 char 를 받는다.group(0) 은 전체 _c group(1) = c
camelcase_str = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), underscore_str)

 

 

회고

re.sub 함수를 활용하면서 새롭게 알게되는 활용법이 어려웠지만 재밌었다.

+ Recent posts