{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Neural networks with PyTorch\n",
    "\n",
    "Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term \"deep\" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTorch has a nice module `nn` that provides a nice way to efficiently build large neural networks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import necessary packages\n",
    "\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "import numpy as np\n",
    "import torch\n",
    "\n",
    "import helper\n",
    "\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Now we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample below\n",
    "\n",
    "<img src='assets/mnist.png'>\n",
    "\n",
    "Our goal is to build a neural network that can take one of these images and predict the digit in the image.\n",
    "\n",
    "First up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\n",
      "Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\n",
      "Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n",
      "Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n",
      "Processing...\n",
      "Done!\n"
     ]
    }
   ],
   "source": [
    "### Run this cell\n",
    "\n",
    "from torchvision import datasets, transforms\n",
    "\n",
    "# Define a transform to normalize the data\n",
    "transform = transforms.Compose([transforms.ToTensor(),\n",
    "                              transforms.Normalize((0.5,), (0.5,)),\n",
    "                              ])\n",
    "\n",
    "# Download and load the training data\n",
    "trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)\n",
    "trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like\n",
    "\n",
    "```python\n",
    "for image, label in trainloader:\n",
    "    ## do things with images and labels\n",
    "```\n",
    "\n",
    "You'll notice I created the `trainloader` with a batch size of 64, and `shuffle=True`. The batch size is the number of images we get in one iteration from the data loader and pass through our network, often called a *batch*. And `shuffle=True` tells it to shuffle the dataset every time we start going through the data loader again. But here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size `(64, 1, 28, 28)`. So, 64 images per batch, 1 color channel, and 28x28 images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'torch.Tensor'>\n",
      "torch.Size([64, 1, 28, 28])\n",
      "torch.Size([64])\n"
     ]
    }
   ],
   "source": [
    "dataiter = iter(trainloader)\n",
    "images, labels = dataiter.next()\n",
    "print(type(images))\n",
    "print(images.shape)\n",
    "print(labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is what one of the images looks like. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9960 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fcee99b1048>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 250,
       "width": 253
      },
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.\n",
    "\n",
    "The networks you've seen so far are called *fully-connected* or *dense* networks. Each unit in one layer is connected to each unit in the next layer. In fully-connected networks, the input to each layer must be a one-dimensional vector (which can be stacked into a 2D tensor as a batch of multiple examples). However, our images are 28x28 2D tensors, so we need to convert them into 1D vectors. Thinking about sizes, we need to convert the batch of images with shape `(64, 1, 28, 28)` to a have a shape of `(64, 784)`, 784 is 28 times 28. This is typically called *flattening*, we flattened the 2D images into 1D vectors.\n",
    "\n",
    "Previously you built a network with one output unit. Here we need 10 output units, one for each digit. We want our network to predict the digit shown in an image, so what we'll do is calculate probabilities that the image is of any one digit or class. This ends up being a discrete probability distribution over the classes (digits) that tells us the most likely class for the image. That means we need 10 output units for the 10 classes (digits). We'll see how to convert the network output into a probability distribution next.\n",
    "\n",
    "> **Exercise:** Flatten the batch of images `images`. Then build a multi-layer network with 784 input units, 256 hidden units, and 10 output units using random tensors for the weights and biases. For now, use a sigmoid activation for the hidden layer. Leave the output layer without an activation, we'll add one that gives us a probability distribution next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Your solution\n",
    "def activation(x):\n",
    "    return 1 / (1 + torch.exp(-x))\n",
    "\n",
    "# Flatten images\n",
    "\n",
    "inputs = images.view(images.shape[0], -1)\n",
    "\n",
    "# Create parameters\n",
    "w1 = torch.randn(784, 256)\n",
    "b1 = torch.randn(256)\n",
    "\n",
    "w2 = torch.randn(256, 10)\n",
    "b2 = torch.randn(10)\n",
    "\n",
    "h = activation(torch.mm(inputs, w1) + b1)\n",
    "\n",
    "out = torch.mm(h, w2) + b2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:\n",
    "<img src='assets/image_distribution.png' width=500px>\n",
    "\n",
    "Here we see that the probability for each class is roughly the same. This is representing an untrained network, it hasn't seen any data yet so it just returns a uniform distribution with equal probabilities for each class.\n",
    "\n",
    "To calculate this probability distribution, we often use the [**softmax** function](https://en.wikipedia.org/wiki/Softmax_function). Mathematically this looks like\n",
    "\n",
    "$$\n",
    "\\Large \\sigma(x_i) = \\cfrac{e^{x_i}}{\\sum_k^K{e^{x_k}}}\n",
    "$$\n",
    "\n",
    "What this does is squish each input $x_i$ between 0 and 1 and normalizes the values to give you a proper probability distribution where the probabilites sum up to one.\n",
    "\n",
    "> **Exercise:** Implement a function `softmax` that performs the softmax calculation and returns probability distributions for each example in the batch. Note that you'll need to pay attention to the shapes when doing this. If you have a tensor `a` with shape `(64, 10)` and a tensor `b` with shape `(64,)`, doing `a/b` will give you an error because PyTorch will try to do the division across the columns (called broadcasting) but you'll get a size mismatch. The way to think about this is for each of the 64 examples, you only want to divide by one value, the sum in the denominator. So you need `b` to have a shape of `(64, 1)`. This way PyTorch will divide the 10 values in each row of `a` by the one value in each row of `b`. Pay attention to how you take the sum as well. You'll need to define the `dim` keyword in `torch.sum`. Setting `dim=0` takes the sum across the rows while `dim=1` takes the sum across the columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([64, 10])\n",
      "tensor([ 1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,  1.0000,\n",
      "         1.0000])\n"
     ]
    }
   ],
   "source": [
    "def softmax(x):\n",
    "    ## TODO: Implement the softmax function here\n",
    "    return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1)\n",
    "\n",
    "# Here, out should be the output of the network in the previous excercise with shape (64,10)\n",
    "probabilities = softmax(out)\n",
    "\n",
    "# Does it have the right shape? Should be (64, 10)\n",
    "print(probabilities.shape)\n",
    "# Does it sum to 1?\n",
    "print(probabilities.sum(dim=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building networks with PyTorch\n",
    "\n",
    "PyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch import nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Network(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        \n",
    "        # Inputs to hidden layer linear transformation\n",
    "        self.hidden = nn.Linear(784, 256)\n",
    "        # Output layer, 10 units - one for each digit\n",
    "        self.output = nn.Linear(256, 10)\n",
    "        \n",
    "        # Define sigmoid activation and softmax output \n",
    "        self.sigmoid = nn.Sigmoid()\n",
    "        self.softmax = nn.Softmax(dim=1)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        # Pass the input tensor through each of our operations\n",
    "        x = self.hidden(x)\n",
    "        x = self.sigmoid(x)\n",
    "        x = self.output(x)\n",
    "        x = self.softmax(x)\n",
    "        \n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's go through this bit by bit.\n",
    "\n",
    "```python\n",
    "class Network(nn.Module):\n",
    "```\n",
    "\n",
    "Here we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.\n",
    "\n",
    "```python\n",
    "self.hidden = nn.Linear(784, 256)\n",
    "```\n",
    "\n",
    "This line creates a module for a linear transformation, $x\\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network (`net`) is created with `net.hidden.weight` and `net.hidden.bias`.\n",
    "\n",
    "```python\n",
    "self.output = nn.Linear(256, 10)\n",
    "```\n",
    "\n",
    "Similarly, this creates another linear transformation with 256 inputs and 10 outputs.\n",
    "\n",
    "```python\n",
    "self.sigmoid = nn.Sigmoid()\n",
    "self.softmax = nn.Softmax(dim=1)\n",
    "```\n",
    "\n",
    "Here I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.\n",
    "\n",
    "```python\n",
    "def forward(self, x):\n",
    "```\n",
    "\n",
    "PyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.\n",
    "\n",
    "```python\n",
    "x = self.hidden(x)\n",
    "x = self.sigmoid(x)\n",
    "x = self.output(x)\n",
    "x = self.softmax(x)\n",
    "```\n",
    "\n",
    "Here the input tensor `x` is passed through each operation a reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.\n",
    "\n",
    "Now we can create a `Network` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Network(\n",
       "  (hidden): Linear(in_features=784, out_features=256, bias=True)\n",
       "  (output): Linear(in_features=256, out_features=10, bias=True)\n",
       "  (sigmoid): Sigmoid()\n",
       "  (softmax): Softmax()\n",
       ")"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Create the network and look at it's text representation\n",
    "model = Network()\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn.functional as F\n",
    "\n",
    "class Network(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        # Inputs to hidden layer linear transformation\n",
    "        self.hidden = nn.Linear(784, 256)\n",
    "        # Output layer, 10 units - one for each digit\n",
    "        self.output = nn.Linear(256, 10)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        # Hidden layer with sigmoid activation\n",
    "        x = F.sigmoid(self.hidden(x))\n",
    "        # Output layer with softmax activation\n",
    "        x = F.softmax(self.output(x), dim=1)\n",
    "        \n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Activation functions\n",
    "\n",
    "So far we've only been looking at the softmax activation, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common activation functions: Tanh (hyperbolic tangent), and ReLU (rectified linear unit).\n",
    "\n",
    "<img src=\"assets/activation.png\" width=700px>\n",
    "\n",
    "In practice, the ReLU function is used almost exclusively as the activation function for hidden layers."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Your Turn to Build a Network\n",
    "\n",
    "<img src=\"assets/mlp_mnist.png\" width=600px>\n",
    "\n",
    "> **Exercise:** Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above. You can use a ReLU activation with the `nn.ReLU` module or `F.relu` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Network(\n",
       "  (l1): Linear(in_features=784, out_features=128, bias=True)\n",
       "  (l2): Linear(in_features=128, out_features=64, bias=True)\n",
       "  (l3): Linear(in_features=64, out_features=10, bias=True)\n",
       ")"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## Your solution here\n",
    "\n",
    "class Network(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        # Define the layers 128, 64, 10 units each\n",
    "        self.l1 = nn.Linear(784, 128)\n",
    "        self.l2 = nn.Linear(128, 64)\n",
    "        # Define output layer\n",
    "        self.l3 = nn.Linear(64, 10)\n",
    "    \n",
    "    def forward(self, x):\n",
    "        \"\"\"Forward pass through the network - reuturns the output\"\"\"\n",
    "        x = self.l1(x)\n",
    "        x = F.relu(x)\n",
    "        \n",
    "        x = self.l2(x)\n",
    "        x = F.relu(x)\n",
    "        \n",
    "        x = self.l3(x)\n",
    "        x = F.softmax(x, dim=1)\n",
    "        \n",
    "        return x\n",
    "\n",
    "model=Network()\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initializing weights and biases\n",
    "\n",
    "The weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[-1.0776e-02,  2.0526e-02, -1.5042e-02,  ..., -4.7536e-03,\n",
      "          2.5714e-03, -5.5181e-03],\n",
      "        [-1.8762e-02, -2.5858e-02, -2.6485e-02,  ..., -1.0233e-02,\n",
      "         -2.2680e-02, -5.5377e-04],\n",
      "        [-1.3932e-02,  6.4527e-03, -2.6832e-03,  ...,  2.3186e-02,\n",
      "          2.8184e-02, -5.7248e-04],\n",
      "        ...,\n",
      "        [ 1.4060e-02,  3.0088e-02, -2.8885e-03,  ...,  2.5048e-02,\n",
      "         -1.9844e-02,  6.5543e-03],\n",
      "        [ 1.5551e-02,  8.4835e-03,  1.5654e-04,  ..., -1.5493e-02,\n",
      "         -4.2152e-03, -2.5316e-02],\n",
      "        [ 1.2114e-03, -1.4411e-02,  1.9116e-02,  ...,  3.1978e-02,\n",
      "          1.9531e-02, -3.2406e-02]])\n",
      "Parameter containing:\n",
      "tensor(1.00000e-02 *\n",
      "       [-2.7470,  2.9781,  2.5320, -2.3808,  3.0487, -0.7365, -2.4079,\n",
      "         0.4414, -1.7073,  1.8509,  3.3353, -0.6008, -3.2928,  3.3918,\n",
      "         2.9831,  0.0983, -1.1983, -2.0790,  0.9813, -0.6745, -0.3347,\n",
      "        -0.8737, -2.7929,  1.2551,  0.2288, -2.4784,  0.0190,  1.2828,\n",
      "        -0.6021,  2.4832,  3.4782, -0.3269, -1.7032, -3.1000, -2.4096,\n",
      "        -1.1523, -3.1894,  3.4164, -3.0275, -2.3891, -0.0275,  1.7851,\n",
      "         3.1205,  1.2810,  1.0525, -0.6538, -1.6390, -2.4172,  2.1895,\n",
      "        -1.8027, -0.4446, -1.5385,  2.0806, -1.9547, -0.4899, -1.0428,\n",
      "         3.3237,  1.0272,  1.2687,  0.9785, -0.6819, -1.0355, -3.1642,\n",
      "         0.9449, -0.3841,  2.8396,  0.5092,  2.9105, -1.7338, -2.2073,\n",
      "         1.2315,  1.6605,  0.9994, -0.9812, -1.5683, -0.1603, -0.3632,\n",
      "         0.3852, -1.0125,  0.2518,  0.2360,  3.5688, -0.3973,  0.8222,\n",
      "        -0.1480,  0.7442,  2.6121, -2.9418,  1.2141,  0.0198, -0.6789,\n",
      "        -0.8365, -0.4946, -0.7336, -0.1345,  1.7144, -1.2053,  1.8478,\n",
      "        -2.6136,  3.3724, -0.7037, -2.8251, -3.3915,  1.9541,  1.3929,\n",
      "         0.4494, -1.4477, -3.0928,  1.5461,  2.9698, -1.2177,  3.4206,\n",
      "        -0.8522, -0.1440,  0.8285,  0.1339,  0.4546,  2.1396,  1.3242,\n",
      "         0.1970,  1.6910,  1.9873,  2.1056, -1.9118,  0.0454, -0.4995,\n",
      "         3.3401,  2.1109])\n"
     ]
    }
   ],
   "source": [
    "print(model.l1.weight)\n",
    "print(model.l1.bias)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,\n",
       "         0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Set biases to all zeros\n",
    "model.l1.bias.data.fill_(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[-2.3535e-03, -4.0847e-03,  6.6107e-03,  ...,  1.3488e-02,\n",
       "         -3.0676e-03,  4.7938e-03],\n",
       "        [ 2.1113e-02, -1.3056e-02, -1.5310e-02,  ...,  1.2427e-03,\n",
       "          2.0526e-02, -3.7705e-03],\n",
       "        [ 1.2847e-02, -3.6961e-03,  1.8160e-02,  ..., -5.9606e-03,\n",
       "         -1.5045e-02, -9.3461e-03],\n",
       "        ...,\n",
       "        [-7.3355e-03,  3.1985e-03,  1.9387e-03,  ..., -1.1342e-02,\n",
       "          3.1593e-04, -2.1606e-03],\n",
       "        [-3.4460e-03,  1.0747e-03,  1.1796e-02,  ...,  3.0916e-03,\n",
       "         -1.3553e-02, -6.0074e-03],\n",
       "        [-3.2343e-03, -9.9594e-03,  9.7654e-03,  ...,  6.7241e-03,\n",
       "         -4.3026e-03,  5.2910e-03]])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sample from random normal with standard dev = 0.01\n",
    "model.l1.weight.data.normal_(std=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Forward pass\n",
    "\n",
    "Now that we have a network, let's see what happens when we pass in an image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 16216 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fce92b8ee80>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 224,
       "width": 423
      },
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Grab some data \n",
    "dataiter = iter(trainloader)\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels) \n",
    "images.resize_(64, 1, 784)\n",
    "# or images.resize_(images.shape[0], 1, 784) to automatically get batch size\n",
    "\n",
    "# Forward pass through the network\n",
    "img_idx = 0\n",
    "ps = model.forward(images[img_idx,:])\n",
    "\n",
    "img = images[img_idx]\n",
    "helper.view_classify(img.view(1, 28, 28), ps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random!\n",
    "\n",
    "### Using `nn.Sequential`\n",
    "\n",
    "PyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sequential(\n",
      "  (0): Linear(in_features=784, out_features=128, bias=True)\n",
      "  (1): ReLU()\n",
      "  (2): Linear(in_features=128, out_features=64, bias=True)\n",
      "  (3): ReLU()\n",
      "  (4): Linear(in_features=64, out_features=10, bias=True)\n",
      "  (5): Softmax()\n",
      ")\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 15916 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fce961a4358>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 224,
       "width": 423
      },
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Hyperparameters for our network\n",
    "input_size = 784\n",
    "hidden_sizes = [128, 64]\n",
    "output_size = 10\n",
    "\n",
    "# Build a feed-forward network\n",
    "model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(hidden_sizes[0], hidden_sizes[1]),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(hidden_sizes[1], output_size),\n",
    "                      nn.Softmax(dim=1))\n",
    "print(model)\n",
    "\n",
    "# Forward pass through the network and display output\n",
    "images, labels = next(iter(trainloader))\n",
    "images.resize_(images.shape[0], 1, 784)\n",
    "ps = model.forward(images[0,:])\n",
    "helper.view_classify(images[0].view(1, 28, 28), ps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.\n",
    "\n",
    "The operations are availble by passing in the appropriate index. For example, if you want to get first Linear operation and look at the weights, you'd use `model[0]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linear(in_features=784, out_features=128, bias=True)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[-2.4938e-02, -7.7938e-03,  6.8920e-02,  ...,  4.9189e-02,\n",
       "          7.5370e-02,  7.8373e-02],\n",
       "        [-8.0918e-02, -3.0586e-02, -4.4575e-02,  ...,  3.4322e-02,\n",
       "          9.7493e-04,  3.5337e-02],\n",
       "        [-3.6158e-03, -1.0852e-02,  2.2992e-02,  ...,  7.2592e-02,\n",
       "         -8.1835e-02,  3.0893e-02],\n",
       "        ...,\n",
       "        [-7.4640e-02,  4.8931e-02,  3.2685e-02,  ..., -3.6627e-02,\n",
       "         -5.1732e-02,  8.4485e-02],\n",
       "        [-1.1577e-02,  2.1981e-02, -3.5689e-02,  ...,  7.4438e-02,\n",
       "         -5.9650e-02,  5.7569e-02],\n",
       "        [ 7.3337e-02,  3.8470e-02, -3.5789e-02,  ...,  5.3540e-02,\n",
       "          1.4137e-02,  5.9897e-02]])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(model[0])\n",
    "model[2].weight"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Sequential(\n",
       "  (fc1): Linear(in_features=784, out_features=128, bias=True)\n",
       "  (relu1): ReLU()\n",
       "  (fc2): Linear(in_features=128, out_features=64, bias=True)\n",
       "  (relu2): ReLU()\n",
       "  (output): Linear(in_features=64, out_features=10, bias=True)\n",
       "  (softmax): Softmax()\n",
       ")"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from collections import OrderedDict\n",
    "model = nn.Sequential(OrderedDict([\n",
    "                      ('fc1', nn.Linear(input_size, hidden_sizes[0])),\n",
    "                      ('relu1', nn.ReLU()),\n",
    "                      ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),\n",
    "                      ('relu2', nn.ReLU()),\n",
    "                      ('output', nn.Linear(hidden_sizes[1], output_size)),\n",
    "                      ('softmax', nn.Softmax(dim=1))]))\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you can access layers either by integer or the name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linear(in_features=784, out_features=128, bias=True)\n",
      "Linear(in_features=784, out_features=128, bias=True)\n"
     ]
    }
   ],
   "source": [
    "print(model[0])\n",
    "print(model.fc1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the next notebook, we'll see how we can train a neural network to accuractly predict the numbers appearing in the MNIST images."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
