{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convolutional neural networks\n",
    "\n",
    "We have seen before that neural networks are quite good at dealing with images, and even one-layer perceptron is able to recognize handwritten digits from MNIST dataset with reasonable accuracy. However, MNIST dataset is very special, and all digits are centered inside the image, which makes the task simpler.\n",
    "\n",
    "In real life, we want to be able to recognize objects on the picture regardless of their exact location in the image. Computer vision is different from generic classification, because when we are trying to find a certain object in the picture, we are scanning the image looking for some specific **patterns** and their combinations. For example, when looking for a cat, we first may look for horizontal lines, which can form whiskers, and then certain combination of whiskers can tell us that it is actually a picture of a cat. Relative position and presence of certain patterns is important, and not their exact position on the image.  \n",
    "\n",
    "To extract patterns, we will use the notion of **convolutional filters**. But first, let us load all dependencies and functions that we have defined in the previous units. We will also import `tfcv` helper library that contain some useful functions that we do not want to define inside this notebook to keep the code short and clean. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from tfcv import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, we will focus on the MNIST dataset that we have seen before, and on image classification. We will start by loading the dataset using Keras built-in functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "(x_train,y_train),(x_test,y_test) = keras.datasets.mnist.load_data()\n",
    "x_train = x_train.astype(np.float32) / 255.0\n",
    "x_test = x_test.astype(np.float32) / 255.0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Convolutional filters\n",
    "\n",
    "Convolutional filters are small windows that run over each pixel of the image and compute weighted average of the neighboring pixels.\n",
    "\n",
    "\n",
    "\n",
    "They are defined by matrices of weight coefficients. Let's see the examples of applying two different convolutional filters over our MNIST handwritten digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 41132 characters]",
      "text/plain": [
       "<Figure size 576x216 with 12 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 42844 characters]",
      "text/plain": [
       "<Figure size 576x216 with 12 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_convolution(x_train[:5],[[-1.,0.,1.],[-1.,0.,1.],[-1.,0.,1.]],'Vertical edge filter')\n",
    "plot_convolution(x_train[:5],[[-1.,-1.,-1.],[0.,0.,0.],[1.,1.,1.]],'Horizontal edge filter')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First filter is called a **vertical edge filter**, and it is defined by the following matrix:\n",
    "$$\n",
    "\\left(\n",
    "    \\begin{matrix}\n",
    "     -1 & 0 & 1 \\cr\n",
    "     -1 & 0 & 1 \\cr\n",
    "     -1 & 0 & 1 \\cr\n",
    "    \\end{matrix}\n",
    "\\right)\n",
    "$$\n",
    "When this filter goes over relatively uniform pixel field, all values add up to 0. However, when it encounters a vertical edge in the image, high spike value is generated. That's why in the images above you can see vertical edges represented by high and low values, while horizontal edges are averaged out.\n",
    "\n",
    "An opposite thing happens when we apply horizontal edge filter - horizontal lines are amplified, and vertical are averaged out.\n",
    "\n",
    "In classical computer vision, multiple filters were applied to the image to generate features, which then were used by machine learning algorithm to build a classifier. Those filters are in fact similar to neural structures that are available in the vision system of some animals.\n",
    "\n",
    "<img src=\"images/lmfilters.jpg\" width=\"400\"/>\n",
    "\n",
    "However, in deep learning we construct networks that **learn** best convolutional filters to solve classification problem. To do that, we introduce **convolutional layers**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Covolutional layers\n",
    "\n",
    "To make the weights of convolutional layer trainable, we need somehow to reduce the process of applying convolutional filter window to the image to the matrix operations, which can then be subject to backward propagation training. To do this, we use a clever matrix transformation, which we call **im2col**.\n",
    "\n",
    "Suppose we have a small image $\\mathbf{x}$, with the following pixels:\n",
    "\n",
    "$$\n",
    "\\mathbf{x} = \\left(\n",
    "         \\begin{array}{ccccc}\n",
    "           a & b & c & d & e \\\\\n",
    "           f & g & h & i & j \\\\\n",
    "           k & l & m & n & o \\\\\n",
    "           p & q & r & s & t \\\\\n",
    "           u & v & w & x & y \\\\\n",
    "         \\end{array}\n",
    "     \\right)\n",
    "$$\n",
    "\n",
    "And we want to apply two conv filters, with the following weights:\n",
    "$$\n",
    "W^{(i)} = \\left(\\begin{array}{ccc}\n",
    "            w^{(i)}_{00} & w^{(i)}_{01} & w^{(i)}_{02} \\\\\n",
    "            w^{(i)}_{10} & w^{(i)}_{11} & w^{(i)}_{12} \\\\\n",
    "            w^{(i)}_{20} & w^{(i)}_{21} & w^{(i)}_{22} \\\\\n",
    "            \\end{array}\\right) \n",
    "$$\n",
    "\n",
    "When applying the convolution, the first pixel of the result would be obtained by element-wise multiplication of \n",
    "$\\left(\\begin{array}{ccc}\n",
    "  a & b & c \\\\\n",
    "  f & g & h \\\\\n",
    "  k & l & m \\\\\n",
    "\\end{array}\\right)$ and $W^{(i)}$, the second element - by multiplying by $\\left(\\begin{array}{ccc}\n",
    "  b & c & d \\\\\n",
    "  g & h & i \\\\\n",
    "  l & m & n \\\\\n",
    "\\end{array}\\right)$ by $W^{(i)}$, and so on.\n",
    "\n",
    "To formalize this process, let's extract all $3\\times3$ fragments of the original image $x$ into the following matrix:\n",
    "\n",
    "$$\n",
    "\\mathrm{im2col}(x) = \\left[\n",
    "        \\begin{array}{cccccc}\n",
    "          a & b & \\ldots & g & \\ldots & m \\\\\n",
    "          b & c & \\ldots & h & \\ldots & n \\\\\n",
    "          c & d & \\ldots & i & \\ldots & o \\\\\n",
    "          f & g & \\ldots & l & \\ldots & r \\\\\n",
    "          g & h & \\ldots & m & \\ldots & s \\\\\n",
    "          h & i & \\ldots & n & \\ldots & t \\\\\n",
    "          k & l & \\ldots & q & \\ldots & w \\\\\n",
    "          l & m & \\ldots & r & \\ldots & x \\\\\n",
    "          m & n & \\ldots & s & \\ldots & y \\\\\n",
    "        \\end{array}\n",
    "    \\right]\n",
    "$$\n",
    "\n",
    "Each column of this matrix corresponds to each $3\\times3$ subregion of the original image. Now, to get the result of the convolution, we just need to multiply this matrix by the matrix or weights\n",
    "$$\n",
    "\\mathbf{W} = \\left[\n",
    "         \\begin{array}{cccccccc}\n",
    "            w^{(0)}_{00} & w^{(0)}_{01} & w^{(0)}_{02} & w^{(0)}_{10} & w^{(0)}_{11} & \\ldots & w^{(0)}_{21} & w^{(0)}_{22} \\\\\n",
    "            w^{(1)}_{00} & w^{(1)}_{01} & w^{(1)}_{02} & w^{(1)}_{10} & w^{(1)}_{11} & \\ldots & w^{(1)}_{21} & w^{(1)}_{22} \\\\\n",
    "         \\end{array}\n",
    "       \\right]\n",
    "$$\n",
    "(each row of this matrix contains weights of $i$-th filter, flattened into one row)\n",
    "\n",
    "So the application of a convolution filter to the original image can be replaced by matrix multiplication, which we already know how to handle using back prop:\n",
    "$$\n",
    "C(x) = W\\times\\mathbf{im2col}(x)\n",
    "$$\n",
    "\n",
    "Convolutional layers are defined using `Conv2d` class. We need to specify the following:\n",
    "* `filters` - number of filters to use. We will use 9 different filters, which will give the network plenty of opportunities to explore which filters work best for our scenario.\n",
    "* `kernel_size` is the size of the sliding window. Usually 3x3 or 5x5 filters are used.\n",
    "\n",
    "Simplest CNN will contain one convolutional layer. Given the input size 28x28, after applying nine 5x5 filters we will end up with a tensor of 24x24x9. The spatial dimension is smaller, because there are only 24 positions where a sliding interval of length 5 can fit into 28 pixels).\n",
    "\n",
    "After convolution, we flatten 24x24x9 tensor into one vector of size 5184, and then add linear layer, to produce 10 classes. We also use `relu` activation function in between layers. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " conv2d (Conv2D)             (None, 24, 24, 9)         234       \n",
      "                                                                 \n",
      " flatten (Flatten)           (None, 5184)              0         \n",
      "                                                                 \n",
      " dense (Dense)               (None, 10)                51850     \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 52,084\n",
      "Trainable params: 52,084\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = keras.models.Sequential([\n",
    "    keras.layers.Conv2D(filters=9, kernel_size=(5,5), input_shape=(28,28,1),activation='relu'),\n",
    "    keras.layers.Flatten(),\n",
    "    keras.layers.Dense(10)\n",
    "])\n",
    "\n",
    "model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['acc'])\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see that this network contains around 50k trainable parameters, compared to around 80k in fully-connected multi-layered networks. This allows us to achieve good results even on smaller datasets, because convolutional networks generalize much better.\n",
    "\n",
    "> **Note**: In most of the practical cases, we want to apply convolutional layers to color images. Thus, `Conv2D` layer expects the input to be of the shape $W\\times H\\times C$, where $W$ and $H$ are width and height of the image, and $C$ is the number of color channels. For grayscale images, we need the same shape with $C=1$.\n",
    "\n",
    "We need to reshape our data before starting training:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/5\n",
      "1875/1875 [==============================] - 15s 7ms/step - loss: 0.2099 - acc: 0.9410 - val_loss: 0.0879 - val_acc: 0.9735\n",
      "Epoch 2/5\n",
      "1875/1875 [==============================] - 13s 7ms/step - loss: 0.0858 - acc: 0.9753 - val_loss: 0.0682 - val_acc: 0.9791\n",
      "Epoch 3/5\n",
      "1875/1875 [==============================] - 13s 7ms/step - loss: 0.0665 - acc: 0.9808 - val_loss: 0.0553 - val_acc: 0.9829\n",
      "Epoch 4/5\n",
      "1875/1875 [==============================] - 15s 8ms/step - loss: 0.0582 - acc: 0.9835 - val_loss: 0.0513 - val_acc: 0.9835\n",
      "Epoch 5/5\n",
      "1875/1875 [==============================] - 14s 8ms/step - loss: 0.0527 - acc: 0.9847 - val_loss: 0.0503 - val_acc: 0.9833\n"
     ]
    }
   ],
   "source": [
    "x_train_c = np.expand_dims(x_train,3)\n",
    "x_test_c = np.expand_dims(x_test,3)\n",
    "hist = model.fit(x_train_c,y_train,validation_data=(x_test_c,y_test),epochs=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 31656 characters]",
      "text/plain": [
       "<Figure size 1080x216 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_results(hist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, we are able to achieve higher accuracy, and much faster (in terms of number of epochs), compared to the fully-connected networks from previous unit. However, the training itself requires more resources, and may be slower on non-GPU computers.\n",
    "\n",
    "## Visualizing Convolutional Layers\n",
    "\n",
    "We can also visualize the weights of our trained convolutional layers, to try and make some more sense of what is going on:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAV0AAAAtCAYAAAAN3bjCAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAGC0lEQVR4nO3dbUyVZRgH8AuQw0EkXg3xBQ4GGDKPCksTZ7ia5SQnNJg1s2WmUcyXXNOtWkvXVlvTtWplK8vWB5s6RcMXUHqhBhpWgi8TNEBEBJQ3Q+AcOOf0ofkh+V/PPK3dfej/+/h/uM5zH85zrj3buXY/AT6fT4iIyIzA/3oBRET/J2y6REQGsekSERnEpktEZBCbLhGRQaOsDuZXFsLRho7+cLWmuS4O5k5nk1oz6MHLKJv/XgDKU/dugetydYWq53Ds98LcVnpKrXHlPADzim82wnVdbYmH6/qiJ1M9R6srEuaVOzLUmu6MYZhffh6va1HFWriu9j79c1yT/C3M39pXoNYMxQ3hda3YBNflbUuB65q8p1A9R9R5+FISWXBVrblyagLML23cAF/sgwsPw3Uduz5VPUftGQfMfTZ83YmIpK6uhvkx7x64rrfPLYLr2l45Xz3HPGcdzE80Jak1a5zfw3xd2nG4rqnFb8J13eoIU88hyv8loC9ILQnuxfeIF18b+TkuTH8Vrslz4ZL6+pc3Pwhzd4JbrfG58Jour8LfRRHe6RIRGcWmS0RkEJsuEZFBbLpERAax6RIRGWQ5vVBdj3/hXJZxUq0JirsI8+aBaLXmsaizVssYoTD9R5jva5mp1izaWgvzFZ/hXERk1v7Zfq3r/FAEzHs9+lTF2TecMI8/06zW9DkS/FrXlPB2mA8MB6s1B6/PgLl9ao9aE1mMJzFkBY5nb3oR5hNvetRzeELwfUJH2US1xp7VrR5DvmrCn/v6+8rVmvPX8NTOcPtotaZx13S/1vVlHV5XVPxNtWbQgz/jvPtr1JqStmkwX5emFJzE173drp5CAp29MO/36d8Ve6M+2XCn3mkxMI9ou6HWDIXjfWi+zt6u1iw9WnTXa7qNd7pERAax6RIRGcSmS0RkEJsuEZFBbLpERAax6RIRGWQ5MmZrxeMmh2P1jT8OzdgB86Bodf8HuTfIYmMMoHcYj+H0uWxqTUZoE8y79P1IpCH/E+XIKzB9JBSPOr20a456DseRKph3P4k33xARqX56m3JkA0yvDETBvPOAPmY1KhePrAWW49cSEYnaWYkPfI7j2OONML85J1E9x/UZ+DoK0/e7kZ5O/64v9zAeTUqx4dE7EZHEsXgs7cZPY9Qae2qfX+sabMfvIzcLX0MiIhXtyTCv+S5VrXEcuoUPKB9vzDm8AZPoX3mRX/F7ufKoXpTyRL3FC/7dmN0nYO4N1ntERD0+96wQfbRynKPzrtd0G+90iYgMYtMlIjKITZeIyCA2XSIig9h0iYgMspxeiM7sgPkLSXjDGRGRVQ34cS4Nx/THg4Qo+5HUfIjzgx9lw3xBof4r7urKZ2D+UIr++I7T7fgxLzWL8d8nla6E+YTf9BGJ7mfxZEPE8ha1ZvnveTAvGY//PnF0F8zrLD79S7V4siH/OeUnbBE5EJulvyBwLRdfE2M/1j9HWyo+hxvvufKPDHvxvUhmiP7Ld2v5JJhHXdM377naom8ChaQU4Y2mqufpj4MKP42vb1cB3qBHRKQpx79pD23iYFIZ3kBGRMRe8jPMw9L0a+iXMAc+MHdk9G4Tnl5YcnSt+vqRZ/H7SK9aptZ4lWvFCu90iYgMYtMlIjKITZeIyCA2XSIig9h0iYgMYtMlIjLIcmRszDv3wHzn6CVqTciRapgHr9dHxuw9FrvOAL4cPAJVXI+fNyYiUjTzB5h/unehWrPgcfxeVB48ctKWpW/ikT33DMwb/sDPeBIRaezyb9SoqgP/713KI81ERHbnvg9zq7Gpw059IySkO3MI5val+mY/XmXvEZv+6DYJ7LW8zEfIS8LPzat1D6o1/clumGcu1jdpGbgxzq91BaVMhnnAZjzaKSIyJWIA5ttitqo1aTbtuW54QyVtYyhnwlPqOYLH41HJQHxJ/FXTpm88c6eVW16G+bgBfYytczo+9np6qVrT4ta/pxre6RIRGcSmS0RkEJsuEZFBbLpERAax6RIRGRTg8+m/5hER0b+Ld7pERAax6RIRGcSmS0RkEJsuEZFBbLpERAax6RIRGfQnZ3ZmJB6JRNQAAAAASUVORK5CYII=",
      "text/plain": [
       "<Figure size 432x288 with 9 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig,ax = plt.subplots(1,9)\n",
    "l = model.layers[0].weights[0]\n",
    "for i in range(9):\n",
    "    ax[i].imshow(l[...,0,i])\n",
    "    ax[i].axis('off')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see that some of those filters look like they can recognize some oblique strokes, while others look pretty random. \n",
    "\n",
    "> **Task**: Train the same network with 3x3 filters and visualize them. Do you see more familiar patterns?\n",
    "\n",
    "## Multi-layered CNNs and pooling layers\n",
    "\n",
    "First convolutional layers looks for primitive patterns, such as horizontal or vertical lines, but we can apply further convolutional layers on top of them to look for higher-level patterns, such as primitive shapes. Then more convolutional layers can combine those shapes into some parts of the picture, up to the final object that we are trying to classify. \n",
    "\n",
    "When doing so, we may also apply one trick: reducing the spatial size of the image. Once we have detected there is a horizontal stoke within sliding 3x3 window, it is not so important at which exact pixel it occurred. Thus we can \"scale down\" the size of the image, which is done using one of the **pooling layers**:\n",
    "\n",
    " * **Average Pooling** takes a sliding window (for example, 2x2 pixels) and computes an average of values within the window\n",
    " * **Max Pooling** replaces the window with the maximum value. The idea behind max pooling is to detect a presence of a certain pattern within the sliding window.\n",
    "\n",
    "Thus, in a typical CNN there would be several convolutional layers, with pooling layers in between them to decrease dimensions of the image. We would also increase the number of filters, because as patterns become more advanced - there are more possible interesting combinations that we need to be looking for.\n",
    "\n",
    "![An image showing several convolutional layers with pooling layers.](./images/cnn-pyramid.png)\n",
    "\n",
    "Because of decreasing spatial dimensions and increasing feature/filters dimensions, this architecture is also called **pyramid architecture**. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_1\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv2d_1 (Conv2D)            (None, 24, 24, 10)        260       \n",
      "_________________________________________________________________\n",
      "max_pooling2d (MaxPooling2D) (None, 12, 12, 10)        0         \n",
      "_________________________________________________________________\n",
      "conv2d_2 (Conv2D)            (None, 8, 8, 20)          5020      \n",
      "_________________________________________________________________\n",
      "max_pooling2d_1 (MaxPooling2 (None, 4, 4, 20)          0         \n",
      "_________________________________________________________________\n",
      "flatten_1 (Flatten)          (None, 320)               0         \n",
      "_________________________________________________________________\n",
      "dense_1 (Dense)              (None, 10)                3210      \n",
      "=================================================================\n",
      "Total params: 8,490\n",
      "Trainable params: 8,490\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = keras.models.Sequential([\n",
    "    keras.layers.Conv2D(filters=10, kernel_size=(5,5), input_shape=(28,28,1),activation='relu'),\n",
    "    keras.layers.MaxPooling2D(),\n",
    "    keras.layers.Conv2D(filters=20, kernel_size=(5,5), activation='relu'),\n",
    "    keras.layers.MaxPooling2D(),    \n",
    "    keras.layers.Flatten(),\n",
    "    keras.layers.Dense(10)\n",
    "])\n",
    "\n",
    "model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['acc'])\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that the number of trainable parameters (~8.5K) is dramatically smaller than in previous cases. This happens because convolutional layers in general have few parameters, and dimensionality of the image before applying final dense layer is significantly reduced. Small number of parameters have positive impact on our models, because it helps to prevent overfitting even on smaller dataset sizes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/5\n",
      "1875/1875 [==============================] - 6s 3ms/step - loss: 0.0723 - acc: 0.9780 - val_loss: 0.0423 - val_acc: 0.9861\n",
      "Epoch 2/5\n",
      "1875/1875 [==============================] - 6s 3ms/step - loss: 0.0523 - acc: 0.9842 - val_loss: 0.0425 - val_acc: 0.9866\n",
      "Epoch 3/5\n",
      "1875/1875 [==============================] - 6s 3ms/step - loss: 0.0448 - acc: 0.9868 - val_loss: 0.0403 - val_acc: 0.9865\n",
      "Epoch 4/5\n",
      "1875/1875 [==============================] - 6s 3ms/step - loss: 0.0383 - acc: 0.9886 - val_loss: 0.0323 - val_acc: 0.9888\n",
      "Epoch 5/5\n",
      "1875/1875 [==============================] - 6s 3ms/step - loss: 0.0338 - acc: 0.9895 - val_loss: 0.0331 - val_acc: 0.9896\n"
     ]
    }
   ],
   "source": [
    "hist = model.fit(x_train_c,y_train,validation_data=(x_test_c,y_test),epochs=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 25528 characters]",
      "text/plain": [
       "<Figure size 1080x216 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_results(hist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What you should probably observe is that we are able to achieve higher accuracy than with just one layer, and much faster in terms of number of epochs - just with 1 or 2 epochs. It means that sophisticated network architecture needs much fewer data to figure out what is going on, and to extract generic patterns from our images. However, training also takes longer, and requires a GPU.\n",
    "\n",
    "## Playing with real images from the CIFAR-10 dataset\n",
    "\n",
    "While our handwritten digit recognition problem may seem like a toy problem, we are now ready to do something more serious. Let's explore more advanced dataset of pictures of different objects, called [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html). It contains 60k 32x32 images, divided into 10 classes. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(x_train,y_train),(x_test,y_test) = keras.datasets.cifar10.load_data()\n",
    "x_train = x_train.astype(np.float32) / 255.0\n",
    "x_test = x_test.astype(np.float32) / 255.0\n",
    "classes = ('plane', 'car', 'bird', 'cat',\n",
    "           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 123916 characters]",
      "text/plain": [
       "<Figure size 1080x216 with 10 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_dataset(x_train,y_train,classes=classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A well-known architecture for CIFAR-10 is called [LeNet](https://en.wikipedia.org/wiki/LeNet), and has been proposed by *Yann LeCun*. It follows the same principles as we have outlined above, the main difference being 3 input color channels instead of 1. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_3\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv2d_8 (Conv2D)            (None, 28, 28, 6)         456       \n",
      "_________________________________________________________________\n",
      "max_pooling2d_6 (MaxPooling2 (None, 14, 14, 6)         0         \n",
      "_________________________________________________________________\n",
      "conv2d_9 (Conv2D)            (None, 10, 10, 16)        2416      \n",
      "_________________________________________________________________\n",
      "max_pooling2d_7 (MaxPooling2 (None, 5, 5, 16)          0         \n",
      "_________________________________________________________________\n",
      "flatten_3 (Flatten)          (None, 400)               0         \n",
      "_________________________________________________________________\n",
      "dense_9 (Dense)              (None, 120)               48120     \n",
      "_________________________________________________________________\n",
      "dense_10 (Dense)             (None, 84)                10164     \n",
      "_________________________________________________________________\n",
      "dense_11 (Dense)             (None, 10)                850       \n",
      "=================================================================\n",
      "Total params: 62,006\n",
      "Trainable params: 62,006\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = keras.models.Sequential([\n",
    "    keras.layers.Conv2D(filters = 6, kernel_size = 5, strides = 1, activation = 'relu', input_shape = (32,32,3)),\n",
    "    keras.layers.MaxPooling2D(pool_size = 2, strides = 2),\n",
    "    keras.layers.Conv2D(filters = 16, kernel_size = 5, strides = 1, activation = 'relu'),\n",
    "    keras.layers.MaxPooling2D(pool_size = 2, strides = 2),\n",
    "    keras.layers.Flatten(),\n",
    "    keras.layers.Dense(120, activation = 'relu'),\n",
    "    keras.layers.Dense(84, activation = 'relu'),\n",
    "    keras.layers.Dense(10, activation = 'softmax')])\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Training this network properly will take significant amount of time, and should preferably be done on GPU-enabled compute."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/10\n",
      "1563/1563 [==============================] - 6s 4ms/step - loss: 1.6205 - acc: 0.4033 - val_loss: 1.4287 - val_acc: 0.4743\n",
      "Epoch 2/10\n",
      "1563/1563 [==============================] - 6s 4ms/step - loss: 1.3435 - acc: 0.5154 - val_loss: 1.2804 - val_acc: 0.5412\n",
      "Epoch 3/10\n",
      "1563/1563 [==============================] - 5s 3ms/step - loss: 1.2225 - acc: 0.5645 - val_loss: 1.2164 - val_acc: 0.5600\n",
      "Epoch 4/10\n",
      "1563/1563 [==============================] - 5s 4ms/step - loss: 1.1360 - acc: 0.5957 - val_loss: 1.1918 - val_acc: 0.5768\n",
      "Epoch 5/10\n",
      "1563/1563 [==============================] - 5s 3ms/step - loss: 1.0776 - acc: 0.6178 - val_loss: 1.1451 - val_acc: 0.5906\n",
      "Epoch 6/10\n",
      "1563/1563 [==============================] - 5s 4ms/step - loss: 1.0228 - acc: 0.6370 - val_loss: 1.1178 - val_acc: 0.6098\n",
      "Epoch 7/10\n",
      "1563/1563 [==============================] - 5s 4ms/step - loss: 0.9769 - acc: 0.6544 - val_loss: 1.0793 - val_acc: 0.6202\n",
      "Epoch 8/10\n",
      "1563/1563 [==============================] - 5s 3ms/step - loss: 0.9340 - acc: 0.6711 - val_loss: 1.0783 - val_acc: 0.6271\n",
      "Epoch 9/10\n",
      "1563/1563 [==============================] - 5s 4ms/step - loss: 0.8983 - acc: 0.6824 - val_loss: 1.0952 - val_acc: 0.6203\n",
      "Epoch 10/10\n",
      "1563/1563 [==============================] - 6s 4ms/step - loss: 0.8648 - acc: 0.6939 - val_loss: 1.1103 - val_acc: 0.6217\n"
     ]
    }
   ],
   "source": [
    "model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['acc'])\n",
    "hist = model.fit(x_train,y_train,validation_data=(x_test,y_test),epochs=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 27416 characters]",
      "text/plain": [
       "<Figure size 1080x216 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_results(hist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The accuracy that we have been able to achieve with few epochs of training does not seem too great. However, remember that bling guessing would only give us 10% accuracy, and that our problem is actually significantly more difficult than MNIST digit classification. Getting above 50% accuracy in such a short training time seems like a good accomplishment.\n",
    "\n",
    "## Takeaways\n",
    "\n",
    "In this unit, we have learned the main concept behind computer vision neural networks - convolutional networks. Real-life architectures that power image classification, object detection, and even image generation networks are all based on CNNs, just with more layers and some additional training tricks."
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0cb620c6d4b9f7a635928804c26cf22403d89d98d79684e4529119355ee6d5a5"
  },
  "kernelspec": {
   "display_name": "Python 3.8.12 64-bit (conda)",
   "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.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
