diff --git a/13_convolutional_neural_networks.ipynb b/13_convolutional_neural_networks.ipynb index 504968b..4bb5a03 100644 --- a/13_convolutional_neural_networks.ipynb +++ b/13_convolutional_neural_networks.ipynb @@ -44,7 +44,7 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, + "collapsed": false, "deletable": true, "editable": true }, @@ -437,6 +437,166 @@ }, "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", + "graph = tf.Graph()\n", + "with graph.as_default():\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, strides=conv1_stride, padding=conv1_pad, activation=tf.nn.relu, name=\"conv1\")\n", + " conv2 = tf.layers.conv2d(conv1, filters=conv2_fmaps, kernel_size=conv2_ksize, strides=conv2_stride, padding=conv2_pad, 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": "code", + "execution_count": 16, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.examples.tutorials.mnist import input_data\n", + "mnist = input_data.read_data_sets(\"/tmp/data/\")" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "n_epochs = 10\n", + "batch_size = 100\n", + "\n", + "with tf.Session(graph=graph) 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, + "deletable": true, + "editable": true + }, + "source": [ + "# Exercise solutions" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "## 1. to 6." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "See appendix A." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": 18, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "import tensorflow as tf\n", + "\n", "height = 28\n", "width = 28\n", "channels = 1\n", @@ -499,9 +659,19 @@ " saver = tf.train.Saver()" ] }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's load the data:" + ] + }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 19, "metadata": { "collapsed": false, "deletable": true, @@ -513,9 +683,19 @@ "mnist = input_data.read_data_sets(\"/tmp/data/\")" ] }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 17, + "execution_count": 20, "metadata": { "collapsed": true, "deletable": true, @@ -536,9 +716,49 @@ " tf.get_default_session().run(assign_ops, feed_dict=feed_dict)" ] }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "We need a validation set for Early Stopping, so we take 2,000 instances from the test set for this purpose." + ] + }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 21, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "X_val = mnist.test.images[:2000]\n", + "y_val = mnist.test.labels[:2000]\n", + "X_test = mnist.test.images[2000:]\n", + "y_test = mnist.test.labels[2000:]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 22, "metadata": { "collapsed": false, "deletable": true, @@ -562,7 +782,7 @@ " X_batch, y_batch = mnist.train.next_batch(batch_size)\n", " sess.run(training_op, feed_dict={X: X_batch, y: y_batch, is_training: True})\n", " if iteration % check_interval == 0:\n", - " acc_val = accuracy.eval(feed_dict={X: mnist.test.images[:2000], y: mnist.test.labels[:2000]})\n", + " acc_val = accuracy.eval(feed_dict={X: X_val, y: y_val})\n", " if acc_val > best_acc_val:\n", " best_acc_val = acc_val\n", " checks_since_last_progress = 0\n", @@ -570,7 +790,7 @@ " else:\n", " checks_since_last_progress += 1\n", " acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})\n", - " acc_test = accuracy.eval(feed_dict={X: mnist.test.images[2000:], y: mnist.test.labels[2000:]})\n", + " acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test})\n", " print(epoch, \"Train accuracy:\", acc_train, \"Test accuracy:\", acc_test, \"Best validation accuracy:\", best_acc_val)\n", " if checks_since_last_progress > max_checks_without_progress:\n", " print(\"Early stopping!\")\n", @@ -578,11 +798,57 @@ "\n", " if best_model_params:\n", " restore_model_params(best_model_params)\n", - " acc_test = accuracy.eval(feed_dict={X: mnist.test.images[2000:], y: mnist.test.labels[2000:]})\n", + " acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test})\n", " print(\"Final accuracy on test set:\", acc_test)\n", " save_path = saver.save(sess, \"./my_mnist_model\")" ] }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true, + "deletable": true, + "editable": 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. Resize and/or crop them to 299 × 299 pixels, and ensure that they have just three channels (RGB), with no transparency channel." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "width = 299\n", + "height = 299\n", + "channels = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { @@ -590,12 +856,13 @@ "editable": true }, "source": [ - "# Inception v3" + "## 8.2.\n", + "Exercise: Download the latest pretrained Inception v3 model: the checkpoint is available at https://goo.gl/nxSQvl[].\n" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 25, "metadata": { "collapsed": true, "deletable": true, @@ -631,7 +898,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 26, "metadata": { "collapsed": false, "deletable": true, @@ -644,7 +911,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 27, "metadata": { "collapsed": true, "deletable": true, @@ -657,14 +924,14 @@ "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", + " 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": 24, + "execution_count": 28, "metadata": { "collapsed": false, "deletable": true, @@ -677,22 +944,7 @@ }, { "cell_type": "code", - "execution_count": 25, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [ - "width = 299\n", - "height = 299\n", - "channels = 3" - ] - }, - { - "cell_type": "code", - "execution_count": 26, + "execution_count": 29, "metadata": { "collapsed": false, "deletable": true, @@ -700,16 +952,23 @@ }, "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()" + "class_names[:5]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 27, + "execution_count": 30, "metadata": { "collapsed": false, "deletable": true, @@ -729,9 +988,46 @@ "saver = tf.train.Saver()" ] }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 28, + "execution_count": 31, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "with tf.Session() as sess:\n", + " saver.restore(sess, INCEPTION_V3_CHECKPOINT_PATH)\n", + " # ..." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 32, "metadata": { "collapsed": false, "deletable": true, @@ -748,7 +1044,7 @@ }, { "cell_type": "code", - "execution_count": 29, + "execution_count": 33, "metadata": { "collapsed": false, "deletable": true, @@ -756,12 +1052,13 @@ }, "outputs": [], "source": [ - "class_names[np.argmax(predictions_val[0])]" + "most_likely_class_index = np.argmax(predictions_val[0])\n", + "most_likely_class_index" ] }, { "cell_type": "code", - "execution_count": 30, + "execution_count": 34, "metadata": { "collapsed": false, "deletable": true, @@ -769,23 +1066,1099 @@ }, "outputs": [], "source": [ - "np.argmax(predictions_val, axis=1)" + "class_names[most_likely_class_index]" ] }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 35, "metadata": { "collapsed": false, "deletable": true, - "editable": true + "editable": true, + "scrolled": true }, "outputs": [], "source": [ "top_5 = np.argpartition(predictions_val[0], -5)[-5:]\n", "top_5 = 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]))" + " print(\"{0}: {1:.2f}%\".format(class_names[i], 100 * predictions_val[0][i]))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "The model is quite accurate on this particular image: if makes the right prediction with high confidence." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's tackle the flowers dataset. First, we need to download it:" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": 37, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "fetch_flowers()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 39, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's get the list of all the image file paths for each class:" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": 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": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's sort the image paths just to make this notebook behave consistently across multiple runs:" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "for paths in image_paths.values():\n", + " paths.sort() " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's take a peek at the first few images from each class:" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": 43, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": 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 = rnd.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 = rnd.randint(0, width - crop_width)\n", + " y0 = rnd.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 rnd.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, the Convolution Neural Network expects colors represented as\n", + " # 32-bit floats ranging from 0.0 to 1.0:\n", + " return image.astype(np.float32) / 255" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's check out the result on this image:" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "There we go:" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "Now let's look at a few other random images generated from the same original image:" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "Looks good!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 47, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's test this function!" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "tf.reset_default_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": { + "deletable": true, + "editable": true + }, + "source": [ + "Looks perfect!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": 49, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.contrib.slim.nets import inception\n", + "import tensorflow.contrib.slim as slim\n", + "\n", + "tf.reset_default_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": { + "deletable": true, + "editable": true + }, + "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": 50, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "logits.op.inputs[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 51, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "logits.op.inputs[0].op.inputs[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 52, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "logits.op.inputs[0].op.inputs[0].op.inputs[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 53, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "end_points" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "As you can see, the `\"PreLogits\"` end point is precisely what we need:" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "end_points[\"PreLogits\"]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "We can drop the 2nd and 3rd dimensions using the `tf.squeeze()` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "prelogits = tf.squeeze(end_points[\"PreLogits\"], axis=[1, 2])" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "Then we can add the final fully connected layer on top of this layer:" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": { + "deletable": true, + "editable": true + }, + "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": 57, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": 58, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "[v.name for v in flower_vars]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "source": [ + "First, we will want to represent the classes as ints rather than strings:" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "flower_class_ids = {flower_class: index for index, flower_class in enumerate(flower_classes)}\n", + "flower_class_ids" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 60, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": { + "deletable": true, + "editable": true + }, + "source": [ + "Next, lets shuffle the dataset and split it into the training set and the test set:" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "test_ratio = 0.2\n", + "train_size = int(len(flower_paths_and_classes) * (1 - test_ratio))\n", + "\n", + "rnd.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": { + "deletable": true, + "editable": true + }, + "source": [ + "Let's look at the first 3 instances in the training set:" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "flower_paths_and_classes_train[:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": 63, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": 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 = np.stack(prepared_images)\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": 64, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "X_batch, y_batch = prepare_batch(flower_paths_and_classes_train, batch_size=4)" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "X_batch.shape" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "X_batch.dtype" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "y_batch.shape" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "y_batch.dtype" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "source": [ + "Looking good. Now let's use this function to prepare the test set:" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": 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": null, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "X_test.shape" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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": { + "deletable": true, + "editable": true + }, + "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": null, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "n_epochs = 10\n", + "batch_size = 50\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\")\n", + "\n", + " print(\"Computing final accuracy on the test set (this will take a while)...\")\n", + " acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test})\n", + " print(\"Test accuracy:\", acc_test)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "deletable": true, + "editable": true + }, + "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" ] }, { @@ -796,17 +2169,7 @@ "editable": true }, "source": [ - "# Exercise solutions" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "**Coming soon**" + "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." ] }, {