{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Classifying Fashion-MNIST\n",
    "\n",
    "Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.\n",
    "\n",
    "<img src='assets/fashion-mnist-sprite.png' width=500px>\n",
    "\n",
    "In this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this.\n",
    "\n",
    "First off, let's load the dataset through torchvision."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz\n",
      "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz\n",
      "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz\n",
      "Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz\n",
      "Processing...\n",
      "Done!\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from torchvision import datasets, transforms\n",
    "import helper\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",
    "# Download and load the training data\n",
    "trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\n",
    "trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n",
    "\n",
    "# Download and load the test data\n",
    "testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\n",
    "testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we can see one of the images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAOsAAADrCAYAAACICmHVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4wLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvpW3flQAABqBJREFUeJzt3ctuXGUWhuEqO3ZsEzskpFsRQcTuSUSkpAUjkDqN1HeC1DOGXB6HETfAAKY4IUwywCYHH8tVfQV7rereSTsfPM90se1y2S97sPLvmi4Wiwnw9lu57BcALEesEEKsEEKsEEKsEEKsEEKsEOLKMv/Rv/7xd8tYeMO++/6HaTV3Z4UQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQYoUQVy77BfB2eu/mzcHZ6pX6z+bZs2ev++W8NtPptJwvFov/0yv577mzQgixQgixQgixQgixQgixQgixQgh71sLbvJO7c+dOOb//0UflfOPqRjk/OT0ZnJ2enpbXvs171rG/s88f/XNwtr6+Xl779bffjPre7qwQQqwQQqwQQqwQQqwQQqwQQqwQ4tL3rN0uc6wxe7U3vUd9+ODh4OzO+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lU6DLXt+97oXsEa2vEj9b+rTaPKu24s0IIsUIIsUIIsUIIsUIIsUIIsUKIpfasp2dno+bVXq07K9vt5MZeX+k+wq8zZl84a/bH3R52MfKjDcs9a3llv1+ev8Hd+Pli3GNQx+yn583uu/s3AR13VgghVgghVgghVgghVgghVgghVgix1J51rGo3NXaX2X1EH/xRuLNCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCCLFCiOlisbjs1wAswZ0VQogVQogVQogVQogVQogVQogVQogVQvwHjF5LNhijqs0AAAAASUVORK5CYII=\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fad8bf30668>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "image, label = next(iter(trainloader))\n",
    "helper.imshow(image[0,:]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building the network\n",
    "\n",
    "Here you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: Define your network architecture here\n",
    "\n",
    "# Import modules\n",
    "from torch import nn, optim\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = nn.Sequential(nn.Linear(784, 256),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(256, 128),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(128, 64),\n",
    "                      nn.ReLU(),\n",
    "                      nn.Linear(64, 10),\n",
    "                      nn.LogSoftmax(dim=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Train the network\n",
    "\n",
    "Now you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).\n",
    "\n",
    "Then write the training code. Remember the training pass is a fairly straightforward process:\n",
    "\n",
    "* Make a forward pass through the network to get the logits \n",
    "* Use the logits 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",
    "By adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: Create the network, define the criterion and optimizer\n",
    "criterion = nn.NLLLoss()\n",
    "optimizer = optim.Adam(model.parameters(), lr=0.003)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training loss: 0.5202356389940166\n",
      "Training loss: 0.3878176898431422\n",
      "Training loss: 0.3550535404860084\n",
      "Training loss: 0.3305503525761272\n",
      "Training loss: 0.31469793412000385\n"
     ]
    }
   ],
   "source": [
    "# TODO: Train the network here\n",
    "epochs = 5\n",
    "\n",
    "for e in range(epochs):\n",
    "    running_loss = 0\n",
    "    for image, label in trainloader:\n",
    "        # Flatten images\n",
    "        image = image.view(image.shape[0], -1)\n",
    "        \n",
    "        # Zero the gradients\n",
    "        optimizer.zero_grad()\n",
    "        \n",
    "        # Do a forward pass\n",
    "        log_ps = model.forward(image)\n",
    "        \n",
    "        # Calculate loss\n",
    "        loss = criterion(log_ps, label)\n",
    "        \n",
    "        # Do a backward pass to find gradients\n",
    "        loss.backward()\n",
    "        \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": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 26088 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7fad51e31470>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 204,
       "width": 423
      },
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "import helper\n",
    "\n",
    "# Test out your network!\n",
    "\n",
    "dataiter = iter(testloader)\n",
    "images, labels = dataiter.next()\n",
    "img = images[0]\n",
    "# Convert 2D image to 1D vector\n",
    "img = img.resize_(1, 784)\n",
    "\n",
    "# TODO: Calculate the class probabilities (softmax) for img\n",
    "ps = torch.exp(model(img))\n",
    "\n",
    "# Plot the image and probabilities\n",
    "helper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
