{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "**Chapter 13 – Convolutional Neural Networks**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_This notebook contains all the sample code and solutions to the exercises in chapter 13._" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Setup" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# To support both python 2 and python 3\n", "from __future__ import division, print_function, unicode_literals\n", "\n", "# Common imports\n", "import numpy as np\n", "import os\n", "\n", "# to make this notebook's output stable across runs\n", "def reset_graph(seed=42):\n", " tf.reset_default_graph()\n", " tf.set_random_seed(seed)\n", " np.random.seed(seed)\n", "\n", "# To plot pretty figures\n", "%matplotlib inline\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "plt.rcParams['axes.labelsize'] = 14\n", "plt.rcParams['xtick.labelsize'] = 12\n", "plt.rcParams['ytick.labelsize'] = 12\n", "\n", "# Where to save the figures\n", "PROJECT_ROOT_DIR = \".\"\n", "CHAPTER_ID = \"cnn\"\n", "\n", "def save_fig(fig_id, tight_layout=True):\n", " path = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID, fig_id + \".png\")\n", " print(\"Saving figure\", fig_id)\n", " if tight_layout:\n", " plt.tight_layout()\n", " plt.savefig(path, format='png', dpi=300)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A couple utility functions to plot grayscale and RGB images:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def plot_image(image):\n", " plt.imshow(image, cmap=\"gray\", interpolation=\"nearest\")\n", " plt.axis(\"off\")\n", "\n", "def plot_color_image(image):\n", " plt.imshow(image.astype(np.uint8),interpolation=\"nearest\")\n", " plt.axis(\"off\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And of course we will need TensorFlow:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import tensorflow as tf" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Convolutional layer" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from sklearn.datasets import load_sample_image\n", "china = load_sample_image(\"china.jpg\")\n", "flower = load_sample_image(\"flower.jpg\")\n", "image = china[150:220, 130:250]\n", "height, width, channels = image.shape\n", "image_grayscale = image.mean(axis=2).astype(np.float32)\n", "images = image_grayscale.reshape(1, height, width, 1)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "fmap = np.zeros(shape=(7, 7, 1, 2), dtype=np.float32)\n", "fmap[:, 3, 0, 0] = 1\n", "fmap[3, :, 0, 1] = 1\n", "plot_image(fmap[:, :, 0, 0])\n", "plt.show()\n", "plot_image(fmap[:, :, 0, 1])\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "reset_graph()\n", "\n", "X = tf.placeholder(tf.float32, shape=(None, height, width, 1))\n", "feature_maps = tf.constant(fmap)\n", "convolution = tf.nn.conv2d(X, feature_maps, strides=[1,1,1,1], padding=\"SAME\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "with tf.Session() as sess:\n", " output = convolution.eval(feed_dict={X: images})" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "plot_image(images[0, :, :, 0])\n", "save_fig(\"china_original\", tight_layout=False)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "plot_image(output[0, :, :, 0])\n", "save_fig(\"china_vertical\", tight_layout=False)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "plot_image(output[0, :, :, 1])\n", "save_fig(\"china_horizontal\", tight_layout=False)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple example" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from sklearn.datasets import load_sample_images\n", "\n", "# Load sample images\n", "china = load_sample_image(\"china.jpg\")\n", "flower = load_sample_image(\"flower.jpg\")\n", "dataset = np.array([china, flower], dtype=np.float32)\n", "batch_size, height, width, channels = dataset.shape\n", "\n", "# Create 2 filters\n", "filters = np.zeros(shape=(7, 7, channels, 2), dtype=np.float32)\n", "filters[:, 3, :, 0] = 1 # vertical line\n", "filters[3, :, :, 1] = 1 # horizontal line\n", "\n", "# Create a graph with input X plus a convolutional layer applying the 2 filters\n", "X = tf.placeholder(tf.float32, shape=(None, height, width, channels))\n", "convolution = tf.nn.conv2d(X, filters, strides=[1,2,2,1], padding=\"SAME\")\n", "\n", "with tf.Session() as sess:\n", " output = sess.run(convolution, feed_dict={X: dataset})\n", "\n", "plt.imshow(output[0, :, :, 1], cmap=\"gray\") # plot 1st image's 2nd feature map\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "for image_index in (0, 1):\n", " for feature_map_index in (0, 1):\n", " plot_image(output[image_index, :, :, feature_map_index])\n", " plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using `tf.layers.conv2d()`:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "reset_graph()\n", "\n", "X = tf.placeholder(shape=(None, height, width, channels), dtype=tf.float32)\n", "conv = tf.layers.conv2d(X, filters=2, kernel_size=7, strides=[2,2],\n", " padding=\"SAME\")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true }, "outputs": [], "source": [ "init = tf.global_variables_initializer()\n", "\n", "with tf.Session() as sess:\n", " init.run()\n", " output = sess.run(conv, feed_dict={X: dataset})" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "plt.imshow(output[0, :, :, 1], cmap=\"gray\") # plot 1st image's 2nd feature map\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## VALID vs SAME padding" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "reset_graph()\n", "\n", "filter_primes = np.array([2., 3., 5., 7., 11., 13.], dtype=np.float32)\n", "x = tf.constant(np.arange(1, 13+1, dtype=np.float32).reshape([1, 1, 13, 1]))\n", "filters = tf.constant(filter_primes.reshape(1, 6, 1, 1))\n", "\n", "valid_conv = tf.nn.conv2d(x, filters, strides=[1, 1, 5, 1], padding='VALID')\n", "same_conv = tf.nn.conv2d(x, filters, strides=[1, 1, 5, 1], padding='SAME')\n", "\n", "with tf.Session() as sess:\n", " print(\"VALID:\\n\", valid_conv.eval())\n", " print(\"SAME:\\n\", same_conv.eval())" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "print(\"VALID:\")\n", "print(np.array([1,2,3,4,5,6]).T.dot(filter_primes))\n", "print(np.array([6,7,8,9,10,11]).T.dot(filter_primes))\n", "print(\"SAME:\")\n", "print(np.array([0,1,2,3,4,5]).T.dot(filter_primes))\n", "print(np.array([5,6,7,8,9,10]).T.dot(filter_primes))\n", "print(np.array([10,11,12,13,0,0]).T.dot(filter_primes))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Pooling layer" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": true }, "outputs": [], "source": [ "batch_size, height, width, channels = dataset.shape\n", "\n", "filters = np.zeros(shape=(7, 7, channels, 2), dtype=np.float32)\n", "filters[:, 3, :, 0] = 1 # vertical line\n", "filters[3, :, :, 1] = 1 # horizontal line" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "X = tf.placeholder(tf.float32, shape=(None, height, width, channels))\n", "max_pool = tf.nn.max_pool(X, ksize=[1,2,2,1], strides=[1,2,2,1],padding=\"VALID\")\n", "\n", "with tf.Session() as sess:\n", " output = sess.run(max_pool, feed_dict={X: dataset})\n", "\n", "plt.imshow(output[0].astype(np.uint8)) # plot the output for the 1st image\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "plot_color_image(dataset[0])\n", "save_fig(\"china_original\")\n", "plt.show()\n", " \n", "plot_color_image(output[0])\n", "save_fig(\"china_max_pool\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MNIST" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: instead of using the `fully_connected()`, `conv2d()` and `dropout()` functions from the `tensorflow.contrib.layers` module (as in the book), we now use the `dense()`, `conv2d()` and `dropout()` functions (respectively) from the `tf.layers` module, which did not exist when this chapter was written. This is preferable because anything in contrib may change or be deleted without notice, while `tf.layers` is part of the official API. As you will see, the code is mostly the same.\n", "\n", "For all these functions:\n", "* the `scope` parameter was renamed to `name`, and the `_fn` suffix was removed in all the parameters that had it (for example the `activation_fn` parameter was renamed to `activation`).\n", "\n", "The other main differences in `tf.layers.dense()` are:\n", "* the `weights` parameter was renamed to `kernel` (and the weights variable is now named `\"kernel\"` rather than `\"weights\"`),\n", "* the default activation is `None` instead of `tf.nn.relu`\n", "\n", "The other main differences in `tf.layers.conv2d()` are:\n", "* the `num_outputs` parameter was renamed to `filters`,\n", "* the `stride` parameter was renamed to `strides`,\n", "* the default `activation` is now `None` instead of `tf.nn.relu`.\n", "\n", "The other main differences in `tf.layers.dropout()` are:\n", "* it takes the dropout rate (`rate`) rather than the keep probability (`keep_prob`). Of course, `rate == 1 - keep_prob`,\n", "* the `is_training` parameters was renamed to `training`." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true }, "outputs": [], "source": [ "height = 28\n", "width = 28\n", "channels = 1\n", "n_inputs = height * width\n", "\n", "conv1_fmaps = 32\n", "conv1_ksize = 3\n", "conv1_stride = 1\n", "conv1_pad = \"SAME\"\n", "\n", "conv2_fmaps = 64\n", "conv2_ksize = 3\n", "conv2_stride = 2\n", "conv2_pad = \"SAME\"\n", "\n", "pool3_fmaps = conv2_fmaps\n", "\n", "n_fc1 = 64\n", "n_outputs = 10\n", "\n", "reset_graph()\n", "\n", "with tf.name_scope(\"inputs\"):\n", " X = tf.placeholder(tf.float32, shape=[None, n_inputs], name=\"X\")\n", " X_reshaped = tf.reshape(X, shape=[-1, height, width, channels])\n", " y = tf.placeholder(tf.int32, shape=[None], name=\"y\")\n", "\n", "conv1 = tf.layers.conv2d(X_reshaped, filters=conv1_fmaps, kernel_size=conv1_ksize,\n", " strides=conv1_stride, padding=conv1_pad,\n", " activation=tf.nn.relu, name=\"conv1\")\n", "conv2 = tf.layers.conv2d(conv1, filters=conv2_fmaps, kernel_size=conv2_ksize,\n", " strides=conv2_stride, padding=conv2_pad,\n", " activation=tf.nn.relu, name=\"conv2\")\n", "\n", "with tf.name_scope(\"pool3\"):\n", " pool3 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n", " pool3_flat = tf.reshape(pool3, shape=[-1, pool3_fmaps * 7 * 7])\n", "\n", "with tf.name_scope(\"fc1\"):\n", " fc1 = tf.layers.dense(pool3_flat, n_fc1, activation=tf.nn.relu, name=\"fc1\")\n", "\n", "with tf.name_scope(\"output\"):\n", " logits = tf.layers.dense(fc1, n_outputs, name=\"output\")\n", " Y_proba = tf.nn.softmax(logits, name=\"Y_proba\")\n", "\n", "with tf.name_scope(\"train\"):\n", " xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)\n", " loss = tf.reduce_mean(xentropy)\n", " optimizer = tf.train.AdamOptimizer()\n", " training_op = optimizer.minimize(loss)\n", "\n", "with tf.name_scope(\"eval\"):\n", " correct = tf.nn.in_top_k(logits, y, 1)\n", " accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n", "\n", "with tf.name_scope(\"init_and_save\"):\n", " init = tf.global_variables_initializer()\n", " saver = tf.train.Saver()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Note: if you are using Python 3.6 on OSX, you need to run the following command on terminal to install the certifi package of certificates because Python 3.6 on OSX has no certificates to validate SSL connections (see this [StackOverflow question](https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error)):\n", "\n", " $ /Applications/Python\\ 3.6/Install\\ Certificates.command" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "from tensorflow.examples.tutorials.mnist import input_data\n", "mnist = input_data.read_data_sets(\"/tmp/data/\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "n_epochs = 10\n", "batch_size = 100\n", "\n", "with tf.Session() as sess:\n", " init.run()\n", " for epoch in range(n_epochs):\n", " for iteration in range(mnist.train.num_examples // batch_size):\n", " X_batch, y_batch = mnist.train.next_batch(batch_size)\n", " sess.run(training_op, feed_dict={X: X_batch, y: y_batch})\n", " acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n", " acc_test = accuracy.eval(feed_dict={X: mnist.test.images, y: mnist.test.labels})\n", " print(epoch, \"Train accuracy:\", acc_train, \"Test accuracy:\", acc_test)\n", "\n", " save_path = saver.save(sess, \"./my_mnist_model\")" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Exercise solutions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. to 6." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See appendix A." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. High Accuracy CNN for MNIST\n", "Exercise: Build your own CNN and try to achieve the highest possible accuracy on MNIST." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following CNN is similar to the one defined above, except using stride 1 for the second convolutional layer (rather than 2), with 25% dropout after the second convolutional layer, 50% dropout after the fully connected layer, and trained using early stopping. It achieves around 99.2% accuracy on MNIST. This is not state of the art, but it is not bad. Can you do better?" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import tensorflow as tf\n", "\n", "height = 28\n", "width = 28\n", "channels = 1\n", "n_inputs = height * width\n", "\n", "conv1_fmaps = 32\n", "conv1_ksize = 3\n", "conv1_stride = 1\n", "conv1_pad = \"SAME\"\n", "\n", "conv2_fmaps = 64\n", "conv2_ksize = 3\n", "conv2_stride = 1\n", "conv2_pad = \"SAME\"\n", "conv2_dropout_rate = 0.25\n", "\n", "pool3_fmaps = conv2_fmaps\n", "\n", "n_fc1 = 128\n", "fc1_dropout_rate = 0.5\n", "\n", "n_outputs = 10\n", "\n", "reset_graph()\n", "\n", "with tf.name_scope(\"inputs\"):\n", " X = tf.placeholder(tf.float32, shape=[None, n_inputs], name=\"X\")\n", " X_reshaped = tf.reshape(X, shape=[-1, height, width, channels])\n", " y = tf.placeholder(tf.int32, shape=[None], name=\"y\")\n", " training = tf.placeholder_with_default(False, shape=[], name='training')\n", "\n", "conv1 = tf.layers.conv2d(X_reshaped, filters=conv1_fmaps, kernel_size=conv1_ksize,\n", " strides=conv1_stride, padding=conv1_pad,\n", " activation=tf.nn.relu, name=\"conv1\")\n", "conv2 = tf.layers.conv2d(conv1, filters=conv2_fmaps, kernel_size=conv2_ksize,\n", " strides=conv2_stride, padding=conv2_pad,\n", " activation=tf.nn.relu, name=\"conv2\")\n", "\n", "with tf.name_scope(\"pool3\"):\n", " pool3 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"VALID\")\n", " pool3_flat = tf.reshape(pool3, shape=[-1, pool3_fmaps * 14 * 14])\n", " pool3_flat_drop = tf.layers.dropout(pool3_flat, conv2_dropout_rate, training=training)\n", "\n", "with tf.name_scope(\"fc1\"):\n", " fc1 = tf.layers.dense(pool3_flat_drop, n_fc1, activation=tf.nn.relu, name=\"fc1\")\n", " fc1_drop = tf.layers.dropout(fc1, fc1_dropout_rate, training=training)\n", "\n", "with tf.name_scope(\"output\"):\n", " logits = tf.layers.dense(fc1, n_outputs, name=\"output\")\n", " Y_proba = tf.nn.softmax(logits, name=\"Y_proba\")\n", "\n", "with tf.name_scope(\"train\"):\n", " xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)\n", " loss = tf.reduce_mean(xentropy)\n", " optimizer = tf.train.AdamOptimizer()\n", " training_op = optimizer.minimize(loss)\n", "\n", "with tf.name_scope(\"eval\"):\n", " correct = tf.nn.in_top_k(logits, y, 1)\n", " accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n", "\n", "with tf.name_scope(\"init_and_save\"):\n", " init = tf.global_variables_initializer()\n", " saver = tf.train.Saver()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's load the data:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "from tensorflow.examples.tutorials.mnist import input_data\n", "mnist = input_data.read_data_sets(\"/tmp/data/\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `get_model_params()` function gets the model's state (i.e., the value of all the variables), and the `restore_model_params()` restores a previous state. This is used to speed up early stopping: instead of storing the best model found so far to disk, we just save it to memory. At the end of training, we roll back to the best model found." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def get_model_params():\n", " gvars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n", " return {gvar.op.name: value for gvar, value in zip(gvars, tf.get_default_session().run(gvars))}\n", "\n", "def restore_model_params(model_params):\n", " gvar_names = list(model_params.keys())\n", " assign_ops = {gvar_name: tf.get_default_graph().get_operation_by_name(gvar_name + \"/Assign\")\n", " for gvar_name in gvar_names}\n", " init_values = {gvar_name: assign_op.inputs[1] for gvar_name, assign_op in assign_ops.items()}\n", " feed_dict = {init_values[gvar_name]: model_params[gvar_name] for gvar_name in gvar_names}\n", " tf.get_default_session().run(assign_ops, feed_dict=feed_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's train the model! This implementation of Early Stopping works like this:\n", "* every 100 training iterations, it evaluates the model on the validation set,\n", "* if the model performs better than the best model found so far, then it saves the model to RAM,\n", "* if there is no progress for 100 evaluations in a row, then training is interrupted,\n", "* after training, the code restores the best model found." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "n_epochs = 1000\n", "batch_size = 50\n", "\n", "best_loss_val = np.infty\n", "check_interval = 500\n", "checks_since_last_progress = 0\n", "max_checks_without_progress = 20\n", "best_model_params = None \n", "\n", "with tf.Session() as sess:\n", " init.run()\n", " for epoch in range(n_epochs):\n", " for iteration in range(mnist.train.num_examples // batch_size):\n", " X_batch, y_batch = mnist.train.next_batch(batch_size)\n", " sess.run(training_op, feed_dict={X: X_batch, y: y_batch, training: True})\n", " if iteration % check_interval == 0:\n", " loss_val = loss.eval(feed_dict={X: mnist.validation.images,\n", " y: mnist.validation.labels})\n", " if loss_val < best_loss_val:\n", " best_loss_val = loss_val\n", " checks_since_last_progress = 0\n", " best_model_params = get_model_params()\n", " else:\n", " checks_since_last_progress += 1\n", " acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n", " acc_val = accuracy.eval(feed_dict={X: mnist.validation.images,\n", " y: mnist.validation.labels})\n", " print(\"Epoch {}, train accuracy: {:.4f}%, valid. accuracy: {:.4f}%, valid. best loss: {:.6f}\".format(\n", " epoch, acc_train * 100, acc_val * 100, best_loss_val))\n", " if checks_since_last_progress > max_checks_without_progress:\n", " print(\"Early stopping!\")\n", " break\n", "\n", " if best_model_params:\n", " restore_model_params(best_model_params)\n", " acc_test = accuracy.eval(feed_dict={X: mnist.test.images,\n", " y: mnist.test.labels})\n", " print(\"Final accuracy on test set:\", acc_test)\n", " save_path = saver.save(sess, \"./my_mnist_model\")" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## 8. Classifying large images using Inception v3.\n", "\n", "### 8.1.\n", "Exercise: Download some images of various animals. Load them in Python, for example using the `matplotlib.image.mpimg.imread()` function or the `scipy.misc.imread()` function. Resize and/or crop them to 299 × 299 pixels, and ensure that they have just three channels (RGB), with no transparency channel. The images that the Inception model was trained on were preprocessed so that their values range from -1.0 to 1.0, so you must ensure that your images do too." ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": true }, "outputs": [], "source": [ "width = 299\n", "height = 299\n", "channels = 3" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "import matplotlib.image as mpimg\n", "test_image = mpimg.imread(os.path.join(\"images\",\"cnn\",\"test_image.png\"))[:, :, :channels]\n", "plt.imshow(test_image)\n", "plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ensure that the values are in the range [-1, 1] (as expected by the pretrained Inception model), instead of [0, 1]:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": true }, "outputs": [], "source": [ "test_image = 2 * test_image - 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8.2.\n", "Exercise: Download the latest pretrained Inception v3 model: the checkpoint is available at https://github.com/tensorflow/models/tree/master/research/slim. The list of class names is available at https://goo.gl/brXRtZ, but you must insert a \"background\" class at the beginning.\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sys\n", "import tarfile\n", "from six.moves import urllib\n", "\n", "TF_MODELS_URL = \"http://download.tensorflow.org/models\"\n", "INCEPTION_V3_URL = TF_MODELS_URL + \"/inception_v3_2016_08_28.tar.gz\"\n", "INCEPTION_PATH = os.path.join(\"datasets\", \"inception\")\n", "INCEPTION_V3_CHECKPOINT_PATH = os.path.join(INCEPTION_PATH, \"inception_v3.ckpt\")\n", "\n", "def download_progress(count, block_size, total_size):\n", " percent = count * block_size * 100 // total_size\n", " sys.stdout.write(\"\\rDownloading: {}%\".format(percent))\n", " sys.stdout.flush()\n", "\n", "def fetch_pretrained_inception_v3(url=INCEPTION_V3_URL, path=INCEPTION_PATH):\n", " if os.path.exists(INCEPTION_V3_CHECKPOINT_PATH):\n", " return\n", " os.makedirs(path, exist_ok=True)\n", " tgz_path = os.path.join(path, \"inception_v3.tgz\")\n", " urllib.request.urlretrieve(url, tgz_path, reporthook=download_progress)\n", " inception_tgz = tarfile.open(tgz_path)\n", " inception_tgz.extractall(path=path)\n", " inception_tgz.close()\n", " os.remove(tgz_path)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": true }, "outputs": [], "source": [ "fetch_pretrained_inception_v3()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import re\n", "\n", "CLASS_NAME_REGEX = re.compile(r\"^n\\d+\\s+(.*)\\s*$\", re.M | re.U)\n", "\n", "def load_class_names():\n", " with open(os.path.join(\"datasets\", \"inception\", \"imagenet_class_names.txt\"), \"rb\") as f:\n", " content = f.read().decode(\"utf-8\")\n", " return CLASS_NAME_REGEX.findall(content)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class_names = [\"background\"] + load_class_names()" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "class_names[:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8.3.\n", "Exercise: Create the Inception v3 model by calling the `inception_v3()` function, as shown below. This must be done within an argument scope created by the `inception_v3_arg_scope()` function. Also, you must set `is_training=False` and `num_classes=1001` [...]" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from tensorflow.contrib.slim.nets import inception\n", "import tensorflow.contrib.slim as slim\n", "\n", "reset_graph()\n", "\n", "X = tf.placeholder(tf.float32, shape=[None, 299, 299, 3], name=\"X\")\n", "with slim.arg_scope(inception.inception_v3_arg_scope()):\n", " logits, end_points = inception.inception_v3(\n", " X, num_classes=1001, is_training=False)\n", "predictions = end_points[\"Predictions\"]\n", "saver = tf.train.Saver()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8.4.\n", "Exercise: Open a session and use the `Saver` to restore the pretrained model checkpoint you downloaded earlier.\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "with tf.Session() as sess:\n", " saver.restore(sess, INCEPTION_V3_CHECKPOINT_PATH)\n", " # ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8.5.\n", "Run the model to classify the images you prepared. Display the top five predictions for each image, along with the estimated probability (the list of class names is available at https://goo.gl/brXRtZ). How accurate is the model?\n" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "X_test = test_image.reshape(-1, height, width, channels)\n", "\n", "with tf.Session() as sess:\n", " saver.restore(sess, INCEPTION_V3_CHECKPOINT_PATH)\n", " predictions_val = predictions.eval(feed_dict={X: X_test})" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "most_likely_class_index = np.argmax(predictions_val[0])\n", "most_likely_class_index" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "class_names[most_likely_class_index]" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "scrolled": true }, "outputs": [], "source": [ "top_5 = np.argpartition(predictions_val[0], -5)[-5:]\n", "top_5 = reversed(top_5[np.argsort(predictions_val[0][top_5])])\n", "for i in top_5:\n", " print(\"{0}: {1:.2f}%\".format(class_names[i], 100 * predictions_val[0][i]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The model is quite accurate on this particular image: if makes the right prediction with high confidence." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. Transfer learning for large image classification.\n", "\n", "### 9.1.\n", "Exercise: Create a training set containing at least 100 images per class. For example, you could classify your own pictures based on the location (beach, mountain, city, etc.), or alternatively you can just use an existing dataset, such as the [flowers dataset](https://goo.gl/EgJVXZ) or MIT's [places dataset](http://places.csail.mit.edu/) (requires registration, and it is huge).\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's tackle the flowers dataset. First, we need to download it:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sys\n", "import tarfile\n", "from six.moves import urllib\n", "\n", "FLOWERS_URL = \"http://download.tensorflow.org/example_images/flower_photos.tgz\"\n", "FLOWERS_PATH = os.path.join(\"datasets\", \"flowers\")\n", "\n", "def fetch_flowers(url=FLOWERS_URL, path=FLOWERS_PATH):\n", " if os.path.exists(FLOWERS_PATH):\n", " return\n", " os.makedirs(path, exist_ok=True)\n", " tgz_path = os.path.join(path, \"flower_photos.tgz\")\n", " urllib.request.urlretrieve(url, tgz_path, reporthook=download_progress)\n", " flowers_tgz = tarfile.open(tgz_path)\n", " flowers_tgz.extractall(path=path)\n", " flowers_tgz.close()\n", " os.remove(tgz_path)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": true }, "outputs": [], "source": [ "fetch_flowers()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each subdirectory of the `flower_photos` directory contains all the pictures of a given class. Let's get the list of classes:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "flowers_root_path = os.path.join(FLOWERS_PATH, \"flower_photos\")\n", "flower_classes = sorted([dirname for dirname in os.listdir(flowers_root_path)\n", " if os.path.isdir(os.path.join(flowers_root_path, dirname))])\n", "flower_classes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's get the list of all the image file paths for each class:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from collections import defaultdict\n", "\n", "image_paths = defaultdict(list)\n", "\n", "for flower_class in flower_classes:\n", " image_dir = os.path.join(flowers_root_path, flower_class)\n", " for filepath in os.listdir(image_dir):\n", " if filepath.endswith(\".jpg\"):\n", " image_paths[flower_class].append(os.path.join(image_dir, filepath))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's sort the image paths just to make this notebook behave consistently across multiple runs:" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": true }, "outputs": [], "source": [ "for paths in image_paths.values():\n", " paths.sort() " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's take a peek at the first few images from each class:" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "import matplotlib.image as mpimg\n", "\n", "n_examples_per_class = 2\n", "\n", "for flower_class in flower_classes:\n", " print(\"Class:\", flower_class)\n", " plt.figure(figsize=(10,5))\n", " for index, example_image_path in enumerate(image_paths[flower_class][:n_examples_per_class]):\n", " example_image = mpimg.imread(example_image_path)[:, :, :channels]\n", " plt.subplot(100 + n_examples_per_class * 10 + index + 1)\n", " plt.title(\"{}x{}\".format(example_image.shape[1], example_image.shape[0]))\n", " plt.imshow(example_image)\n", " plt.axis(\"off\")\n", " plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how the image dimensions vary, and how difficult the task is in some cases (e.g., the 2nd tulip image)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9.2.\n", "Exercise: Write a preprocessing step that will resize and crop the image to 299 × 299, with some randomness for data augmentation.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First, let's implement this using NumPy and SciPy:\n", "\n", "* using basic NumPy slicing for image cropping,\n", "* NumPy's `fliplr()` function to flip the image horizontally (with 50% probability),\n", "* and SciPy's `imresize()` function for zooming.\n", " * Note that `imresize()` is based on the Python Image Library (PIL).\n", "\n", "For more image manipulation functions, such as rotations, check out [SciPy's documentation](https://docs.scipy.org/doc/scipy-0.19.0/reference/ndimage.html) or [this nice page](http://www.scipy-lectures.org/advanced/image_processing/)." ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from scipy.misc import imresize\n", "\n", "def prepare_image(image, target_width = 299, target_height = 299, max_zoom = 0.2):\n", " \"\"\"Zooms and crops the image randomly for data augmentation.\"\"\"\n", "\n", " # First, let's find the largest bounding box with the target size ratio that fits within the image\n", " height = image.shape[0]\n", " width = image.shape[1]\n", " image_ratio = width / height\n", " target_image_ratio = target_width / target_height\n", " crop_vertically = image_ratio < target_image_ratio\n", " crop_width = width if crop_vertically else int(height * target_image_ratio)\n", " crop_height = int(width / target_image_ratio) if crop_vertically else height\n", " \n", " # Now let's shrink this bounding box by a random factor (dividing the dimensions by a random number\n", " # between 1.0 and 1.0 + `max_zoom`.\n", " resize_factor = np.random.rand() * max_zoom + 1.0\n", " crop_width = int(crop_width / resize_factor)\n", " crop_height = int(crop_height / resize_factor)\n", " \n", " # Next, we can select a random location on the image for this bounding box.\n", " x0 = np.random.randint(0, width - crop_width)\n", " y0 = np.random.randint(0, height - crop_height)\n", " x1 = x0 + crop_width\n", " y1 = y0 + crop_height\n", " \n", " # Let's crop the image using the random bounding box we built.\n", " image = image[y0:y1, x0:x1]\n", "\n", " # Let's also flip the image horizontally with 50% probability:\n", " if np.random.rand() < 0.5:\n", " image = np.fliplr(image)\n", "\n", " # Now, let's resize the image to the target dimensions.\n", " image = imresize(image, (target_width, target_height))\n", " \n", " # Finally, let's ensure that the colors are represented as\n", " # 32-bit floats ranging from 0.0 to 1.0 (for now):\n", " return image.astype(np.float32) / 255" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: at test time, the preprocessing step should be as light as possible, just the bare minimum necessary to be able to feed the image to the neural network. You may want to tweak the above function to add a `training` parameter: if `False`, preprocessing should be limited to the bare minimum (i.e., no flipping the image, and just the minimum cropping required, preserving the center of the image)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's check out the result on this image:" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(6, 8))\n", "plt.imshow(example_image)\n", "plt.title(\"{}x{}\".format(example_image.shape[1], example_image.shape[0]))\n", "plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There we go:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "prepared_image = prepare_image(example_image)\n", "\n", "plt.figure(figsize=(8, 8))\n", "plt.imshow(prepared_image)\n", "plt.title(\"{}x{}\".format(prepared_image.shape[1], prepared_image.shape[0]))\n", "plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's look at a few other random images generated from the same original image:" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "rows, cols = 2, 3\n", "\n", "plt.figure(figsize=(14, 8))\n", "for row in range(rows):\n", " for col in range(cols):\n", " prepared_image = prepare_image(example_image)\n", " plt.subplot(rows, cols, row * cols + col + 1)\n", " plt.title(\"{}x{}\".format(prepared_image.shape[1], prepared_image.shape[0]))\n", " plt.imshow(prepared_image)\n", " plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Looks good!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, it's also possible to implement this image preprocessing step directly with TensorFlow, using the functions in the `tf.image` module (see [the API](https://www.tensorflow.org/api_docs/python/) for the full list). As you can see, this function looks very much like the one above, except it does not actually perform the image transformation, but rather creates a set of TensorFlow operations that *will* perform the transformation when you run the graph." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def prepare_image_with_tensorflow(image, target_width = 299, target_height = 299, max_zoom = 0.2):\n", " \"\"\"Zooms and crops the image randomly for data augmentation.\"\"\"\n", "\n", " # First, let's find the largest bounding box with the target size ratio that fits within the image\n", " image_shape = tf.cast(tf.shape(image), tf.float32)\n", " height = image_shape[0]\n", " width = image_shape[1]\n", " image_ratio = width / height\n", " target_image_ratio = target_width / target_height\n", " crop_vertically = image_ratio < target_image_ratio\n", " crop_width = tf.cond(crop_vertically,\n", " lambda: width,\n", " lambda: height * target_image_ratio)\n", " crop_height = tf.cond(crop_vertically,\n", " lambda: width / target_image_ratio,\n", " lambda: height)\n", "\n", " # Now let's shrink this bounding box by a random factor (dividing the dimensions by a random number\n", " # between 1.0 and 1.0 + `max_zoom`.\n", " resize_factor = tf.random_uniform(shape=[], minval=1.0, maxval=1.0 + max_zoom)\n", " crop_width = tf.cast(crop_width / resize_factor, tf.int32)\n", " crop_height = tf.cast(crop_height / resize_factor, tf.int32)\n", " box_size = tf.stack([crop_height, crop_width, 3]) # 3 = number of channels\n", "\n", " # Let's crop the image using a random bounding box of the size we computed\n", " image = tf.random_crop(image, box_size)\n", "\n", " # Let's also flip the image horizontally with 50% probability:\n", " image = tf.image.random_flip_left_right(image)\n", "\n", " # The resize_bilinear function requires a 4D tensor (a batch of images)\n", " # so we need to expand the number of dimensions first:\n", " image_batch = tf.expand_dims(image, 0)\n", "\n", " # Finally, let's resize the image to the target dimensions. Note that this function\n", " # returns a float32 tensor.\n", " image_batch = tf.image.resize_bilinear(image_batch, [target_height, target_width])\n", " image = image_batch[0] / 255 # back to a single image, and scale the colors from 0.0 to 1.0\n", " return image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's test this function!" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "reset_graph()\n", "\n", "input_image = tf.placeholder(tf.uint8, shape=[None, None, 3])\n", "prepared_image_op = prepare_image_with_tensorflow(input_image)\n", "\n", "with tf.Session():\n", " prepared_image = prepared_image_op.eval(feed_dict={input_image: example_image})\n", " \n", "plt.figure(figsize=(6, 6))\n", "plt.imshow(prepared_image)\n", "plt.title(\"{}x{}\".format(prepared_image.shape[1], prepared_image.shape[0]))\n", "plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Looks perfect!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9.3.\n", "Exercise: Using the pretrained Inception v3 model from the previous exercise, freeze all layers up to the bottleneck layer (i.e., the last layer before the output layer), and replace the output layer with the appropriate number of outputs for your new classification task (e.g., the flowers dataset has five mutually exclusive classes so the output layer must have five neurons and use the softmax activation function).\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's start by fetching the inception v3 graph again. This time, let's use a `training` placeholder that we will use to tell TensorFlow whether we are training the network or not (this is needed by operations such as dropout and batch normalization)." ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from tensorflow.contrib.slim.nets import inception\n", "import tensorflow.contrib.slim as slim\n", "\n", "reset_graph()\n", "\n", "X = tf.placeholder(tf.float32, shape=[None, height, width, channels], name=\"X\")\n", "training = tf.placeholder_with_default(False, shape=[])\n", "with slim.arg_scope(inception.inception_v3_arg_scope()):\n", " logits, end_points = inception.inception_v3(X, num_classes=1001, is_training=training)\n", "\n", "inception_saver = tf.train.Saver()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we need to find the point in the graph where we should attach the new output layer. It should be the layer right before the current output layer. One way to do this is to explore the output layer's inputs: " ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "logits.op.inputs[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nope, that's part of the output layer (adding the biases). Let's continue walking backwards in the graph:" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "logits.op.inputs[0].op.inputs[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's also part of the output layer, it's the final layer in the inception layer (if you are not sure you can visualize the graph using TensorBoard). Once again, let's continue walking backwards in the graph:" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "logits.op.inputs[0].op.inputs[0].op.inputs[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Aha! There we are, this is the output of the dropout layer. This is the very last layer before the output layer in the Inception v3 network, so that's the layer we need to build upon. Note that there was actually a simpler way to find this layer: the `inception_v3()` function returns a dict of end points: " ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "end_points" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, the `\"PreLogits\"` end point is precisely what we need:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "end_points[\"PreLogits\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can drop the 2nd and 3rd dimensions using the `tf.squeeze()` function:" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": true }, "outputs": [], "source": [ "prelogits = tf.squeeze(end_points[\"PreLogits\"], axis=[1, 2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then we can add the final fully connected layer on top of this layer:" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": true }, "outputs": [], "source": [ "n_outputs = len(flower_classes)\n", "\n", "with tf.name_scope(\"new_output_layer\"):\n", " flower_logits = tf.layers.dense(prelogits, n_outputs, name=\"flower_logits\")\n", " Y_proba = tf.nn.softmax(flower_logits, name=\"Y_proba\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we need to add the usual bits and pieces:\n", "\n", "* the placeholder for the targets (`y`),\n", "* the loss function, which is the cross-entropy, as usual for a classification task,\n", "* an optimizer, that we use to create a training operation that will minimize the cost function,\n", "* a couple operations to measure the model's accuracy,\n", "* and finally an initializer and a saver.\n", "\n", "There is one important detail, however: since we want to train only the output layer (all other layers must be frozen), we must pass the list of variables to train to the optimizer's `minimize()` method:" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": true }, "outputs": [], "source": [ "y = tf.placeholder(tf.int32, shape=[None])\n", "\n", "with tf.name_scope(\"train\"):\n", " xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=flower_logits, labels=y)\n", " loss = tf.reduce_mean(xentropy)\n", " optimizer = tf.train.AdamOptimizer()\n", " flower_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"flower_logits\")\n", " training_op = optimizer.minimize(loss, var_list=flower_vars)\n", "\n", "with tf.name_scope(\"eval\"):\n", " correct = tf.nn.in_top_k(flower_logits, y, 1)\n", " accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n", "\n", "with tf.name_scope(\"init_and_save\"):\n", " init = tf.global_variables_initializer()\n", " saver = tf.train.Saver() " ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "[v.name for v in flower_vars]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that we created the `inception_saver` before adding the new output layer: we will use this saver to restore the pretrained model state, so we don't want it to try to restore new variables (it would just fail saying it does not know the new variables). The second `saver` will be used to save the final flower model, including both the pretrained variables and the new ones." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9.4.\n", "Exercise: Split your dataset into a training set and a test set. Train the model on the training set and evaluate it on the test set.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First, we will want to represent the classes as ints rather than strings:" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "flower_class_ids = {flower_class: index for index, flower_class in enumerate(flower_classes)}\n", "flower_class_ids" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It will be easier to shuffle the dataset set if we represent it as a list of filepath/class pairs:" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": true }, "outputs": [], "source": [ "flower_paths_and_classes = []\n", "for flower_class, paths in image_paths.items():\n", " for path in paths:\n", " flower_paths_and_classes.append((path, flower_class_ids[flower_class]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, lets shuffle the dataset and split it into the training set and the test set:" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": true }, "outputs": [], "source": [ "test_ratio = 0.2\n", "train_size = int(len(flower_paths_and_classes) * (1 - test_ratio))\n", "\n", "np.random.shuffle(flower_paths_and_classes)\n", "\n", "flower_paths_and_classes_train = flower_paths_and_classes[:train_size]\n", "flower_paths_and_classes_test = flower_paths_and_classes[train_size:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at the first 3 instances in the training set:" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "flower_paths_and_classes_train[:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we will also need a function to preprocess a set of images. This function will be useful to preprocess the test set, and also to create batches during training. For simplicity, we will use the NumPy/SciPy implementation:" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from random import sample\n", "\n", "def prepare_batch(flower_paths_and_classes, batch_size):\n", " batch_paths_and_classes = sample(flower_paths_and_classes, batch_size)\n", " images = [mpimg.imread(path)[:, :, :channels] for path, labels in batch_paths_and_classes]\n", " prepared_images = [prepare_image(image) for image in images]\n", " X_batch = 2 * np.stack(prepared_images) - 1 # Inception expects colors ranging from -1 to 1\n", " y_batch = np.array([labels for path, labels in batch_paths_and_classes], dtype=np.int32)\n", " return X_batch, y_batch" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": true }, "outputs": [], "source": [ "X_batch, y_batch = prepare_batch(flower_paths_and_classes_train, batch_size=4)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [], "source": [ "X_batch.shape" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "X_batch.dtype" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "y_batch.shape" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "y_batch.dtype" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Looking good. Now let's use this function to prepare the test set:" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": true }, "outputs": [], "source": [ "X_test, y_test = prepare_batch(flower_paths_and_classes_test, batch_size=len(flower_paths_and_classes_test))" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [], "source": [ "X_test.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could prepare the training set in much the same way, but it would only generate one variant for each image. Instead, it's preferable to generate the training batches on the fly during training, so that we can really benefit from data augmentation, with many variants of each image." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now, we are ready to train the network (or more precisely, the output layer we just added, since all the other layers are frozen). Be aware that this may take a (very) long time." ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "collapsed": true }, "outputs": [], "source": [ "X_test, y_test = prepare_batch(flower_paths_and_classes_test, batch_size=len(flower_paths_and_classes_test))" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [], "source": [ "X_test.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could prepare the training set in much the same way, but it would only generate one variant for each image. Instead, it's preferable to generate the training batches on the fly during training, so that we can really benefit from data augmentation, with many variants of each image." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now, we are ready to train the network (or more precisely, the output layer we just added, since all the other layers are frozen). Be aware that this may take a (very) long time." ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [], "source": [ "n_epochs = 10\n", "batch_size = 40\n", "n_iterations_per_epoch = len(flower_paths_and_classes_train) // batch_size\n", "\n", "with tf.Session() as sess:\n", " init.run()\n", " inception_saver.restore(sess, INCEPTION_V3_CHECKPOINT_PATH)\n", "\n", " for epoch in range(n_epochs):\n", " print(\"Epoch\", epoch, end=\"\")\n", " for iteration in range(n_iterations_per_epoch):\n", " print(\".\", end=\"\")\n", " X_batch, y_batch = prepare_batch(flower_paths_and_classes_train, batch_size)\n", " sess.run(training_op, feed_dict={X: X_batch, y: y_batch, training: True})\n", "\n", " acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n", " print(\" Train accuracy:\", acc_train)\n", "\n", " save_path = saver.save(sess, \"./my_flowers_model\")" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [], "source": [ "n_test_batches = 10\n", "X_test_batches = np.array_split(X_test, n_test_batches)\n", "y_test_batches = np.array_split(y_test, n_test_batches)\n", "\n", "with tf.Session() as sess:\n", " saver.restore(sess, \"./my_flowers_model\")\n", "\n", " print(\"Computing final accuracy on the test set (this will take a while)...\")\n", " acc_test = np.mean([\n", " accuracy.eval(feed_dict={X: X_test_batch, y: y_test_batch})\n", " for X_test_batch, y_test_batch in zip(X_test_batches, y_test_batches)])\n", " print(\"Test accuracy:\", acc_test)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Okay, 70.58% accuracy is not great (in fact, it's really bad), but this is only after 10 epochs, and freezing all layers except for the output layer. If you have a GPU, you can try again and let training run for much longer (e.g., using early stopping to decide when to stop). You can also improve the image preprocessing function to make more tweaks to the image (e.g., changing the brightness and hue, rotate the image slightly). You can reach above 95% accuracy on this task. If you want to dig deeper, this [great blog post](https://kwotsin.github.io/tech/2017/02/11/transfer-learning.html) goes into more details and reaches 96% accuracy." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10.\n", "Exercise: Go through TensorFlow's [DeepDream tutorial](https://goo.gl/4b2s6g). It is a fun way to familiarize yourself with various ways of visualizing the patterns learned by a CNN, and to generate art using Deep Learning.\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Simply download the notebook and follow its instructions. For extra fun, you can produce a series of images, by repeatedly zooming in and running the DeepDream algorithm: using a tool such as [ffmpeg](https://ffmpeg.org/) you can then create a video from these images. For example, here is a [DeepDream video](https://www.youtube.com/watch?v=l6i_fDg30p0) I made... as you will see, it quickly turns into a nightmare. ;-) You can find hundreds of [similar videos](https://www.youtube.com/results?search_query=+deepdream) (often much more artistic) on the web." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "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.6.2" }, "nav_menu": {}, "toc": { "navigate_menu": true, "number_sections": true, "sideBar": true, "threshold": 6, "toc_cell": false, "toc_section_display": "block", "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }