<jupyter_start><jupyter_text>60-minute blitzhttp://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html  Getting started  Tensors* Like ndarrays but can be used on GPUs.<jupyter_code>import torch<jupyter_output><empty_output><jupyter_text>* Construct a 5x3 matrix uninitialised.<jupyter_code>x = torch.Tensor(5, 3)
print(x)<jupyter_output>0.0000e+00  2.0000e+00 -7.6443e+22
-1.5849e+29  8.4078e-45  0.0000e+00
 0.0000e+00  0.0000e+00  0.0000e+00
 0.0000e+00  0.0000e+00  0.0000e+00
-7.6398e+22 -1.0845e-19  0.0000e+00
[torch.FloatTensor of size 5x3]<jupyter_text>* Construct a randomly initialised matrix.<jupyter_code>x = torch.rand(5, 3)
print(x)
print(x.size())<jupyter_output>torch.Size([5, 3])<jupyter_text>Operations<jupyter_code>y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))<jupyter_output>1.2988  0.8416  1.0662
 1.6944  0.8925  0.9409
 1.5882  1.4218  1.6692
 0.9968  0.7080  0.3703
 0.0390  1.1604  1.3318
[torch.FloatTensor of size 5x3]<jupyter_text>* Provide output tensor as argument:<jupyter_code>result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)<jupyter_output>1.2988  0.8416  1.0662
 1.6944  0.8925  0.9409
 1.5882  1.4218  1.6692
 0.9968  0.7080  0.3703
 0.0390  1.1604  1.3318
[torch.FloatTensor of size 5x3]<jupyter_text>* * Any operation that mutates a tensor in-place is post-fixed with an `_`. Example, here's how to add in place:<jupyter_code>y.add_(x)
print(y)<jupyter_output>1.2988  0.8416  1.0662
 1.6944  0.8925  0.9409
 1.5882  1.4218  1.6692
 0.9968  0.7080  0.3703
 0.0390  1.1604  1.3318
[torch.FloatTensor of size 5x3]<jupyter_text>* Can use standard NumPy-like indexing:<jupyter_code>print(x[:, 1])<jupyter_output>0.7383
 0.2807
 0.6879
 0.3989
 0.4853
[torch.FloatTensor of size 5]<jupyter_text>* If you want to resize/reshape the tensor, you can use `torch.view`:<jupyter_code>x = torch.rand(28, 28, 3)
x.shape
x_batch = x.view(1, 28, 28, 3)
x_batch.shape<jupyter_output><empty_output><jupyter_text>NumPy Bridge * When you convert a NumPy array to Torch tensor, they will share underlying memory locations. Changing one will change the other:<jupyter_code>a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
a.add_(1)
print(a)
print(b)<jupyter_output>2
 2
 2
 2
 2
[torch.FloatTensor of size 5]

[2. 2. 2. 2. 2.]<jupyter_text>* Can also go the other way:<jupyter_code>import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)<jupyter_output>[2. 2. 2. 2. 2.]

 2
 2
 2
 2
 2
[torch.DoubleTensor of size 5]<jupyter_text>CUDA Tensors * Tensors can be moved on the GPU using the `.cuda` method:<jupyter_code>if torch.cuda.is_available():
    x = x.cuda()
    y = y.cuda()
    x = y<jupyter_output><empty_output><jupyter_text>Autograd: automatic differentiation * `autograd` package does automatic differentiation for all Tensor operations.  Variable * `autograd.Variable` wraps a Tensor and supports most operations defined on them.   * Access raw tensor using `.data`.  * Gradient with respect to the variable is accumulated into `grad`.* `autograd.Function` are used to build up acyclic graph that stores a history of computation.  * Each variable has a `.grad_fn` attribute that refs a `Function`.* Run `Variable.backward()` to have all gradients computed automatically.  * If value is a scalar, don't need any arguments to `backward()`.  * If it has more elements, need to specify a `gradient` argument.<jupyter_code>import torch
from torch.autograd import Variable
x = Variable(torch.ones(2, 2), requires_grad=True)
print(x)
y = x + 2
print(y)
print(y.grad_fn)
z = y * y * 3
out = z.mean()
print(z, out)
print(z.grad_fn)
out.grad_fn
out.backward()
print(x.grad)
z
x = torch.randn(3)
x = Variable(x, requires_grad=True)

y = x * 2
while y.data.norm() < 1000:
    y = y * 2
    
print(y)
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)

print(x.grad)<jupyter_output>Variable containing:
  204.8000
 2048.0000
    0.2048
[torch.FloatTensor of size 3]<jupyter_text>Neural Networks * `nn.Module` - neural network module.  * Encapsulated params with helpers for moving to GPU, exporting, loading, etc.  Defining a network * You need to define the `forward` function. `backward` function is a automatically defined for you using `autograd`.<jupyter_code>from torch import nn
from torch.nn import 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)
        
        # an affine operation: y = Wx + b
        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.relu(self.conv1(x))
        
        # Max pooling over a (2, 2) window.
        x = F.max_pool2d(x, (2, 2))
        
        x = F.relu(self.conv2(x))
        
        # Same as before, except using a single value to represent the size which
        # assumes a square.
        x = F.max_pool2d(x, 2)
        
        # Flatten
        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:]
        num_features = 1
        for s in size:
            num_features *= s
        return num_features
net = Net()
print(net)<jupyter_output>Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)<jupyter_text>* Can find all learnable parameters of a model using `model.parameters()`:<jupyter_code>params = list(net.parameters())
print(len(params))
print(params[0].size())<jupyter_output>10
torch.Size([6, 1, 5, 5])<jupyter_text>* Expected input size is 32x32:<jupyter_code>input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)<jupyter_output>Variable containing:
-0.0516 -0.1052 -0.0639  0.0303  0.0067 -0.0453 -0.0341  0.0924  0.0128  0.1216
[torch.FloatTensor of size 1x10]<jupyter_text>* Zero gradient buffers of all params and backprops with random gradients:<jupyter_code>net.zero_grad()
out.backward(torch.randn(1, 10))<jupyter_output><empty_output><jupyter_text>* Inputs to everything in the `torch.nn` package are mini-batches of samples, not a single sample.  * Add a fake dimension with `input.unsqueeze(0)`:<jupyter_code>inp = Variable(torch.randn(1, 32, 32))
print(inp.shape)
inp_batch = inp.unsqueeze(0)
print(inp_batch.shape)<jupyter_output>torch.Size([1, 1, 32, 32])<jupyter_text>Loss Function * Several loss functions in the `nn` package.  * Simple loss: `nn.MSELoss` which calculates the mean squared error betweens outputs and target.<jupyter_code>output = net(inp_batch)
target = Variable(torch.arange(1, 11))
target = target.view(1, -1)
criterion = nn.MSELoss()

loss = criterion(output, target)
print(loss)
print(loss.grad_fn)
print(loss.grad_fn.next_functions[0][0])
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])<jupyter_output><MseLossBackward object at 0x11044bf98>
<AddmmBackward object at 0x11044bf28>
<ExpandBackward object at 0x11044bf98><jupyter_text>Backprop * To backpropagate the error, call `loss.backward()`.  * Need to clear the existing gradients first, or else they'll be accumulated.<jupyter_code>net.zero_grad()

print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)

loss.backward()

print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)<jupyter_output>conv1.bias.grad before backward
Variable containing:
 0
 0
 0
 0
 0
 0
[torch.FloatTensor of size 6]

conv1.bias.grad after backward
Variable containing:
1.00000e-02 *
  0.7114
 -4.5536
 -2.8932
 -9.5142
  1.6317
  2.1173
[torch.FloatTensor of size 6]<jupyter_text>Update the weights * To implement the SGD update rule: `weight = weight - learning_rate * gradient`:<jupyter_code>learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)<jupyter_output><empty_output><jupyter_text>* Since there are other optimisation algorithms, Torch provides a package that implements a lot of these in `torch.optim`:<jupyter_code>import torch.optim as optim

optimizer = optim.SGD(net.parameters(), lr=0.01)

optimizer.zero_grad()
output = net(inp_batch)
loss = criterion(output, target)
loss.backward()

optimizer.step()<jupyter_output><empty_output><jupyter_text>Training the classifier Want to perform the following steps:1. Load and normalise the CIFAR10 training and test sets.2. Define a Convolution Neural Network.3. Define a loss function.4. Train the network on training data.5. Test the network on test data.  1. Load and normalize CIFAR10<jupyter_code>import torch
import torchvision
import torchvision.transforms as transforms<jupyter_output><empty_output><jupyter_text>* Output of PILImage images are of range 0-1, we want them -1 to 1:<jupyter_code>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', 'frog', 'horse', 'ship', 'truck')
import matplotlib.pyplot as plt
import numpy as np

def imshow(img):
    # Unnormalise
    img = img / 2 + 0.5
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
# Get some images at random
images, labels = next(iter(trainloader))
imshow(torchvision.utils.make_grid(images))
print(' '.join(f'{classes[labels[j]]}' for j in range(4)))<jupyter_output>truck plane deer cat<jupyter_text>2. Define a CNN<jupyter_code>from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        
        self.pool = nn.MaxPool2d(2, 2)
            
        self.conv1 = nn.Conv2d(3, 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 = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        
        # Flatten
        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()<jupyter_output><empty_output><jupyter_text>3. Define a loss function and optimizer<jupyter_code>import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)<jupyter_output><empty_output><jupyter_text>4. Train the network<jupyter_code>for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # Get the input data
        inputs, labels = data
        
        # wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)
        
        # zero the parameter gradients
        optimizer.zero_grad()
        
        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        
        # print stats
        running_loss += loss.data[0]
        if i % 2000 == 1999:
            print(f'{epoch + 1} {i + 1} loss: {running_loss / 2000}')
            running_loss = 0.0
            
print('Finished training')<jupyter_output>1 2000 loss: 2.1936859393715857
1 4000 loss: 1.9162742663621903
1 6000 loss: 1.716825078845024
1 8000 loss: 1.6106379229426384
1 10000 loss: 1.5585327709764243
1 12000 loss: 1.5175080568492412
2 2000 loss: 1.444005235865712
2 4000 loss: 1.4348339248225093
2 6000 loss: 1.3821665869578719
2 8000 loss: 1.3699464064389468
2 10000 loss: 1.3347010424658656
2 12000 loss: 1.3258742596581579
Finished training<jupyter_text>5. Test the network on test data<jupyter_code>dataiter = iter(testloader)
images, labels = dataiter.next()

imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join(f'{classes[labels[j]]}' for j in range(4)))
outputs = net(Variable(images))
_, predicted = torch.max(outputs.data, 1)

print('Predicted: ', ' '.join(f'{classes[predicted[j]]}' for j in range(4)))
correct = 0
total = 0
for data in testloader:
    images, labels = data
    outputs = net(Variable(images))
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum()

print(f'Accuracy of the network on the 10000 test images: {100 * correct / total}')
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
for data in testloader:
    images, labels = data
    outputs = net(Variable(images))
    _, predicted = torch.max(outputs.data, 1)
    c = (predicted == labels).squeeze()
    for i in range(4):
        label = labels[i]
        class_correct[label] += c[i]
        class_total[label] += 1


for i in range(10):
    print(f'Accuracy of {classes[i]} : {100 * class_correct[i] / class_total[i]}')<jupyter_output>Accuracy of plane : 66.2
Accuracy of car : 62.6
Accuracy of bird : 30.3
Accuracy of cat : 40.4
Accuracy of deer : 35.4
Accuracy of dog : 52.2
Accuracy of frog : 72.2
Accuracy of horse : 63.1
Accuracy of ship : 63.4
Accuracy of truck : 56.2<jupyter_text>Training on GPU * To recursively loop over all modules, converting them to CUDA tensors, run the following:<jupyter_code>net.cuda()
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1262904822514496, 'fraction_numerical': 0.08216659595531042, 'mean_word_length': 3.8138189244383933, 'pattern_counts': {'":': 0, '<': 99, '<?xml version=': 0, '>': 98, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '28', 'dir': 'jupyter-structured-clean-dedup', 'id': '421237', 'license': 'MIT', 'n_tokens_mistral': 5951, 'n_tokens_neox': 5239, 'n_words': 1347, 'path': 'notes/reference/tutorials/pytorch/60-minute-blitz.ipynb', 'repo_name': 'aav789/study-notes', 'size': '14142'}