본문 바로가기

부스트캠프 AI Tech/Pytorch

(17)
[07] apply PyTorch를 사용하면서 Pretrained된 모델을 많이 사용하게 될텐데 모델 자체에 버그가 있거나, 혹은 수정해서 써야만 하는 등의 사항들이 발생할 수 있다. 이런 경우 전 포스팅 했던 hook이나 apply 등을 이용하여 모델을 수정 할 수 있다. apply 입력으로 받는 모든 module을 순차적으로 처리한다. (1) apply를 활용해 parameter(W)를 1로 초기화하는 함수를 구현해보자 model = Model() # pply를 이용해 모든 Parameter 값을 1로 초기화 def weight_initialization(module): module_name = module.__class__.__name__ for param in module.parameters(): # param da..
[06] Pytorch의 hook hook이 뭘까요 ?? from torch import nn class Model(nn.Module): def __init__(self): super().__init__() def module_hook(grad): pass model_obj = Model() model_obj.__dict__ # {'training': True, # '_parameters': OrderedDict(), # '_buffers': OrderedDict(), # '_non_persistent_buffers_set': set(), # '_backward_hooks': OrderedDict(), # '_is_full_backward_hook': None, # '_forward_hooks': OrderedDict(), # '_for..
[05] named_children, named_modules. import torch from torch import nn from torch.nn.parameter import Parameter # Function class Function_A(nn.Module): def __init__(self, name): super().__init__() self.name = name def forward(self, x): x = x * 2 return x class Function_B(nn.Module): def __init__(self): super().__init__() self.W1 = Parameter(torch.Tensor([10])) self.W2 = Parameter(torch.Tensor([2])) def forward(self, x): x = x / sel..
[04] nn.parameter nn.Module 에서 parameter 정의하기 linear transformation인 Y = XW + b 에 대해서 W,b 를 어떻게 만들까?? nn.Module안에 미리 만들어진 tensor들을 보관 가능 -> Parameter tensor를 안쓰고 Parameter 사용하는 이유 : 아래에 나와용 보통은 torch.nn에 구현된 layer들을 가져다 쓰기 때문에 Parameter를 직접 다루는 경우는 직접 layer를 작성하지 않는 이상 사용할 일이 거의 없음 import torch from torch import nn from torch.nn.parameter import Parameter class Linear(nn.Module): def __init__(self, in_features, o..
[03] nn.Module 이해하기 pytorch documentation https://pytorch.org/docs/stable/index.html PyTorch documentation — PyTorch 1.10.1 documentation Shortcuts pytorch.org index select >>> x = torch.randn(3, 4) >>> x tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], [-0.4664, 0.2647, -0.1228, -1.1068], [-1.1734, -0.6571, 0.7230, -0.6004]]) >>> indices = torch.tensor([0, 2]) >>> torch.index_select(x, 0, indices) tensor([[ 0.1427, 0...
[02] Pytorch Basics Tensor 다차원 Arrays를 표현하는 pytorch 클래스 사실상 numpy의 ndarray와 동일 ( = 텐서프로 Tensor와 동일 ) import numpy as np n_array = np.arange(10) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) n_array = n_array.reshape(2,5) print("ndim :", n_array.ndim, "shape :", n_array.shape) #ndim : 2 shape : (2, 5) import torch t_array = torch.FloatTensor(n_array) print("ndim :", t_array.ndim, "shape :", t_array.shape) # ndim : 2 shape..
[01] Introduction (Pytorch vs Tensorflow) Pytorch Numpy 구조를 가지는 Tensor 객체로 array 표현 자동미분을 지원하여 DL 연산 지원 다양한 형태의 DL을 지원하는 함수와 모델을 지원함 Define by Run. 실행을 하면서 그래프를 생성하는 방식 -> 즉시 확인 가능한 pythonic code 사용하기 편한 장점이 크다 TF의 장점 : production과 scalability