<jupyter_start><jupyter_text>Get Started with PyTorch This tutoral is based on [the original PyTorch tutorial](https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.htmlsphx-glr-beginner-blitz-neural-networks-tutorial-py).  The goal of this notebook is to explain how PyTorch works and the procedure that we follow to train a deep learning model using PyTorch. In this notebook, we won't be using a real dataset. However, in the other notebook, we will see a real example.   To install PyTorch, you can run the following line.  For other installation ways, you can go [here](https://pytorch.org/get-started/locally/)<jupyter_code>!pip install torch torchvision  
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Neural Networks===============Neural networks can be constructed using the ``torch.nn`` package.An ``nn.Module`` contains layers, and a method ``forward(input)``\ thatreturns the ``output``.For example, look at this network that classifies digit images:![](mnist.png) It is a simple feed-forward network. It takes the input, feeds itthrough several layers one after the other, and then finally gives theoutput.A typical training procedure for a neural network is as follows:- Define the neural network that has some learnable parameters (or  weights)- Iterate over a dataset of inputs- Process input through the network- Compute the loss (how far is the output from being correct)- Propagate gradients back into the network’s parameters- Update the weights of the network, typically using a simple update rule:  ``weight = weight - learning_rate * gradient`` Define the network------------------Let’s define this network:<jupyter_code>import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # In this example, we assume the input shape is (N, 1, 32, 32). N is the size 
        # of the batch
        
        
        # 1 input image channel, 6 output channels, 3x3 square convolution
        # kernel. Note, here we assume the image has one channel.
        # please refer to PyTorch Documentation to learn more about nn.Conv2d function
        # https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d
        # the stide value is 1 and the padding is zero. We used the default values. 
        self.conv1 = nn.Conv2d(1, 6, 3)
        self.conv2 = nn.Conv2d(6, 16, 3)
        
        # Linear operation: y = Wx + b. It takes two arguments: the number of input features
        # and the number of output features. 
        # Here, 16 is the number of output channels we defined above 
        # and 6*6 from the image dimension we get from the output of the previous layer. 
        # It's determined by the method we define in the forward function
        # and is calculated as follow: 
        #                      the image (32,32) -> conv1 (30,30) - Because stide=1 and padding=0
        #                      conv1 (30,30) -> max_pool2d (15,15) - the pool kernel size is 2 
        #                      max_pool2d (15,15) -> conv2 (13,13)
        #                      conv2 (13,13) -> max_pool2d (6,6)
        self.fc1 = nn.Linear(16 * 6 * 6, 120)  
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Here we define the sequence of operations we apply to the input
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # conv -> relu -> pool2d
        
        # If the pool size is a square you can only specify a single number 
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        
        # here we reshave the input from 4 dimensions to 2 because Linear layer 
        # takes an input of two dimensions. We use num_flat_features method to 
        # automatically calculates the second dimension size. The first dimension 
        # is the batch size which will be the same. 
        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)<jupyter_output><empty_output><jupyter_text>You just have to define the ``forward`` function, and the ``backward``function (where gradients are computed) is automatically defined for youusing ``autograd``.You can use any of the Tensor operations in the ``forward`` function.The learnable parameters of a model are returned by ``net.parameters()``<jupyter_code>params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1's .weight<jupyter_output><empty_output><jupyter_text>Let's try a random 32x32 input.Note: expected input size of this net (LeNet) is 32x32.<jupyter_code>input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)<jupyter_output><empty_output><jupyter_text>Zero the gradient buffers of all parameters and backprops with randomgradients:<jupyter_code>net.zero_grad()
out.backward(torch.randn(1, 10))<jupyter_output><empty_output><jupyter_text>Note``torch.nn`` only supports mini-batches. The entire ``torch.nn``    package only supports inputs that are a mini-batch of samples, and not    a single sample.    For example, ``nn.Conv2d`` will take in a 4D Tensor of    ``nSamples x nChannels x Height x Width``.    If you have a single sample, just use ``input.unsqueeze(0)`` to add    a fake batch dimension.Before proceeding further, let's recap all the classes you’ve seen so far.**Recap:**  -  ``torch.Tensor`` - A *multi-dimensional array* with support for autograd     operations like ``backward()``. Also *holds the gradient* w.r.t. the     tensor.  -  ``nn.Module`` - Neural network module. *Convenient way of     encapsulating parameters*, with helpers for moving them to GPU,     exporting, loading, etc.  -  ``nn.Parameter`` - A kind of Tensor, that is *automatically     registered as a parameter when assigned as an attribute to a*     ``Module``.**At this point, we covered:**  -  Defining a neural network  -  Processing inputs and calling backward**Still Left:**  -  Computing the loss  -  Updating the weights of the networkLoss Function-------------A loss function takes the (output, target) pair of inputs, and computes avalue that estimates how far away the output is from the target.There are several different`loss functions `[loss-functions](https://pytorch.org/docs/nn.html)  `under thenn package .A simple loss is: ``nn.MSELoss`` which computes the mean-squared errorbetween the input and the target.For example:<jupyter_code>output = net(input)
target = torch.randn(10)  # a dummy target, for example
target = target.view(1, -1)  # make it the same shape as output
criterion = nn.MSELoss()

loss = criterion(output, target)
print(loss)<jupyter_output><empty_output><jupyter_text>Now, if you follow ``loss`` in the backward direction, using its``.grad_fn`` attribute, you will see a graph of computations that lookslike this:::    input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d          -> view -> linear -> relu -> linear -> relu -> linear          -> MSELoss          -> lossSo, when we call ``loss.backward()``, the whole graph is differentiatedw.r.t. the loss, and all Tensors in the graph that has ``requires_grad=True``will have their ``.grad`` Tensor accumulated with the gradient.For illustration, let us follow a few steps backward:<jupyter_code>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<jupyter_output><empty_output><jupyter_text>Backprop--------To backpropagate the error all we have to do is to ``loss.backward()``.You need to clear the existing gradients though, else gradients will beaccumulated to existing gradients.Now we shall call ``loss.backward()``, and have a look at conv1's biasgradients before and after the backward.<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>Now, we have seen how to use loss functions.**Read Later:**  The neural network package contains various modules and loss functions  that form the building blocks of deep neural networks. A full list with  documentation is [here](https://pytorch.org/docs/nn)**The only thing left to learn is:**  - Updating the weights of the networkUpdate the weights------------------The simplest update rule used in practice is the Stochastic GradientDescent (SGD):     ``weight = weight - learning_rate * gradient``We can implement this using simple Python code:.. code:: python    learning_rate = 0.01    for f in net.parameters():        f.data.sub_(f.grad.data * learning_rate)However, as you use neural networks, you want to use various differentupdate rules such as SGD, Nesterov-SGD, Adam, RMSProp, etc.To enable this, we built a small package: ``torch.optim`` thatimplements all these methods. Using it is very simple:<jupyter_code>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<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10172306414780984, 'fraction_numerical': 0.015777454847415405, 'mean_word_length': 3.5171120487576184, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 57, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '359167', 'license': 'Apache-2.0', 'n_tokens_mistral': 2885, 'n_tokens_neox': 2750, 'n_words': 1090, 'path': 'learning resources/4-labs/week5-Convolutional Neural Networks/Get Started with PyTorch.ipynb', 'repo_name': 'linksdl/acs_project_maching-learning', 'size': '9634'}