In [205]:
from __future__ import print_function
import torch
In [206]:
x = torch.empty(5,3)
print(x)
In [207]:
x = torch.rand(5,3)
print(x)
In [208]:
x = torch.zeros(5,3,dtype=torch.long)
print(x)
In [209]:
x = torch.tensor([5.5,3])
print(x)
In [210]:
x = x.new_ones(5,3,dtype=torch.double) #new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same size
In [211]:
#Get its size:
print(x.size())
In [212]:
#syntax 1
y = torch.rand(5,3)
print(x + y)
In [213]:
#syntax 2
print(torch.add(x,y))
In [214]:
#providing an output tensor as argument
result = torch.empty(5,3)
torch.add(x,y,out=result)
print(result)
In [215]:
#in-place
#add x to y
y.add_(x)
print(y)
#Any operation that mutates a tensor in-place is post-fixed with an _.
#For example: x.copy_(y), x.t_(), will change x.
In [216]:
#You can use standard NumPy-like indexing with all bells and whistles!
print(x[:,1])
In [217]:
#Resizing: If you want to resize/reshape tensor, you can use torch.view:
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
In [218]:
#If you have a one element tensor, use .item() to get the value as a Python number
x = torch.randn(1)
print(x)
print(x.item())
In [219]:
a = torch.ones(5)
print(a)
In [220]:
b = a.numpy()
print(b)
In [221]:
#See how the numpy array changed in value.
a.add_(1)
print(a)
print(b)
In [222]:
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1,out=a)
print(a)
print(b)
In [223]:
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
In [224]:
x = torch.ones(2,2,requires_grad = True)
print(x)
In [225]:
y = x + 2
print(y)
In [226]:
print(y.grad_fn) #y was created as a result of an operation, so it has a grad_fn.
In [227]:
z = y*y*3
out = z.mean()
print(z, out)
In [228]:
a = torch.randn(2,2)
a = ((a*3)/(a-1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a*a).sum()
print(b.grad_fn)
In [229]:
out.backward()
In [230]:
print(x.grad)
In [231]:
x = torch.randn(3,requires_grad = True)
y = x*2
while y.data.norm() < 1000:
y = y*2
print(y)
In [232]:
y
Out[232]:
In [233]:
y.data.norm()
Out[233]:
In [234]:
0.7772*0.7772+0.5340*0.5340+4.4317*4.4317
Out[234]:
In [235]:
4.5309*4.5309
Out[235]:
In [236]:
gradients = torch.tensor([0.1,1.0,0.001],dtype=torch.float)
y.backward(gradients)
print(x.grad)
In [237]:
print(x.requires_grad)
print((x**2).requires_grad)
with torch.no_grad():
print((x**2).requires_grad)
In [238]:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),(2))# If the size is a square you can only specify a single number
x = x.view(-1,self.num_flat_features(x))
x = F.relu((self.fc1(x)))
x = F.relu((self.fc2(x)))
x = self.fc3(x)
return x
def num_flat_features(self,x):
size = x.size()[1:]# all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
In [239]:
params = list(net.parameters())
print(len(params))
print(params[0].size())# conv1's .weight
In [240]:
for i in range(len(params)):
print(i,params[i].size())
In [241]:
input = torch.randn(1,1,32,32)
out = net(input)
print(out)
In [242]:
net.zero_grad()
out.backward(torch.randn(1,10))
In [243]:
output = net(input)
target = torch.randn(10)
target = target.view(1,-1)
criterion = nn.MSELoss()
loss = criterion(output,target)
print(loss)
In [244]:
print(loss.grad_fn)# MSELoss
print(loss.grad_fn.next_functions[0][0])# Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
In [245]:
net.zero_grad()# zeroes the gradient buffers of all parameters
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
In [246]:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
In [247]:
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(),lr=0.01)
#in your training loop:
optimizer.zero_grad()#zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() #does the update
In [248]:
import torch
import torchvision
import torchvision.transforms as transforms
In [249]:
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download = True, transform = transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform = transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'forg', 'horse', 'ship', 'truck')
In [250]:
import matplotlib.pyplot as plt
import numpy as np
def imshow(img):
img = img/2 + 0.5 #unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1,2,0)))
#get some random traning images
dataiter = iter(trainloader)
images, labels = dataiter.next()
#show images
imshow(torchvision.utils.make_grid(images))
#print labels
print(''.join('%5s' % classes[labels[j]] for j in range(4)))
In [251]:
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5,120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self,x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16*5*5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
In [252]:
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum = 0.9)
In [253]:
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
#get inputs
inputs, labels = data
#zero the params gridents
optimizer.zero_grad()
#forward,backward,optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
#print statistic
running_loss += loss.item()
if i%2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss /2000))
running_loss = 0.0
print('Finished Trianing')
In [262]:
dataiter = iter(testloader)
images, labels = dataiter.next()
#print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth:', ' '.join('%5s'%classes[labels[j]] for j in range(4)))
In [263]:
#Okay, now let us see what the neural network thinks these examples above are:
outputs = net(images)
In [264]:
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
In [265]:
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(output.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
In [266]:
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
iamges, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
In [259]:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assume that we are on a CUDA machine, then this should print a CUDA device:
print(device)
In [260]:
net.to(device)
Out[260]:
In [261]:
inputs, labels = inputs.to(device), labels.to(device)
In [ ]: