본문 바로가기

코딩/PyTorch

(10)
[Introduction to PyTorch] Building Models Building Models in PyTorchtorch.nn.Module and torch.nn.ParameterModule class는 모델과 모델 구성 요소들을 포함Parameter class는 learning weights들을 표현두 개의 linear layer와 하나의 activation function, 그리고 softmax로 구성된 모델import torchclass TinyModel(torch.nn.Module): def __init__(self): super(TinyModel, self).__init__() self.linear1 = torch.nn.Linear(100, 200) self.activation = torch.nn.ReLU() ..
[Introduction to PyTorch] Autograd What Do We Need Autograd for?Tensor가 거쳐가는 모든 계산 과정을 기록해 chain rule과 backpropagation에 사용 Simple Examplerequires_grad=True로 설정한 tensor는 autograd를 사용a = torch.linspace(0., 2. * math.pi, steps=25, requires_grad=True)b = torch.sin(a)print(b)Outputtensor([ 0.0000e+00, 2.5882e-01, 5.0000e-01, 7.0711e-01, 8.6603e-01, 9.6593e-01, 1.0000e+00, 9.6593e-01, 8.6603e-01, 7.0711e-01, 5.0..
[Introduction to PyTorch] Tensors Creating Tensorsx = torch.empty(3, 4)# memeory allocate만 하고 값 초기화 xzeros = torch.zeros(2, 3)# 0.으로 초기화ones = torch.ones(2, 3)# 1.으로 초기화torch.manual_seed(1828)random = torch.rand(2, 3)# 랜덤 값으로 초기화random2 = torch.rand(2, 3)# 이 값은 manual_seed에 영향 받지 않음 Tensor Shapestorch.*_like() 함수로 같은 shape을 가진 tensor를 만들 수 있음empty_like_x = torch.empty_like(x)zeros_like_x = torch.zeros_like(x)... torch.tensor로 직접..
[PyTorch] Save and Load the Model 이 글에서는 모델의 상태를 저장하고 불러오는 방법을 소개한다.import torchimport torchvision.models as models Save and Loading Model WeightsPyTorch 모델은 학습된 parameter들을 state_dict라 불리는 내부 dictionary에 저장한다. 이 dictionary는 torch.save 함수로 저장될 수 있다.model = models.vgg16(weights='IMAGENET1K_V1')torch.save(model.state_dict(), 'model_weights.pth') 저장된 모델 weight들을 불러오기 위해서는 같은 모델의 객체를 만든 후 load_state_dict() 함수를 사용해 parameter들을 불러온다. ..
[PyTroch] Optimizing Model Parameters 이번 글에서는 data를 사용해 모델 parameter들을 최적화 하는 방법을 소개한다. 모델을 학습은 반복 과정이다. 각 iteration에서 모델은 output의 예측값을 만들고, 에러를 계산하고 (loss), 각 parameter에 대해 미분값을 계산하고, parameter들을 gradient descent 방법을 사용해 최적화한다. Prerequisite CodeDatasets & DataLoaders와 Build Model 섹션의 코드이다.import torchform torch import nnfrom troch.utils.data import DataLoaderfrom torchvision import datasetsfrom torchvision.transform import ToTensor..
[PyTorch] Automatic Differentiation with torch.autogrid Neural network를 학습할 때 가장 많이 사용되는 알고리즘은 back propagation이다. 이 알고리즘에서는 parameter들이 loss function의 parameter에 대한 gradient에 따라 조절된다.이런 gradient를 계산하기 위해서 PyTorch에서는 내재된 differentiation 엔진인 torch.autograd를 사용한다. 아래 예제에서는 input x, parameters w와 b, 그리고 loss 함수를 사용하는 가장 간단한 one-layer neural network를 보여준다.import torchx = torch.ones(5) # input tensory = torch.zeros(3) # expected outputw = torch.randn(5,..
[PyTorch] Build the Neural Network Neural Networks는 데이터에 작업을 하는 layer와 모듈로 이루어져있다. torch.nn namespace는 사용저 정의 neural network를 만드는데 필요한 기본 구성 요소들을 제공한다. PyTorch에 있는 모든 모듈은 nn.Module의 subclass로 정의된다. Neural network란 다른 모듈들로 구성되어 있는 하나의 모듈이다. 아래 예제에서는 FashionMNIST 데이터셋 이미지들을 classify하기 위한 neural network를 만든다.import osimport torchfrom torch import nnform torch.utils.data import DataLoaderfrom torchvision import datasets, transforms G..
[PyTorch] Transforms Data는 항상 machine learning 알고리즘에 사용되는 정재된 형태로 존재하지 않는다. 따라서 transforms를 활용해 데이터를 조정하고자 한다. 모든 TrochVision 데이터셋은 transformation logic이 포함된 callables를 받는 두 개의 parameter가 존재한다.transform: feature를 바꿀 때 사용target_transform: label을 바꿀 때 사용torchvision.transforms 모듈은 자주 사용되는 transforms를 제공한다. FashionMNIST 데이터셋의 feature들은 PIL 이미지 형식이고 label들은 integer이다. 학습을 위해서 feature들은 normalized tensor로, label들은 one-hot..