본문 바로가기

분류 전체보기

(131)
[08] backward 과정 이해하기 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..
[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
[08] 베이즈 통계학 조건부 확률 베이즈 통계학의 이해를 위해서는 조건부확률 개념 이해 필요 $$ P(A \cap B) = P(B)P(A|B) $$ 조건부확률 $P(A | B)$는 사건 B가 일어난 상황에서 사건 A가 발생할 확률 $$ P(A|B) = \frac{P(A \cap B)}{P(B)} $$ $P(A|B)$는 A given B 베이즈 정리는 조건부확률을 이용해 정보를 갱신하는 방법 $$ P(A \cap B) = P(B)P(A|B) $$ $$ P(B|A) = \frac{P(A \cap B)}{P(A)} = P(B) \frac{P(A|B)}{P(A)} $$ A라는 새로운 정보가 주어졌을 때, $P(B)$로부터 $P(B|A)$를 계산하는 방법 제공 베이즈 정리 $$ P(\theta | \mathcal{D}) = P(\th..
[07] 통계학 모수 (parameter) 통계적 모델링은 적절한 가정 위에서 확률분포를 추정(inference) 하는 것이 목표이며, 기계학습과 통계학이 공통적으로 추구하는 목표 분포의 종류 매우 다양 → 어떤 확률분포를 사용해 모델링하지? 그러나 유한한 개수의 데이터만 관찰해서 모집단의 분포를 정확하게 알아낸다는 것은 불가능하므로, 근사적으로 확률분포를 추정(예측)할 수 밖에 없다 예측모형의 목적은 분포를 정확하게 맞추는 것보다 데이터와 추정 방법의 불확실성을 고려해 위험을 최소화 하는 것 데이터가 특정 확률분포를 따른다고 선험적으로(a priori) 가정한 후 그 분포를 결정하는 모수(parameter)를 추정하는 방법을 모수적(parametric) 방법론이라고 한다 특정 확률분포를 가정하지 않고 데이터에 따라 모..