{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training Neural Networks\n",
    "\n",
    "The network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten digits to class probabilities. The power of neural networks is that we can train them to approximate this function, and basically any function given enough data and compute time.\n",
    "\n",
    "<img src=\"assets/function_approx.png\" width=500px>\n",
    "\n",
    "At first the network is naive, it doesn't know the function mapping the inputs to the outputs. We train the network by showing it examples of real data, then adjusting the network parameters such that it approximates this function.\n",
    "\n",
    "To find these parameters, we need to know how poorly the network is predicting the real outputs. For this we calculate a **loss function** (also called the cost), a measure of our prediction error. For example, the mean squared loss is often used in regression and binary classification problems\n",
    "\n",
    "$$\n",
    "\\large \\ell = \\frac{1}{2n}\\sum_i^n{\\left(y_i - \\hat{y}_i\\right)^2}\n",
    "$$\n",
    "\n",
    "where $n$ is the number of training examples, $y_i$ are the true labels, and $\\hat{y}_i$ are the predicted labels.\n",
    "\n",
    "By minimizing this loss with respect to the network parameters, we can find configurations where the loss is at a minimum and the network is able to predict the correct labels with high accuracy. We find this minimum using a process called **gradient descent**. The gradient is the slope of the loss function and points in the direction of fastest change. To get to the minimum in the least amount of time, we then want to follow the gradient (downwards). You can think of this like descending a mountain by following the steepest slope to the base.\n",
    "\n",
    "<img src='assets/gradient_descent.png' width=350px>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Backpropagation\n",
    "\n",
    "For single layer networks, gradient descent is straightforward to implement. However, it's more complicated for deeper, multilayer neural networks like the one we've built. Complicated enough that it took about 30 years before researchers figured out how to train multilayer networks.\n",
    "\n",
    "Training multilayer networks is done through **backpropagation** which is really just an application of the chain rule from calculus. It's easiest to understand if we convert a two layer network into a graph representation.\n",
    "\n",
    "<img src='assets/backprop_diagram.png' width=550px>\n",
    "\n",
    "In the forward pass through the network, our data and operations go from bottom to top here. We pass the input $x$ through a linear transformation $L_1$ with weights $W_1$ and biases $b_1$. The output then goes through the sigmoid operation $S$ and another linear transformation $L_2$. Finally we calculate the loss $\\ell$. We use the loss as a measure of how bad the network's predictions are. The goal then is to adjust the weights and biases to minimize the loss.\n",
    "\n",
    "To train the weights with gradient descent, we propagate the gradient of the loss backwards through the network. Each operation has some gradient between the inputs and outputs. As we send the gradients backwards, we multiply the incoming gradient with the gradient for the operation. Mathematically, this is really just calculating the gradient of the loss with respect to the weights using the chain rule.\n",
    "\n",
    "$$\n",
    "\\large \\frac{\\partial \\ell}{\\partial W_1} = \\frac{\\partial L_1}{\\partial W_1} \\frac{\\partial S}{\\partial L_1} \\frac{\\partial L_2}{\\partial S} \\frac{\\partial \\ell}{\\partial L_2}\n",
    "$$\n",
    "\n",
    "**Note:** I'm glossing over a few details here that require some knowledge of vector calculus, but they aren't necessary to understand what's going on.\n",
    "\n",
    "We update our weights using this gradient with some learning rate $\\alpha$. \n",
    "\n",
    "$$\n",
    "\\large W^\\prime_1 = W_1 - \\alpha \\frac{\\partial \\ell}{\\partial W_1}\n",
    "$$\n",
    "\n",
    "The learning rate $\\alpha$ is set such that the weight update steps are small enough that the iterative method settles in a minimum."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Losses in PyTorch\n",
    "\n",
    "Let's start by seeing how we calculate the loss with PyTorch. Through the `nn` module, PyTorch provides losses such as the cross-entropy loss (`nn.CrossEntropyLoss`). You'll usually see the loss assigned to `criterion`. As noted in the last part, with a classification problem such as MNIST, we're using the softmax function to predict class probabilities. With a softmax output, you want to use cross-entropy as the loss. To actually calculate the loss, you first define the criterion then pass in the output of your network and the correct labels.\n",
    "\n",
    "Something really important to note here. Looking at [the documentation for `nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss),\n",
    "\n",
    "> This criterion combines `nn.LogSoftmax()` and `nn.NLLLoss()` in one single class.\n",
    ">\n",
    "> The input is expected to contain scores for each class.\n",
    "\n",
    "This means we need to pass in the raw output of our network into the loss, not the output of the softmax function. This raw output is usually called the *logits* or *scores*. We use the logits because softmax gives you probabilities which will often be very close to zero or one but floating-point numbers can't accurately represent values near zero or one ([read more here](https://docs.python.org/3/tutorial/floatingpoint.html)). It's usually best to avoid doing calculations with probabilities, typically we use log-probabilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "import torch.nn.functional as F\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, 0.5), (0.5, 0.5, 0.5)),\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": [
    "### Note\n",
    "If you haven't seen `nn.Sequential` yet, please finish the end of the Part 2 notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(2.3037)\n"
     ]
    }
   ],
   "source": [
    "# Build a feed-forward network\n",
    "model = nn.Sequential(nn.Linear(784, 128),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(128, 64),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(64, 10))\n",
    "\n",
    "# Define the loss\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "\n",
    "# Get our data\n",
    "images, labels = next(iter(trainloader))\n",
    "# Flatten images\n",
    "images = images.view(images.shape[0], -1)\n",
    "\n",
    "# Forward pass, get our logits\n",
    "logits = model(images)\n",
    "# Calculate the loss with the logits and the labels\n",
    "loss = criterion(logits, labels)\n",
    "\n",
    "print(loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, you want to use the negative log likelihood loss, `nn.NLLLoss` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss)).\n",
    "\n",
    ">**Exercise:** Build a model that returns the log-softmax as the output and calculate the loss using the negative log likelihood loss. Note that for `nn.LogSoftmax` and `F.log_softmax` you'll need to set the `dim` keyword argument appropriately. `dim=0` calculates softmax across the rows, so each column sums to 1, while `dim=1` calculates across the columns so each row sums to 1. Think about what you want the output to be and choose `dim` appropriately."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(2.3134)\n"
     ]
    }
   ],
   "source": [
    "# TODO: Build a feed-forward network\n",
    "model = nn.Sequential(nn.Linear(784, 128),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(128, 64),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(64, 10),\n",
    "                      nn.LogSoftmax(dim=1))\n",
    "\n",
    "# TODO: Define the loss\n",
    "criterion = nn.NLLLoss()\n",
    "\n",
    "### Run this to check your work\n",
    "# Get our data\n",
    "images, labels = next(iter(trainloader))\n",
    "# Flatten images\n",
    "images = images.view(images.shape[0], -1)\n",
    "\n",
    "# Forward pass, get our logits\n",
    "logits = model(images)\n",
    "# Calculate the loss with the logits and the labels\n",
    "loss = criterion(logits, labels)\n",
    "\n",
    "print(loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Autograd\n",
    "\n",
    "Now that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operations performed on tensors, then going backwards through those operations, calculating gradients along the way. To make sure PyTorch keeps track of operations on a tensor and calculates the gradients, you need to set `requires_grad = True` on a tensor. You can do this at creation with the `requires_grad` keyword, or at any time with `x.requires_grad_(True)`.\n",
    "\n",
    "You can turn off gradients for a block of code with the `torch.no_grad()` content:\n",
    "```python\n",
    "x = torch.zeros(1, requires_grad=True)\n",
    ">>> with torch.no_grad():\n",
    "...     y = x * 2\n",
    ">>> y.requires_grad\n",
    "False\n",
    "```\n",
    "\n",
    "Also, you can turn on or off gradients altogether with `torch.set_grad_enabled(True|False)`.\n",
    "\n",
    "The gradients are computed with respect to some variable `z` with `z.backward()`. This does a backward pass through the operations that created `z`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-0.1234,  1.2443],\n",
      "        [-1.2560, -0.1746]])\n"
     ]
    }
   ],
   "source": [
    "x = torch.randn(2,2, requires_grad=True)\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.0152,  1.5482],\n",
      "        [ 1.5776,  0.0305]])\n"
     ]
    }
   ],
   "source": [
    "y = x**2\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Below we can see the operation that created `y`, a power operation `PowBackward0`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<PowBackward0 object at 0x7fec63741780>\n"
     ]
    }
   ],
   "source": [
    "## grad_fn shows the function that generated this variable\n",
    "print(y.grad_fn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The autgrad module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(0.7929)\n"
     ]
    }
   ],
   "source": [
    "z = y.mean()\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can check the gradients for `x` and `y` but they are empty currently."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x`\n",
    "\n",
    "$$\n",
    "\\frac{\\partial z}{\\partial x} = \\frac{\\partial}{\\partial x}\\left[\\frac{1}{n}\\sum_i^n x_i^2\\right] = \\frac{x}{2}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-0.0617,  0.6221],\n",
      "        [-0.6280, -0.0873]])\n",
      "tensor([[-0.0617,  0.6221],\n",
      "        [-0.6280, -0.0873]])\n"
     ]
    }
   ],
   "source": [
    "z.backward()\n",
    "print(x.grad)\n",
    "print(x/2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These gradients calculations are particularly useful for neural networks. For training we need the gradients of the weights with respect to the cost. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the gradients we can make a gradient descent step. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loss and Autograd together\n",
    "\n",
    "When we create a network with PyTorch, all of the parameters are initialized with `requires_grad = True`. This means that when we calculate the loss and call `loss.backward()`, the gradients for the parameters are calculated. These gradients are used to update the weights with gradient descent. Below you can see an example of calculating the gradients using a backwards pass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build a feed-forward network\n",
    "model = nn.Sequential(nn.Linear(784, 128),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(128, 64),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(64, 10),\n",
    "                      nn.LogSoftmax(dim=1))\n",
    "\n",
    "criterion = nn.NLLLoss()\n",
    "images, labels = next(iter(trainloader))\n",
    "images = images.view(images.shape[0], -1)\n",
    "\n",
    "logits = model(images)\n",
    "loss = criterion(logits, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before backward pass: \n",
      " None\n",
      "After backward pass: \n",
      " tensor(1.00000e-02 *\n",
      "       [[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],\n",
      "        [ 0.1559,  0.1559,  0.1559,  ...,  0.1559,  0.1559,  0.1559],\n",
      "        [-0.2130, -0.2130, -0.2130,  ..., -0.2130, -0.2130, -0.2130],\n",
      "        ...,\n",
      "        [ 0.0225,  0.0225,  0.0225,  ...,  0.0225,  0.0225,  0.0225],\n",
      "        [ 0.0050,  0.0050,  0.0050,  ...,  0.0050,  0.0050,  0.0050],\n",
      "        [ 0.1201,  0.1201,  0.1201,  ...,  0.1201,  0.1201,  0.1201]])\n"
     ]
    }
   ],
   "source": [
    "print('Before backward pass: \\n', model[0].weight.grad)\n",
    "\n",
    "loss.backward()\n",
    "\n",
    "print('After backward pass: \\n', model[0].weight.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training the network!\n",
    "\n",
    "There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to define an optimizer below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch import optim\n",
    "\n",
    "# Optimizers require the parameters to optimize and a learning rate\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch:\n",
    "\n",
    "* Make a forward pass through the network \n",
    "* Use the network output to calculate the loss\n",
    "* Perform a backward pass through the network with `loss.backward()` to calculate the gradients\n",
    "* Take a step with the optimizer to update the weights\n",
    "\n",
    "Below I'll go through one training step and print out the weights and gradients so you can see how it changes. Note that I have a line of code `optimizer.zero_grad()`. When you do multiple backwards passes with the same parameters, the gradients are accumulated. This means that you need to zero the gradients on each training pass or you'll retain gradients from previous training batches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial weights -  Parameter containing:\n",
      "tensor(1.00000e-02 *\n",
      "       [[-2.7038,  1.9887,  3.2999,  ...,  0.8496, -2.6579, -0.8653],\n",
      "        [ 2.2119,  3.2675,  1.8336,  ...,  1.7263, -1.5512,  2.4111],\n",
      "        [ 3.4532, -2.9259, -1.6578,  ...,  3.4532, -1.8388,  1.4622],\n",
      "        ...,\n",
      "        [-3.1650,  1.7098, -1.7899,  ...,  3.3786,  2.3959,  0.5995],\n",
      "        [-1.4419,  0.8861,  2.4177,  ..., -2.7610, -0.7628,  2.6093],\n",
      "        [ 2.0784, -3.4497, -2.4344,  ..., -2.2582, -0.4973,  2.0179]])\n",
      "Gradient - tensor(1.00000e-02 *\n",
      "       [[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],\n",
      "        [-0.2836, -0.2836, -0.2836,  ..., -0.2836, -0.2836, -0.2836],\n",
      "        [ 0.1898,  0.1898,  0.1898,  ...,  0.1898,  0.1898,  0.1898],\n",
      "        ...,\n",
      "        [-0.2426, -0.2426, -0.2426,  ..., -0.2426, -0.2426, -0.2426],\n",
      "        [-0.0191, -0.0191, -0.0191,  ..., -0.0191, -0.0191, -0.0191],\n",
      "        [-0.0097, -0.0097, -0.0097,  ..., -0.0097, -0.0097, -0.0097]])\n"
     ]
    }
   ],
   "source": [
    "print('Initial weights - ', model[0].weight)\n",
    "\n",
    "images, labels = next(iter(trainloader))\n",
    "images.resize_(64, 784)\n",
    "\n",
    "# Clear the gradients, do this because gradients are accumulated\n",
    "optimizer.zero_grad()\n",
    "\n",
    "# Forward pass, then backward pass, then update weights\n",
    "output = model.forward(images)\n",
    "loss = criterion(output, labels)\n",
    "loss.backward()\n",
    "print('Gradient -', model[0].weight.grad)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Updated weights -  Parameter containing:\n",
      "tensor([[-2.7038e-02,  1.9887e-02,  3.2999e-02,  ...,  8.4956e-03,\n",
      "         -2.6579e-02, -8.6528e-03],\n",
      "        [ 2.2148e-02,  3.2703e-02,  1.8365e-02,  ...,  1.7291e-02,\n",
      "         -1.5484e-02,  2.4139e-02],\n",
      "        [ 3.4513e-02, -2.9278e-02, -1.6597e-02,  ...,  3.4513e-02,\n",
      "         -1.8407e-02,  1.4603e-02],\n",
      "        ...,\n",
      "        [-3.1626e-02,  1.7122e-02, -1.7874e-02,  ...,  3.3810e-02,\n",
      "          2.3983e-02,  6.0188e-03],\n",
      "        [-1.4417e-02,  8.8628e-03,  2.4179e-02,  ..., -2.7608e-02,\n",
      "         -7.6258e-03,  2.6094e-02],\n",
      "        [ 2.0785e-02, -3.4496e-02, -2.4343e-02,  ..., -2.2581e-02,\n",
      "         -4.9718e-03,  2.0180e-02]])\n"
     ]
    }
   ],
   "source": [
    "# Take an update step and few the new weights\n",
    "optimizer.step()\n",
    "print('Updated weights - ', model[0].weight)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training for real\n",
    "\n",
    "Now we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the loss, do a backwards pass, and update the weights.\n",
    "\n",
    ">**Exercise:** Implement the training pass for our network. If you implemented it correctly, you should see the training loss drop with each epoch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[-2.7038e-02,  1.9887e-02,  3.2999e-02,  ...,  8.4956e-03,\n",
      "         -2.6579e-02, -8.6528e-03],\n",
      "        [ 2.2148e-02,  3.2703e-02,  1.8365e-02,  ...,  1.7291e-02,\n",
      "         -1.5484e-02,  2.4139e-02],\n",
      "        [ 3.4513e-02, -2.9278e-02, -1.6597e-02,  ...,  3.4513e-02,\n",
      "         -1.8407e-02,  1.4603e-02],\n",
      "        ...,\n",
      "        [-3.1626e-02,  1.7122e-02, -1.7874e-02,  ...,  3.3810e-02,\n",
      "          2.3983e-02,  6.0188e-03],\n",
      "        [-1.4417e-02,  8.8628e-03,  2.4179e-02,  ..., -2.7608e-02,\n",
      "         -7.6258e-03,  2.6094e-02],\n",
      "        [ 2.0785e-02, -3.4496e-02, -2.4343e-02,  ..., -2.2581e-02,\n",
      "         -4.9718e-03,  2.0180e-02]])\n",
      "Parameter containing:\n",
      "tensor(1.00000e-02 *\n",
      "       [ 3.3668,  0.7419, -1.8832,  3.3459, -1.2885,  2.3498, -3.2847,\n",
      "        -2.5125,  1.2113,  0.9952,  0.9553,  2.6171, -3.3212, -0.0938,\n",
      "        -2.4987,  3.5654, -0.0948,  1.7207, -2.3500, -1.9280,  2.4983,\n",
      "        -0.7706, -0.8420,  1.0975,  2.1482,  1.1367,  2.0218, -3.2644,\n",
      "        -2.3274, -0.7202, -3.2821,  0.8014,  1.2345, -0.6529, -0.8498,\n",
      "         1.2524, -1.3299,  0.9776, -0.4898, -1.0730, -3.5097, -1.4012,\n",
      "        -2.7926,  0.8974,  3.0059,  2.6043,  0.9115, -1.5502, -3.5404,\n",
      "         2.3430,  0.1960,  1.9573,  0.0817,  2.7596, -1.2438,  0.1364,\n",
      "        -2.0851,  0.8863, -3.5209,  2.5510,  0.1684,  2.5416, -1.9530,\n",
      "         0.5968,  2.5971, -2.3745, -3.0792, -3.1208, -2.2553, -3.4898,\n",
      "         1.1541,  3.1804, -1.1212,  2.2470,  1.0808,  0.8310,  1.2837,\n",
      "        -1.7779, -1.6034,  2.6021,  2.1201,  1.6791, -2.4881,  0.5171,\n",
      "        -0.8303, -0.3989,  0.0729,  1.6734,  1.8116, -1.7574,  2.0754,\n",
      "         0.0821,  2.7436, -0.4718, -3.4319,  1.6395,  3.0917, -2.0894,\n",
      "        -0.9218, -0.9748,  0.7447,  1.4246,  1.3142,  0.1103, -3.3546,\n",
      "        -2.9479,  1.2459,  0.3943, -1.6950, -2.2550, -3.3813,  2.1158,\n",
      "         1.4592, -1.8017,  2.4179,  0.0491,  2.9096, -1.5254, -0.4820,\n",
      "         0.3837, -1.3550,  1.3072,  1.3357,  1.1340,  3.2454,  2.2717,\n",
      "         1.1681, -2.5664])\n",
      "Parameter containing:\n",
      "tensor(1.00000e-02 *\n",
      "       [[ 6.6118, -5.8799, -5.6224,  ..., -2.8308,  1.6130,  2.3117],\n",
      "        [ 5.6230, -7.6402, -3.0842,  ..., -3.8696,  6.2061, -5.9002],\n",
      "        [-3.8905,  6.3519, -5.9665,  ..., -0.1648, -2.1185, -1.2933],\n",
      "        ...,\n",
      "        [ 6.8186,  8.6024, -6.3402,  ..., -7.1725,  1.5164,  0.4358],\n",
      "        [-2.5287, -1.2489,  3.1559,  ...,  5.4540, -0.7595, -4.3730],\n",
      "        [ 4.9476, -3.3993,  1.2295,  ...,  8.5481, -7.4347,  4.5469]])\n",
      "Parameter containing:\n",
      "tensor(1.00000e-02 *\n",
      "       [-4.2665, -8.4224,  3.8957, -4.5744, -5.5559, -1.9764, -5.7001,\n",
      "        -0.7511, -6.2323, -4.1819,  7.6090, -4.4706, -3.8207,  2.9006,\n",
      "         5.1528,  7.7814,  5.3032,  2.4000,  7.3391, -4.7441,  4.2543,\n",
      "         4.4049, -1.3232,  5.0152, -1.6704, -4.5327,  1.2556, -0.0931,\n",
      "        -8.7371,  7.8578,  3.7794,  4.6325, -6.3968, -3.6761,  6.5102,\n",
      "         2.2799,  5.7632, -8.4905, -4.4629,  3.5130, -6.7430,  3.7210,\n",
      "         4.5112, -7.3436, -6.4811,  6.3507,  6.6141,  4.2889,  2.2299,\n",
      "        -1.1551, -7.1582,  4.3566, -3.2439,  6.8339, -7.5185,  3.7190,\n",
      "        -2.6939, -0.1771,  4.0041, -6.9810, -3.5107, -3.7741,  8.7073,\n",
      "         0.9784])\n",
      "Parameter containing:\n",
      "tensor([[-0.1156,  0.0478,  0.0616, -0.0066, -0.0416,  0.0679,  0.0206,\n",
      "          0.0655, -0.0790,  0.0835,  0.0760,  0.1124,  0.0986, -0.0493,\n",
      "         -0.0347,  0.0515,  0.1063,  0.0494,  0.0595,  0.0682,  0.1170,\n",
      "          0.0899, -0.1067,  0.0376,  0.0708,  0.0139, -0.1158,  0.0311,\n",
      "         -0.0509,  0.0421,  0.0182,  0.0832, -0.0492,  0.0312, -0.0999,\n",
      "         -0.0778,  0.0766,  0.0154, -0.0489, -0.0173,  0.1053, -0.0114,\n",
      "         -0.1161, -0.0816,  0.0791,  0.0699, -0.0501, -0.0844, -0.0436,\n",
      "          0.0475, -0.1048, -0.0036,  0.0216, -0.0255, -0.0483,  0.0618,\n",
      "         -0.1012,  0.0282,  0.1031,  0.0963, -0.0339, -0.0409, -0.0900,\n",
      "          0.0780],\n",
      "        [-0.1092,  0.0088, -0.0426,  0.0808,  0.1203, -0.0687,  0.0719,\n",
      "         -0.0458,  0.0621, -0.0764, -0.0596,  0.0524,  0.0561, -0.0782,\n",
      "         -0.0837,  0.0204,  0.1058, -0.1158, -0.1138, -0.0045,  0.0377,\n",
      "         -0.1221,  0.0042, -0.0447, -0.0881, -0.0242,  0.0043,  0.0937,\n",
      "          0.1025, -0.1106,  0.0193,  0.0884,  0.0952,  0.0523, -0.0701,\n",
      "          0.0619, -0.0630, -0.0392,  0.0586, -0.0436,  0.0939,  0.1035,\n",
      "         -0.0818,  0.1120, -0.1231,  0.0135,  0.0916,  0.0524, -0.0912,\n",
      "          0.0338, -0.0286,  0.0630, -0.0029, -0.0016,  0.0476,  0.1196,\n",
      "          0.0622, -0.0497,  0.0627,  0.0528,  0.0707, -0.0206, -0.0481,\n",
      "         -0.0057],\n",
      "        [-0.0746,  0.1005,  0.1051, -0.0218,  0.0296,  0.0880,  0.0444,\n",
      "         -0.0073, -0.1095, -0.1090,  0.1074,  0.0169, -0.0584, -0.0759,\n",
      "          0.0731,  0.0007, -0.0929, -0.1037,  0.0466,  0.0908,  0.0439,\n",
      "          0.0965,  0.0031, -0.0598,  0.0400,  0.0020,  0.0759,  0.0121,\n",
      "         -0.0259, -0.0308, -0.0550, -0.0732, -0.0540, -0.0185,  0.0064,\n",
      "          0.0245,  0.0490, -0.0285,  0.0665, -0.0285, -0.0247,  0.0209,\n",
      "         -0.0813, -0.0742,  0.0530, -0.0962, -0.0915,  0.0179, -0.0471,\n",
      "          0.0476,  0.0992,  0.0732, -0.0714,  0.0505,  0.0211,  0.0166,\n",
      "          0.0320, -0.0982, -0.0344, -0.0764,  0.0429,  0.0872,  0.0424,\n",
      "          0.0147],\n",
      "        [-0.0164, -0.0382, -0.0536, -0.0941,  0.0881, -0.0055, -0.0429,\n",
      "          0.0311, -0.1157,  0.0331, -0.1165, -0.0494,  0.0229, -0.0027,\n",
      "         -0.0877,  0.0723,  0.0355, -0.0309,  0.0930,  0.0279,  0.0324,\n",
      "         -0.0833, -0.1145,  0.0684, -0.0048, -0.0678,  0.0104,  0.0794,\n",
      "         -0.0760,  0.0932, -0.0475,  0.1190,  0.0043, -0.0639, -0.0486,\n",
      "         -0.1066,  0.0610,  0.0843,  0.0696, -0.0143,  0.0524, -0.0314,\n",
      "         -0.0708, -0.0492,  0.0120, -0.1079, -0.0514, -0.1059, -0.1088,\n",
      "          0.0988, -0.0305, -0.0849,  0.0158, -0.0824,  0.1033, -0.0051,\n",
      "         -0.0442, -0.0562, -0.1185, -0.0407,  0.0941, -0.0040,  0.0132,\n",
      "         -0.0754],\n",
      "        [ 0.0938,  0.1147,  0.0023, -0.0157, -0.0163,  0.1141,  0.1167,\n",
      "         -0.0423,  0.0170, -0.0370, -0.0245, -0.1108, -0.0043,  0.0700,\n",
      "         -0.0491,  0.1237, -0.0400, -0.1136,  0.1244,  0.0252, -0.0029,\n",
      "         -0.0106,  0.0356, -0.0449, -0.0110,  0.0670, -0.0550, -0.0638,\n",
      "          0.1102,  0.0690, -0.1191,  0.0004,  0.0185,  0.0207,  0.0258,\n",
      "         -0.0651, -0.0515, -0.0399, -0.0194, -0.0138,  0.0962,  0.0952,\n",
      "         -0.0591,  0.1115,  0.0217, -0.0004,  0.0801,  0.1140, -0.0576,\n",
      "         -0.0994,  0.0473,  0.0969,  0.0528, -0.1126,  0.0189,  0.0094,\n",
      "          0.0853,  0.1138, -0.0919, -0.0234, -0.0754,  0.0672, -0.0215,\n",
      "         -0.1048],\n",
      "        [ 0.1191,  0.1056, -0.0127,  0.0916, -0.0624, -0.0694,  0.0523,\n",
      "         -0.0315,  0.0693,  0.1197, -0.0222,  0.0428,  0.1163, -0.0914,\n",
      "         -0.0285, -0.0261, -0.0901, -0.1024,  0.0669,  0.0541,  0.0612,\n",
      "          0.1061,  0.0176, -0.0266, -0.0117, -0.1171,  0.0448, -0.0451,\n",
      "          0.0740, -0.0085, -0.0433,  0.1239,  0.0014,  0.0595, -0.0222,\n",
      "          0.0242, -0.1162, -0.0992,  0.1196, -0.0826,  0.0745,  0.1157,\n",
      "          0.0178, -0.0370,  0.0617, -0.0736,  0.1169,  0.0245,  0.0838,\n",
      "         -0.1123,  0.1202, -0.0781,  0.0130, -0.1246,  0.1007,  0.1031,\n",
      "          0.0280, -0.1056,  0.1004,  0.0594, -0.0396,  0.0640, -0.1247,\n",
      "          0.0525],\n",
      "        [ 0.0985, -0.0683, -0.1202, -0.0508,  0.0315, -0.1193, -0.0622,\n",
      "          0.1096, -0.0646, -0.0668, -0.1205,  0.0505,  0.1117, -0.0098,\n",
      "         -0.0791, -0.0047,  0.0948,  0.1165,  0.1093, -0.0008,  0.1132,\n",
      "         -0.0794, -0.0297,  0.0950,  0.0144,  0.0130,  0.1033,  0.0345,\n",
      "         -0.0381, -0.0196,  0.0834,  0.0524,  0.0292,  0.1210, -0.0037,\n",
      "         -0.1051, -0.0395, -0.0169, -0.0704, -0.1053, -0.0806, -0.0609,\n",
      "          0.0266,  0.1034,  0.0929, -0.1187,  0.0170,  0.0521,  0.0566,\n",
      "          0.1137, -0.0370,  0.0997, -0.1121,  0.0793, -0.0370,  0.0375,\n",
      "         -0.1243,  0.0818, -0.0093,  0.0325, -0.0824,  0.0870, -0.1134,\n",
      "          0.0516],\n",
      "        [ 0.0630,  0.0979,  0.1116,  0.0468,  0.0581,  0.0167,  0.0566,\n",
      "          0.0487, -0.0610, -0.1248,  0.1037,  0.0113, -0.0857, -0.0064,\n",
      "         -0.0544, -0.1025,  0.1028, -0.0504, -0.0179,  0.0860,  0.0311,\n",
      "          0.0570, -0.0606, -0.0050,  0.1080,  0.0421, -0.0743, -0.0743,\n",
      "          0.0574, -0.0788, -0.0008,  0.0033, -0.0681,  0.0608,  0.0709,\n",
      "          0.0534, -0.0943,  0.0017,  0.0309, -0.0405, -0.0831, -0.1093,\n",
      "         -0.0639,  0.0849, -0.0586, -0.0784, -0.0013,  0.0146, -0.0718,\n",
      "          0.0621, -0.0744, -0.0070, -0.0853, -0.0287, -0.0907,  0.0585,\n",
      "          0.0701, -0.0735, -0.0663,  0.0744, -0.0495, -0.0306, -0.0157,\n",
      "          0.0674],\n",
      "        [-0.1175,  0.0135, -0.0159,  0.1169,  0.1150, -0.0593,  0.1114,\n",
      "          0.0051,  0.1246, -0.1125, -0.0935,  0.0661, -0.0983,  0.0082,\n",
      "          0.0973,  0.0323, -0.0007,  0.1161, -0.0085,  0.0322,  0.0122,\n",
      "          0.0803,  0.0136,  0.0047,  0.0970,  0.0295, -0.0083,  0.0325,\n",
      "         -0.0336, -0.0414,  0.1043,  0.0433,  0.0486, -0.0818, -0.0341,\n",
      "          0.0878,  0.0607,  0.0399,  0.1129,  0.1141,  0.1010,  0.0923,\n",
      "         -0.0500, -0.1137, -0.0929, -0.0015, -0.0390,  0.1137,  0.1152,\n",
      "         -0.0941,  0.1011,  0.0285,  0.0942,  0.0853, -0.1022,  0.1209,\n",
      "          0.0605, -0.0964,  0.0687,  0.0762, -0.0920,  0.0930, -0.0598,\n",
      "         -0.0363],\n",
      "        [ 0.0675, -0.0126, -0.0291,  0.1144,  0.0427,  0.1141, -0.0564,\n",
      "         -0.1134, -0.0879,  0.0917,  0.0895, -0.0589,  0.1166,  0.0081,\n",
      "          0.0092,  0.0726,  0.0485, -0.0497,  0.1212, -0.0607, -0.0025,\n",
      "          0.0066,  0.0369, -0.1079,  0.0571, -0.0955,  0.1071,  0.0222,\n",
      "         -0.0096, -0.0946,  0.0068,  0.0222,  0.0417, -0.0834,  0.0503,\n",
      "         -0.0290, -0.0980, -0.0585, -0.0479,  0.0470, -0.0598, -0.0981,\n",
      "          0.0652, -0.0065, -0.0511, -0.0315, -0.0483, -0.0538, -0.0438,\n",
      "         -0.0818, -0.0593, -0.1167, -0.0972, -0.1077, -0.0861, -0.0792,\n",
      "          0.0165,  0.0559,  0.0547, -0.0204, -0.1176, -0.1241, -0.0117,\n",
      "         -0.0134]])\n",
      "Parameter containing:\n",
      "tensor([-0.0605, -0.1067, -0.0319, -0.0027,  0.0564,  0.0976,  0.0972,\n",
      "        -0.0675, -0.0780, -0.1053])\n"
     ]
    }
   ],
   "source": [
    "for i in model.parameters():\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training loss: 1.950723188518207\n",
      "Training loss: 0.8936214096256411\n",
      "Training loss: 0.5425369234672234\n",
      "Training loss: 0.4404041236206921\n",
      "Training loss: 0.3902943800094285\n"
     ]
    }
   ],
   "source": [
    "## Your solution here\n",
    "\n",
    "model = nn.Sequential(nn.Linear(784, 128),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(128, 64),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(64, 10),\n",
    "                      nn.LogSoftmax(dim=1))\n",
    "\n",
    "criterion = nn.NLLLoss()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.003)\n",
    "\n",
    "epochs = 5\n",
    "for e in range(epochs):\n",
    "    running_loss = 0\n",
    "    for images, labels in trainloader:\n",
    "        # Flatten MNIST images into a 784 long vector\n",
    "        images = images.view(images.shape[0], -1)\n",
    "    \n",
    "        # TODO: Training pass\n",
    "        # Zero the gradients\n",
    "        optimizer.zero_grad()\n",
    "        # Do a forward pass and get output\n",
    "        output = model.forward(images)\n",
    "        # Calculate loss\n",
    "        loss = criterion(output, labels)\n",
    "        # Do a backwards pass to find gradients\n",
    "        loss.backward()\n",
    "        # Update weights\n",
    "        optimizer.step()\n",
    "        \n",
    "        running_loss += loss.item()\n",
    "    else:\n",
    "        print(f\"Training loss: {running_loss/len(trainloader)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "366.09612844884396"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "running_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the network trained, we can check out it's predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7652 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fec66da5f98>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import helper\n",
    "\n",
    "images, labels = next(iter(trainloader))\n",
    "\n",
    "img = images[0].view(1, 784)\n",
    "# Turn off gradients to speed up this part\n",
    "with torch.no_grad():\n",
    "    logits = model.forward(img)\n",
    "\n",
    "# Output of the network are logits, need to take softmax for probabilities\n",
    "ps = F.softmax(logits, dim=1)\n",
    "helper.view_classify(img.view(1, 28, 28), ps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 1.0032e-05,  2.0539e-05,  4.5163e-06,  2.1405e-04,  8.1418e-02,\n",
       "          1.4443e-03,  1.3010e-05,  6.3836e-01,  1.1517e-03,  2.7737e-01]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now our network is brilliant. It can accurately predict the digits in our images. Next up you'll write the code for training a neural network on a more complex dataset."
   ]
  }
 ],
 "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
}
