In [1]:
import torch
import torchvision
import torch.nn as nn
import torch.utils.data as data
import numpy as np
import torchvision.transforms as transforms
import torchvision.datasets as dsets
from torch.autograd import Variable
In [2]:
# random normal
x = torch.randn(5, 3)
print (x)
In [3]:
# build a layer
linear = nn.Linear(3, 2)
In [5]:
# Sess weight and bias
print (linear.weight)
print (linear.bias)
print(linear)
In [6]:
# forward propagate
y = linear(Variable(x))
print (y)
In [7]:
# convert numpy array to tensor
a = np.array([[1,2], [3,4]])
b = torch.from_numpy(a)
print (b)
In [18]:
# Image Preprocessing
transform = transforms.Compose([
transforms.Scale(40),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32),
transforms.ToTensor()])
In [14]:
# download and loading dataset f
train_dataset = dsets.CIFAR10(root='./data/',
train=True,
transform=transform,
download=True)
image, label = train_dataset[0]
print (image.size())
print (label)
In [16]:
# data loader provides queue and thread in a very simple way
train_loader = data.DataLoader(dataset=train_dataset,
batch_size=100,
shuffle=True,
num_workers=2)
In [ ]:
# iteration start then queue and thread start
data_iter = iter(train_loader)
# mini-batch images and labels
images, labels = data_iter.next()
for images, labels in train_loader:
# your training code will be written here
pass
In [25]:
class CustomDataset(data.Dataset):
def __init__(self):
pass
def __getitem__(self, index):
# You should build this function to return one data for given index
pass
def __len__(self):
pass
In [26]:
custom_dataset = CustomDataset()
data.DataLoader(dataset=custom_dataset,
batch_size=100,
shuffle=True,
num_workers=2)
In [17]:
# Download and load pretrained model
resnet = torchvision.models.resnet18(pretrained=True)
In [ ]:
# delete top layer for finetuning
sub_model = nn.Sequentialtial(*list(resnet.children()[:-1]))
# for test
images = Variable(torch.randn(10, 3, 256, 256))
print (resnet(images).size())
print (sub_model(images).size())
In [ ]:
# Save and load the trained model
torch.save(sub_model, 'model.pkl')
model = torch.load('model.pkl')