Py Torch
Py Torch
Follow
1 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
import numpy as np
2 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
.data .grad
import torch
from torch.autograd import Variable
# define an inputs
x_tensor = torch.randn(10, 20)
y_tensor = torch.randn(10, 5)
x = Variable(x_tensor, requires_grad=False)
y = Variable(y_tensor, requires_grad=False)
# define some weights
w = Variable(torch.randn(20, 5), requires_grad=True)
loss = torch.mean((y - x @ w) ** 2)
3 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
from torch.autograd import Variable
import torch.nn.functional as F
learning_rate = 0.1
loss_fn = torch.nn.MSELoss()
optimizer = torch.optim.SGD([w1, w2], lr=learning_rate)
for step in range(5):
pred = F.sigmoid(x @ w1)
pred = F.sigmoid(pred @ w2)
4 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import tensorflow as tf
first_counter = tf.constant(0)
second_counter = tf.constant(10)
some_value = tf.Variable(15)
import torch
first_counter = torch.Tensor([0])
second_counter = torch.Tensor([10])
some_value = torch.Tensor(15)
nn
nn
5 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch.nn as nn
nn.Module
class Model(nn.Module):
def __init__(self):
super().__init__()
self.feature_extractor = nn.Sequential(
nn.Conv2d(3, 12, kernel_size=3, padding=1, stride
nn.Conv2d(12, 24, kernel_size=3, padding=1, stride
)
self.second_extractor = nn.Conv2d(
24, 36, kernel_size=3, padding=1, stride=1)
__init__
6 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
forward
7 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
class MyFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
output = torch.sign(input)
return output
@staticmethod
def backward(ctx, grad_output):
# saved tensors - tuple of tensors, so we need get first
input, = ctx.saved_variables
grad_output[input.ge(1)] = 0
grad_output[input.le(-1)] = 0
return grad_output
# usage
ctx
self.save_for_backward(input)
input, _ = self.saved_tensors
.cuda()
.cuda()
.cpu()
8 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
import torch
9 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
class Trainer:
def __init__(self, model, use_cuda=False, gpu_idx=0):
self.use_cuda = use_cuda
self.gpu_idx = gpu_idx
self.model = self.to_gpu(model)
torch.nn.init
10 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
from torch.autograd import Variable
requires_grad volatile
11 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
from torch.autograd import Variable
# requires grad
# If theres a single input to an operation that requires gradient,
# its output will also require gradient.
x = Variable(torch.randn(5, 5))
y = Variable(torch.randn(5, 5))
z = Variable(torch.randn(5, 5), requires_grad=True)
a = x + y
a.requires_grad # False
b = a + z
b.requires_grad # True
# scheduler example
from torch.optim import lr_scheduler
12 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch.nn as nn
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1, 20, 5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20, 64, 5)),
('relu2', nn.ReLU())
]))
print(model)
# Sequential (
# (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
# (relu1): ReLU ()
# (conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
# (relu2): ReLU ()
state_dict()
13 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
torch.utils.data.Dataset
14 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
import torch
import torchvision as tv
class ImagesDataset(torch.utils.data.Dataset):
def __init__(self, df, transform=None,
loader=tv.datasets.folder.default_loader):
self.df = df
self.transform = transform
self.loader = loader
target = row['class_']
path = row['path']
img = self.loader(path)
if self.transform is not None:
img = self.transform(img)
def __len__(self):
n, _ = self.df.shape
return n
torchvision.transforms.ToTensor()
15 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
async=True
cuda()
pin_memory=True
16 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
class ImagesDataset(torch.utils.data.Dataset):
pass
class Net(nn.Module):
pass
model = Net()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
scheduler = lr_scheduler.StepLR(optimizer, step_size=30, gamma
criterion = torch.nn.MSELoss()
dataset = ImagesDataset(path_to_images)
data_loader = torch.utils.data.DataLoader(dataset, batch_size
train = True
for epoch in range(epochs):
if train:
lr_scheduler.step()
17 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
18 of 19 10/6/2017, 10:01 PM
PyTorch tutorial distilled Towards Data Science Medium https://medium.com/towards-data-science/pytorch-tutorial-distilled-95ce...
19 of 19 10/6/2017, 10:01 PM