{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Image Classification\n",
    "In this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html).  The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded.  You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers.  At the end, you'll get to see your neural network's predictions on the sample images.\n",
    "## Get the Data\n",
    "Run the following cell to download the [CIFAR-10 dataset for python](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "All files found!\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "from urllib.request import urlretrieve\n",
    "from os.path import isfile, isdir\n",
    "from tqdm import tqdm\n",
    "import problem_unittests as tests\n",
    "import tarfile\n",
    "\n",
    "cifar10_dataset_folder_path = 'cifar-10-batches-py'\n",
    "\n",
    "class DLProgress(tqdm):\n",
    "    last_block = 0\n",
    "\n",
    "    def hook(self, block_num=1, block_size=1, total_size=None):\n",
    "        self.total = total_size\n",
    "        self.update((block_num - self.last_block) * block_size)\n",
    "        self.last_block = block_num\n",
    "\n",
    "if not isfile('cifar-10-python.tar.gz'):\n",
    "    with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:\n",
    "        urlretrieve(\n",
    "            'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',\n",
    "            'cifar-10-python.tar.gz',\n",
    "            pbar.hook)\n",
    "\n",
    "if not isdir(cifar10_dataset_folder_path):\n",
    "    with tarfile.open('cifar-10-python.tar.gz') as tar:\n",
    "        tar.extractall()\n",
    "        tar.close()\n",
    "\n",
    "\n",
    "tests.test_folder_path(cifar10_dataset_folder_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Explore the Data\n",
    "The dataset is broken into batches to prevent your machine from running out of memory.  The CIFAR-10 dataset consists of 5 batches, named `data_batch_1`, `data_batch_2`, etc.. Each batch contains the labels and images that are one of the following:\n",
    "* airplane\n",
    "* automobile\n",
    "* bird\n",
    "* cat\n",
    "* deer\n",
    "* dog\n",
    "* frog\n",
    "* horse\n",
    "* ship\n",
    "* truck\n",
    "\n",
    "Understanding a dataset is part of making predictions on the data.  Play around with the code cell below by changing the `batch_id` and `sample_id`. The `batch_id` is the id for a batch (1-5). The `sample_id` is the id for a image and label pair in the batch.\n",
    "\n",
    "Ask yourself \"What are all possible labels?\", \"What is the range of values for the image data?\", \"Are the labels in order or random?\".  Answers to questions like these will help you preprocess the data and end up with better predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Stats of batch 1:\n",
      "Samples: 10000\n",
      "Label Counts: {0: 1005, 1: 974, 2: 1032, 3: 1016, 4: 999, 5: 937, 6: 1030, 7: 1001, 8: 1025, 9: 981}\n",
      "First 20 Labels: [6, 9, 9, 4, 1, 1, 2, 7, 8, 3, 4, 7, 7, 2, 9, 9, 9, 3, 2, 6]\n",
      "\n",
      "Example of Image 32:\n",
      "Image - Min Value: 0 Max Value: 255\n",
      "Image - Shape: (32, 32, 3)\n",
      "Label - Label Id: 1 Name: automobile\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAfoAAAH0CAYAAADVH+85AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAWJQAAFiUBSVIk8AA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m6AGgMEUPAIUpegAoTNED\nQGGKHgAKU/QAUJiiB4DCFD0AFKboAaCwTnbFCwD45ecbPQAUpugBoDBFDwCFKXoAKEzRA0Bhih4A\nClP0AFCYogeAwhQ9ABSm6AGgMEUPAIUpegAoTNEDQGGKHgAKU/QAUJiiB4DCFD0AFKboAaAwRQ8A\nhSl6AChM0QNAYYoeAApT9ABQmKIHgMIUPQAUpugBoDBFDwCFKXoAKEzRA0Bhih4AClP0AFCYogeA\nwhQ9ABSm6AGgMEUPAIUpegAoTNEDQGGKHgAKU/QAUJiiB4DCFD0AFKboAaAwRQ8AhSl6AChM0QNA\nYYoeAAr7v3To37eZkHdPAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f961c32c518>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 250,
       "width": 253
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "import helper\n",
    "import numpy as np\n",
    "\n",
    "# Explore the dataset\n",
    "batch_id = 1\n",
    "sample_id = 32\n",
    "helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Implement Preprocess Functions\n",
    "### Normalize\n",
    "In the cell below, implement the `normalize` function to take in image data, `x`, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive.  The return object should be the same shape as `x`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "def normalize(x):\n",
    "    \"\"\"\n",
    "    Normalize a list of sample image data in the range of 0 to 1\n",
    "    : x: List of image data.  The image shape is (32, 32, 3)\n",
    "    : return: Numpy array of normalize data\n",
    "    \"\"\"\n",
    "    return (x - x.min()) / (x.max() - x.min())\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_normalize(normalize)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### One-hot encode\n",
    "Just like the previous code cell, you'll be implementing a function for preprocessing.  This time, you'll implement the `one_hot_encode` function. The input, `x`, are a list of labels.  Implement the function to return the list of labels as One-Hot encoded Numpy array.  The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to `one_hot_encode`.  Make sure to save the map of encodings outside the function.\n",
    "\n",
    "Hint: Don't reinvent the wheel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "encodings = {}\n",
    "for i in range(10):\n",
    "    v = np.zeros(10)\n",
    "    v[i] = 1\n",
    "    encodings[i] = v\n",
    "\n",
    "def one_hot_encode(x):\n",
    "    \"\"\"\n",
    "    One hot encode a list of sample labels. Return a one-hot encoded vector for each label.\n",
    "    : x: List of sample Labels\n",
    "    : return: Numpy array of one-hot encoded labels\n",
    "    \"\"\"\n",
    "    assert np.max(x) < 10 and np.min(x) >= 0, 'label must be between 0 and 9'\n",
    "    encoded = np.array(list(map(lambda v: encodings[v],x)))\n",
    "    return encoded\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_one_hot_encode(one_hot_encode)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Randomize Data\n",
    "As you saw from exploring the data above, the order of the samples are randomized.  It doesn't hurt to randomize it again, but you don't need to for this dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Preprocess all the data and save it\n",
    "Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL\n",
    "\"\"\"\n",
    "# Preprocess Training, Validation, and Testing Data\n",
    "helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Check Point\n",
    "This is your first checkpoint.  If you ever decide to come back to this notebook or have to restart the notebook, you can start from here.  The preprocessed data has been saved to disk."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL\n",
    "\"\"\"\n",
    "import pickle\n",
    "import problem_unittests as tests\n",
    "import helper\n",
    "\n",
    "# Load the Preprocessed Validation data\n",
    "valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Build the network\n",
    "For the neural network, you'll build each layer into a function.  Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function.  This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.\n",
    "\n",
    "If you're finding it hard to dedicate enough time for this course a week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) to build each layer, except \"Convolutional & Max Pooling\" layer.  TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.\n",
    "\n",
    "If you would like to get the most of this course, try to solve all the problems without TF Layers.  Let's begin!\n",
    "### Input\n",
    "The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions\n",
    "* Implement `neural_net_image_input`\n",
    " * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n",
    " * Set the shape using `image_shape` with batch size set to `None`.\n",
    " * Name the TensorFlow placeholder \"x\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n",
    "* Implement `neural_net_label_input`\n",
    " * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n",
    " * Set the shape using `n_classes` with batch size set to `None`.\n",
    " * Name the TensorFlow placeholder \"y\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n",
    "* Implement `neural_net_keep_prob_input`\n",
    " * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) for dropout keep probability.\n",
    " * Name the TensorFlow placeholder \"keep_prob\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n",
    "\n",
    "These names will be used at the end of the project to load your saved model.\n",
    "\n",
    "Note: `None` for shapes in TensorFlow allow for a dynamic size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Image Input Tests Passed.\n",
      "Label Input Tests Passed.\n",
      "Keep Prob Tests Passed.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "def neural_net_image_input(image_shape):\n",
    "    \"\"\"\n",
    "    Return a Tensor for a bach of image input\n",
    "    : image_shape: Shape of the images\n",
    "    : return: Tensor for image input.\n",
    "    \"\"\"\n",
    "    # shape [None, 32, 32, 3]\n",
    "    return tf.placeholder(tf.float32, [None] + list(image_shape), name='x')\n",
    "\n",
    "\n",
    "\n",
    "def neural_net_label_input(n_classes):\n",
    "    \"\"\"\n",
    "    Return a Tensor for a batch of label input\n",
    "    : n_classes: Number of classes\n",
    "    : return: Tensor for label input.\n",
    "    \"\"\"\n",
    "    return tf.placeholder(tf.float32, [None, n_classes], name='y')\n",
    "\n",
    "\n",
    "def neural_net_keep_prob_input():\n",
    "    \"\"\"\n",
    "    Return a Tensor for keep probability\n",
    "    : return: Tensor for keep probability.\n",
    "    \"\"\"\n",
    "    # TODO: Implement Function\n",
    "    return tf.placeholder(tf.float32, name='keep_prob')\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tf.reset_default_graph()\n",
    "tests.test_nn_image_inputs(neural_net_image_input)\n",
    "tests.test_nn_label_inputs(neural_net_label_input)\n",
    "tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Convolution and Max Pooling Layer\n",
    "Convolution layers have a lot of success with images. For this code cell, you should implement the function `conv2d_maxpool` to apply convolution then max pooling:\n",
    "* Create the weight and bias using `conv_ksize`, `conv_num_outputs` and the shape of `x_tensor`.\n",
    "* Apply a convolution to `x_tensor` using weight and `conv_strides`.\n",
    " * We recommend you use same padding, but you're welcome to use any padding.\n",
    "* Add bias\n",
    "* Add a nonlinear activation to the convolution.\n",
    "* Apply Max Pooling using `pool_ksize` and `pool_strides`.\n",
    " * We recommend you use same padding, but you're welcome to use any padding.\n",
    "\n",
    "Note: You **can't** use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for this layer.  You're free to use any TensorFlow package for all the other layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):\n",
    "    \"\"\"\n",
    "    Apply convolution then max pooling to x_tensor\n",
    "    :param x_tensor: TensorFlow Tensor\n",
    "    :param conv_num_outputs: Number of outputs for the convolutional layer\n",
    "    :param conv_strides: Stride 2-D Tuple for convolution\n",
    "    :param pool_ksize: kernal size 2-D Tuple for pool\n",
    "    :param pool_strides: Stride 2-D Tuple for pool\n",
    "    : return: A tensor that represents convolution and max pooling of x_tensor\n",
    "    \"\"\"\n",
    "    w_conv = tf.Variable(tf.truncated_normal((conv_ksize[0], # Kernel height\n",
    "                                                 conv_ksize[1], # Kernel width\n",
    "                                                 x_tensor.get_shape()[3].value, # Input channels\n",
    "                                                 conv_num_outputs), stddev=0.05)) # output depth\n",
    "    bias_conv = tf.Variable(tf.random_normal([conv_num_outputs], stddev=0.05))\n",
    "    \n",
    "    padding = 'VALID'\n",
    "    \n",
    "    \n",
    "    # DEBUG\n",
    "    #print('conv ksize: ', conv_ksize)\n",
    "    #print('conv strides: ',conv_strides)\n",
    "    #print('pool ksize: ', pool_ksize)\n",
    "    #print('pool strides: ',pool_strides)\n",
    "    #print('conv_depth: ', conv_num_outputs)\n",
    "    #print('x_tensor :',x_tensor)\n",
    "    #print('conv weights :', w_conv) \n",
    "    # DEBUG\n",
    "    \n",
    "    \n",
    "    # Apply conv to x_tensor\n",
    "    cv1 = tf.nn.conv2d(x_tensor,\n",
    "                       w_conv,\n",
    "                       [1, conv_strides[0], conv_strides[1], 1],\n",
    "                       padding=padding\n",
    "                      )\n",
    "    # add bias\n",
    "    cv1 = tf.nn.bias_add(cv1, bias_conv)\n",
    "    \n",
    "    # Apply relu\n",
    "    cv1 = tf.nn.relu(cv1)\n",
    "    \n",
    "    # Apply Maxpooling\n",
    "    cv1 = tf.nn.max_pool(cv1,\n",
    "                         ksize=[1,pool_ksize[0], pool_ksize[1], 1],\n",
    "                         strides=[1, pool_strides[0], pool_strides[1], 1],\n",
    "                         padding=padding\n",
    "                        )\n",
    "    \n",
    "     \n",
    "    \n",
    "    #print('conv layer :', cv1.get_shape())\n",
    "    return cv1 \n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_con_pool(conv2d_maxpool)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Flatten Layer\n",
    "Implement the `flatten` function to change the dimension of `x_tensor` from a 4-D tensor to a 2-D tensor.  The output should be the shape (*Batch Size*, *Flattened Image Size*). You can use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for this layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "\n",
    "def flatten(x_tensor):\n",
    "    \"\"\"\n",
    "    Flatten x_tensor to (Batch Size, Flattened Image Size)\n",
    "    : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.\n",
    "    : return: A tensor of size (Batch Size, Flattened Image Size).\n",
    "    \"\"\"\n",
    "    flat_size = np.multiply.reduce(x_tensor.get_shape()[1:].as_list())\n",
    "    return tf.reshape(x_tensor, [-1, flat_size])\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_flatten(flatten)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Fully-Connected Layer\n",
    "Implement the `fully_conn` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). You can use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for this layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "def fully_conn(x_tensor, num_outputs):\n",
    "    \"\"\"\n",
    "    Apply a fully connected layer to x_tensor using weight and bias\n",
    "    : x_tensor: A 2-D tensor where the first dimension is batch size.\n",
    "    : num_outputs: The number of output that the new tensor should be.\n",
    "    : return: A 2-D tensor where the second dimension is num_outputs.\n",
    "    \"\"\"\n",
    "    full_w = tf.Variable(tf.truncated_normal((x_tensor.get_shape()[1].value, num_outputs), stddev=0.05))\n",
    "    full_b = tf.Variable(tf.random_normal([num_outputs], stddev=0.05))\n",
    "    \n",
    "    full = tf.add(tf.matmul(x_tensor, full_w), full_b)\n",
    "    full = tf.nn.relu(full)\n",
    "    return full\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_fully_conn(fully_conn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Output Layer\n",
    "Implement the `output` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). You can use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for this layer.\n",
    "\n",
    "Note: Activation, softmax, or cross entropy shouldn't be applied to this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "def output(x_tensor, num_outputs):\n",
    "    \"\"\"\n",
    "    Apply a output layer to x_tensor using weight and bias\n",
    "    : x_tensor: A 2-D tensor where the first dimension is batch size.\n",
    "    : num_outputs: The number of output that the new tensor should be.\n",
    "    : return: A 2-D tensor where the second dimension is num_outputs.\n",
    "    \"\"\"\n",
    "    out_w = tf.Variable(tf.truncated_normal((x_tensor.get_shape()[1].value, num_outputs)))\n",
    "    out_b = tf.Variable(tf.zeros(num_outputs))\n",
    "    \n",
    "    out = tf.add(tf.matmul(x_tensor, out_w), out_b)\n",
    "    return out\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_output(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Create Convolutional Model\n",
    "Implement the function `conv_net` to create a convolutional neural network model. The function takes in a batch of images, `x`, and outputs logits.  Use the layers you created above to create this model:\n",
    "\n",
    "* Apply 1, 2, or 3 Convolution and Max Pool layers\n",
    "* Apply a Flatten Layer\n",
    "* Apply 1, 2, or 3 Fully Connected Layers\n",
    "* Apply an Output Layer\n",
    "* Return the output\n",
    "* Apply [TensorFlow's Dropout](https://www.tensorflow.org/api_docs/python/tf/nn/dropout) to one or more layers in the model using `keep_prob`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------\n",
      "Tensor(\"x:0\", shape=(?, 32, 32, 3), dtype=float32)\n",
      "Tensor(\"MaxPool:0\", shape=(?, 15, 15, 60), dtype=float32)\n",
      "Tensor(\"MaxPool_1:0\", shape=(?, 6, 6, 120), dtype=float32)\n",
      "Tensor(\"MaxPool_2:0\", shape=(?, 2, 2, 400), dtype=float32)\n",
      "Tensor(\"Reshape:0\", shape=(?, 1600), dtype=float32)\n",
      "Tensor(\"dropout/mul:0\", shape=(?, 600), dtype=float32)\n",
      "Tensor(\"dropout_1/mul:0\", shape=(?, 60), dtype=float32)\n",
      "Tensor(\"Add_2:0\", shape=(?, 10), dtype=float32)\n",
      "--------------\n",
      "Tensor(\"Placeholder:0\", shape=(?, 32, 32, 3), dtype=float32)\n",
      "Tensor(\"MaxPool_3:0\", shape=(?, 15, 15, 60), dtype=float32)\n",
      "Tensor(\"MaxPool_4:0\", shape=(?, 6, 6, 120), dtype=float32)\n",
      "Tensor(\"MaxPool_5:0\", shape=(?, 2, 2, 400), dtype=float32)\n",
      "Tensor(\"Reshape_4:0\", shape=(?, 1600), dtype=float32)\n",
      "Tensor(\"dropout_2/mul:0\", shape=(?, 600), dtype=float32)\n",
      "Tensor(\"dropout_3/mul:0\", shape=(?, 60), dtype=float32)\n",
      "Tensor(\"Add_5:0\", shape=(?, 10), dtype=float32)\n",
      "Neural Network Built!\n"
     ]
    }
   ],
   "source": [
    "def conv_net(x, keep_prob):\n",
    "    \"\"\"\n",
    "    Create a convolutional neural network model\n",
    "    : x: Placeholder tensor that holds image data.\n",
    "    : keep_prob: Placeholder tensor that hold dropout keep probability.\n",
    "    : return: Tensor that represents logits\n",
    "    \"\"\"\n",
    "    \n",
    "    \n",
    "    conv1_hyper_params = {\n",
    "        'conv_num_outputs': 60,\n",
    "        'conv_ksize': (3,3),\n",
    "        'conv_strides': (1,1),\n",
    "        'pool_ksize': (2,2),\n",
    "        'pool_strides': (2,2)\n",
    "    }\n",
    "    \n",
    "    conv2_hyper_params = {\n",
    "        'conv_num_outputs': 120,\n",
    "        'conv_ksize': (3,3),\n",
    "        'conv_strides': (1,1),\n",
    "        'pool_ksize': (2,2),\n",
    "        'pool_strides': (2,2)\n",
    "    }\n",
    "    \n",
    "    conv3_hyper_params = {\n",
    "        'conv_num_outputs': 400,\n",
    "        'conv_ksize': (3,3),\n",
    "        'conv_strides': (1,1),\n",
    "        'pool_ksize': (2,2),\n",
    "        'pool_strides': (2,2)\n",
    "    }\n",
    "    \n",
    "   \n",
    "    conv1 = conv2d_maxpool(x, **conv1_hyper_params)  \n",
    "    conv2 = conv2d_maxpool(conv1, **conv2_hyper_params)\n",
    "    conv3 = conv2d_maxpool(conv2, **conv3_hyper_params)\n",
    "\n",
    "    \n",
    "    \n",
    "    \n",
    "    flat = flatten(conv3)\n",
    "    \n",
    "    \n",
    "    \n",
    "    \n",
    "    full1 = fully_conn(flat, 600)\n",
    "    full1 = tf.nn.dropout(full1, keep_prob)\n",
    "    \n",
    "    \n",
    "    full2 = fully_conn(full1, 60)\n",
    "    full2 = tf.nn.dropout(full2, keep_prob)\n",
    "\n",
    "\n",
    "    \n",
    "    \n",
    "    \n",
    "    # TODO: Apply an Output Layer\n",
    "    #    Set this to the number of classes\n",
    "    # Function Definition from Above:\n",
    "    #   output(x_tensor, num_outputs)\n",
    "    out = output(full2, 10)\n",
    "    \n",
    "    \n",
    "    # DEBUG\n",
    "    print(x)\n",
    "    print(conv1)\n",
    "    print(conv2)\n",
    "    print(conv3)\n",
    "    print(flat)\n",
    "    print(full1)\n",
    "    print(full2)\n",
    "    print(out)\n",
    "    # DEBUG\n",
    "    \n",
    "    \n",
    "    return out\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "\n",
    "##############################\n",
    "## Build the Neural Network ##\n",
    "##############################\n",
    "\n",
    "# Remove previous weights, bias, inputs, etc..\n",
    "tf.reset_default_graph()\n",
    "\n",
    "# Inputs\n",
    "x = neural_net_image_input((32, 32, 3))\n",
    "y = neural_net_label_input(10)\n",
    "keep_prob = neural_net_keep_prob_input()\n",
    "\n",
    "# Model\n",
    "logits = conv_net(x, keep_prob)\n",
    "\n",
    "# Name logits Tensor, so that is can be loaded from disk after training\n",
    "logits = tf.identity(logits, name='logits')\n",
    "\n",
    "# Loss and Optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\n",
    "optimizer = tf.train.AdamOptimizer().minimize(cost)\n",
    "\n",
    "# Accuracy\n",
    "correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\n",
    "\n",
    "tests.test_conv_net(conv_net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Train the Neural Network\n",
    "### Single Optimization\n",
    "Implement the function `train_neural_network` to do a single optimization.  The optimization should use `optimizer` to optimize in `session` with a `feed_dict` of the following:\n",
    "* `x` for image input\n",
    "* `y` for labels\n",
    "* `keep_prob` for keep probability for dropout\n",
    "\n",
    "This function will be called for each batch, so `tf.global_variables_initializer()` has already been called.\n",
    "\n",
    "Note: Nothing needs to be returned. This function is only optimizing the neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tests Passed\n"
     ]
    }
   ],
   "source": [
    "def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):\n",
    "    \"\"\"\n",
    "    Optimize the session on a batch of images and labels\n",
    "    : session: Current TensorFlow session\n",
    "    : optimizer: TensorFlow optimizer function\n",
    "    : keep_probability: keep probability\n",
    "    : feature_batch: Batch of Numpy image data\n",
    "    : label_batch: Batch of Numpy label data\n",
    "    \"\"\"\n",
    "    session.run([optimizer], feed_dict={x: feature_batch,\n",
    "                                        y: label_batch,\n",
    "                                        keep_prob: keep_probability\n",
    "                                       })\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
    "\"\"\"\n",
    "tests.test_train_nn(train_neural_network)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Show Stats\n",
    "Implement the function `print_stats` to print loss and validation accuracy.  Use the global variables `valid_features` and `valid_labels` to calculate validation accuracy.  Use a keep probability of `1.0` to calculate the loss and validation accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "def print_stats(session, feature_batch, label_batch, cost, accuracy):\n",
    "    \"\"\"\n",
    "    Print information about loss and validation accuracy\n",
    "    : session: Current TensorFlow session\n",
    "    : feature_batch: Batch of Numpy image data\n",
    "    : label_batch: Batch of Numpy label data\n",
    "    : cost: TensorFlow cost function\n",
    "    : accuracy: TensorFlow accuracy function\n",
    "    \"\"\"\n",
    "    loss_feed = {\n",
    "        x: feature_batch,\n",
    "        y: label_batch,\n",
    "        keep_prob: 1.\n",
    "    }\n",
    "    \n",
    "    valid_feed = {\n",
    "        x: valid_features,\n",
    "        y: valid_labels,\n",
    "        keep_prob: 1.\n",
    "    }\n",
    "    \n",
    "    loss = session.run(cost, loss_feed)\n",
    "    accuracy = session.run(accuracy, valid_feed)\n",
    "    \n",
    "    print('Loss: {:>10.4f} - Valid Accuracy: {:.2f}%'.format(loss,accuracy*100))\n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Hyperparameters\n",
    "Tune the following parameters:\n",
    "* Set `epochs` to the number of iterations until the network stops learning or start overfitting\n",
    "* Set `batch_size` to the highest number that your machine has memory for.  Most people set them to common sizes of memory:\n",
    " * 64\n",
    " * 128\n",
    " * 256\n",
    " * ...\n",
    "* Set `keep_probability` to the probability of keeping a node using dropout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "# TODO: Tune Parameters\n",
    "epochs = 9\n",
    "batch_size = 512\n",
    "keep_probability = 0.75"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Train on a Single CIFAR-10 Batch\n",
    "Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy.  Once the final validation accuracy is 50% or greater, run the model on all the data in the next section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL\n",
    "\"\"\"\n",
    "print('Checking the Training on a Single Batch...')\n",
    "with tf.Session() as sess:\n",
    "    # Initializing the variables\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    \n",
    "    # Training cycle\n",
    "    for epoch in range(epochs):\n",
    "        batch_i = 1\n",
    "        for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n",
    "            train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n",
    "        print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')\n",
    "        print_stats(sess, batch_features, batch_labels, cost, accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "### Fully Train the Model\n",
    "Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training...\n",
      "Epoch  1, CIFAR-10 Batch 1:  Loss:     2.2161 - Valid Accuracy: 18.40%\n",
      "Epoch  1, CIFAR-10 Batch 2:  Loss:     2.0625 - Valid Accuracy: 25.98%\n",
      "Epoch  1, CIFAR-10 Batch 3:  Loss:     1.7185 - Valid Accuracy: 34.68%\n",
      "Epoch  1, CIFAR-10 Batch 4:  Loss:     1.6533 - Valid Accuracy: 39.72%\n",
      "Epoch  1, CIFAR-10 Batch 5:  Loss:     1.5159 - Valid Accuracy: 43.98%\n",
      "Epoch  2, CIFAR-10 Batch 1:  Loss:     1.6357 - Valid Accuracy: 47.40%\n",
      "Epoch  2, CIFAR-10 Batch 2:  Loss:     1.4579 - Valid Accuracy: 48.64%\n",
      "Epoch  2, CIFAR-10 Batch 3:  Loss:     1.2390 - Valid Accuracy: 51.38%\n",
      "Epoch  2, CIFAR-10 Batch 4:  Loss:     1.2468 - Valid Accuracy: 53.06%\n",
      "Epoch  2, CIFAR-10 Batch 5:  Loss:     1.2385 - Valid Accuracy: 53.86%\n",
      "Epoch  3, CIFAR-10 Batch 1:  Loss:     1.3218 - Valid Accuracy: 55.72%\n",
      "Epoch  3, CIFAR-10 Batch 2:  Loss:     1.1992 - Valid Accuracy: 54.00%\n",
      "Epoch  3, CIFAR-10 Batch 3:  Loss:     1.0670 - Valid Accuracy: 57.56%\n",
      "Epoch  3, CIFAR-10 Batch 4:  Loss:     1.0798 - Valid Accuracy: 57.62%\n",
      "Epoch  3, CIFAR-10 Batch 5:  Loss:     1.0199 - Valid Accuracy: 59.20%\n",
      "Epoch  4, CIFAR-10 Batch 1:  Loss:     1.0873 - Valid Accuracy: 61.30%\n",
      "Epoch  4, CIFAR-10 Batch 2:  Loss:     1.0366 - Valid Accuracy: 61.46%\n",
      "Epoch  4, CIFAR-10 Batch 3:  Loss:     0.9007 - Valid Accuracy: 61.18%\n",
      "Epoch  4, CIFAR-10 Batch 4:  Loss:     0.8702 - Valid Accuracy: 63.08%\n",
      "Epoch  4, CIFAR-10 Batch 5:  Loss:     0.8193 - Valid Accuracy: 65.02%\n",
      "Epoch  5, CIFAR-10 Batch 1:  Loss:     0.9168 - Valid Accuracy: 63.96%\n",
      "Epoch  5, CIFAR-10 Batch 2:  Loss:     0.8561 - Valid Accuracy: 65.00%\n",
      "Epoch  5, CIFAR-10 Batch 3:  Loss:     0.7567 - Valid Accuracy: 65.08%\n",
      "Epoch  5, CIFAR-10 Batch 4:  Loss:     0.7559 - Valid Accuracy: 65.62%\n",
      "Epoch  5, CIFAR-10 Batch 5:  Loss:     0.7026 - Valid Accuracy: 66.76%\n",
      "Epoch  6, CIFAR-10 Batch 1:  Loss:     0.8156 - Valid Accuracy: 67.12%\n",
      "Epoch  6, CIFAR-10 Batch 2:  Loss:     0.7452 - Valid Accuracy: 67.18%\n",
      "Epoch  6, CIFAR-10 Batch 3:  Loss:     0.6952 - Valid Accuracy: 65.44%\n",
      "Epoch  6, CIFAR-10 Batch 4:  Loss:     0.6694 - Valid Accuracy: 66.68%\n",
      "Epoch  6, CIFAR-10 Batch 5:  Loss:     0.6272 - Valid Accuracy: 67.82%\n",
      "Epoch  7, CIFAR-10 Batch 1:  Loss:     0.7157 - Valid Accuracy: 68.12%\n",
      "Epoch  7, CIFAR-10 Batch 2:  Loss:     0.6450 - Valid Accuracy: 67.92%\n",
      "Epoch  7, CIFAR-10 Batch 3:  Loss:     0.6158 - Valid Accuracy: 66.10%\n",
      "Epoch  7, CIFAR-10 Batch 4:  Loss:     0.5492 - Valid Accuracy: 68.74%\n",
      "Epoch  7, CIFAR-10 Batch 5:  Loss:     0.5193 - Valid Accuracy: 68.12%\n",
      "Epoch  8, CIFAR-10 Batch 1:  Loss:     0.6347 - Valid Accuracy: 69.08%\n",
      "Epoch  8, CIFAR-10 Batch 2:  Loss:     0.5660 - Valid Accuracy: 69.54%\n",
      "Epoch  8, CIFAR-10 Batch 3:  Loss:     0.4913 - Valid Accuracy: 67.54%\n",
      "Epoch  8, CIFAR-10 Batch 4:  Loss:     0.4737 - Valid Accuracy: 69.96%\n",
      "Epoch  8, CIFAR-10 Batch 5:  Loss:     0.4385 - Valid Accuracy: 70.38%\n",
      "Epoch  9, CIFAR-10 Batch 1:  Loss:     0.5353 - Valid Accuracy: 69.56%\n",
      "Epoch  9, CIFAR-10 Batch 2:  Loss:     0.4946 - Valid Accuracy: 69.56%\n",
      "Epoch  9, CIFAR-10 Batch 3:  Loss:     0.4304 - Valid Accuracy: 68.02%\n",
      "Epoch  9, CIFAR-10 Batch 4:  Loss:     0.4035 - Valid Accuracy: 70.64%\n",
      "Epoch  9, CIFAR-10 Batch 5:  Loss:     0.3885 - Valid Accuracy: 70.56%\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL\n",
    "\"\"\"\n",
    "save_model_path = './image_classification'\n",
    "\n",
    "print('Training...')\n",
    "with tf.Session() as sess:\n",
    "    # Initializing the variables\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    \n",
    "    # Training cycle\n",
    "    for epoch in range(epochs):\n",
    "        # Loop over all batches\n",
    "        n_batches = 5\n",
    "        for batch_i in range(1, n_batches + 1):\n",
    "            for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n",
    "                train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n",
    "            print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')\n",
    "            print_stats(sess, batch_features, batch_labels, cost, accuracy)\n",
    "            \n",
    "    # Save Model\n",
    "    saver = tf.train.Saver()\n",
    "    save_path = saver.save(sess, save_model_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Checkpoint\n",
    "The model has been saved to disk.\n",
    "## Test Model\n",
    "Test your model against the test dataset.  This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "DON'T MODIFY ANYTHING IN THIS CELL\n",
    "\"\"\"\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "import tensorflow as tf\n",
    "import pickle\n",
    "import helper\n",
    "import random\n",
    "\n",
    "# Set batch size if not already set\n",
    "try:\n",
    "    if batch_size:\n",
    "        pass\n",
    "except NameError:\n",
    "    batch_size = 64\n",
    "\n",
    "save_model_path = './image_classification'\n",
    "n_samples = 4\n",
    "top_n_predictions = 3\n",
    "\n",
    "def test_model():\n",
    "    \"\"\"\n",
    "    Test the saved model against the test dataset\n",
    "    \"\"\"\n",
    "\n",
    "    test_features, test_labels = pickle.load(open('preprocess_training.p', mode='rb'))\n",
    "    loaded_graph = tf.Graph()\n",
    "\n",
    "    with tf.Session(graph=loaded_graph) as sess:\n",
    "        # Load model\n",
    "        loader = tf.train.import_meta_graph(save_model_path + '.meta')\n",
    "        loader.restore(sess, save_model_path)\n",
    "\n",
    "        # Get Tensors from loaded model\n",
    "        loaded_x = loaded_graph.get_tensor_by_name('x:0')\n",
    "        loaded_y = loaded_graph.get_tensor_by_name('y:0')\n",
    "        loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n",
    "        loaded_logits = loaded_graph.get_tensor_by_name('logits:0')\n",
    "        loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')\n",
    "        \n",
    "        # Get accuracy in batches for memory limitations\n",
    "        test_batch_acc_total = 0\n",
    "        test_batch_count = 0\n",
    "        \n",
    "        for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):\n",
    "            test_batch_acc_total += sess.run(\n",
    "                loaded_acc,\n",
    "                feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})\n",
    "            test_batch_count += 1\n",
    "\n",
    "        print('Testing Accuracy: {}\\n'.format(test_batch_acc_total/test_batch_count))\n",
    "\n",
    "        # Print Random Samples\n",
    "        random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))\n",
    "        random_test_predictions = sess.run(\n",
    "            tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),\n",
    "            feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})\n",
    "        helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)\n",
    "\n",
    "\n",
    "test_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Why 50-70% Accuracy?\n",
    "You might be wondering why you can't get an accuracy any higher. First things first, 50% isn't bad for a simple CNN.  Pure guessing would get you 10% accuracy. However, you might notice people are getting scores [well above 70%](http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html#43494641522d3130).  That's because we haven't taught you all there is to know about neural networks. We still need to cover a few more techniques.\n",
    "## Submitting This Project\n",
    "When submitting this project, make sure to run all the cells before saving the notebook.  Save the notebook file as \"dlnd_image_classification.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\".  Include the \"helper.py\" and \"problem_unittests.py\" files in your submission."
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "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.5.2"
  },
  "widgets": {
   "state": {},
   "version": "1.1.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
