Chapter 13 – Convolutional Neural Networks

This notebook contains all the sample code and solutions to the exercises in chapter 13.

Setup

#Setup

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:

A couple utility functions to plot grayscale and RGB images:

And of course we will need TensorFlow:

Convolutional layer

#Convolutional-layer
Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...

Simple example

#Simple-example
Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...

Using tf.layers.conv2d():

Loading output library...

VALID vs SAME padding

#VALID-vs-SAME-padding

Pooling layer

#Pooling-layer
Loading output library...
Loading output library...
Loading output library...

MNIST

#MNIST

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.

For all these functions:

  • 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).

The other main differences in tf.layers.dense() are:

  • the weights parameter was renamed to kernel (and the weights variable is now named "kernel" rather than "weights"),
  • the default activation is None instead of tf.nn.relu

The other main differences in tf.layers.conv2d() are:

  • the num_outputs parameter was renamed to filters,
  • the stride parameter was renamed to strides,
  • the default activation is now None instead of tf.nn.relu.

The other main differences in tf.layers.dropout() are:

  • it takes the dropout rate (rate) rather than the keep probability (keep_prob). Of course, rate == 1 - keep_prob,
  • the is_training parameters was renamed to training.

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):

1
$ /Applications/Python\ 3.6/Install\ Certificates.command

Exercise solutions

#Exercise-solutions

1. to 6.

#1.-to-6.

See appendix A.

7. High Accuracy CNN for MNIST

#7.-High-Accuracy-CNN-for-MNIST

Exercise: Build your own CNN and try to achieve the highest possible accuracy on MNIST.

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?

Let's load the data:

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.

Now let's train the model! This implementation of Early Stopping works like this:

  • every 100 training iterations, it evaluates the model on the validation set,
  • if the model performs better than the best model found so far, then it saves the model to RAM,
  • if there is no progress for 100 evaluations in a row, then training is interrupted,
  • after training, the code restores the best model found.

8. Classifying large images using Inception v3.

#8.-Classifying-large-images-using-Inception-v3.

8.1.

#8.1.

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.

Loading output library...

Ensure that the values are in the range -1, 1 (as expected by the pretrained Inception model), instead of 0, 1:

8.2.

#8.2.

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.

Loading output library...

8.3.

#8.3.

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 ...

8.4.

#8.4.

Exercise: Open a session and use the Saver to restore the pretrained model checkpoint you downloaded earlier.

8.5.

#8.5.

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?

Loading output library...
Loading output library...

The model is quite accurate on this particular image: if makes the right prediction with high confidence.

9. Transfer learning for large image classification.

#9.-Transfer-learning-for-large-image-classification.

9.1.

#9.1.

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 or MIT's places dataset (requires registration, and it is huge).

Let's tackle the flowers dataset. First, we need to download it:

Each subdirectory of the flower_photos directory contains all the pictures of a given class. Let's get the list of classes:

Loading output library...

Let's get the list of all the image file paths for each class:

Let's sort the image paths just to make this notebook behave consistently across multiple runs:

Let's take a peek at the first few images from each class:

Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...

Notice how the image dimensions vary, and how difficult the task is in some cases (e.g., the 2nd tulip image).

9.2.

#9.2.

Exercise: Write a preprocessing step that will resize and crop the image to 299 × 299, with some randomness for data augmentation.

First, let's implement this using NumPy and SciPy:

  • using basic NumPy slicing for image cropping,
  • NumPy's fliplr() function to flip the image horizontally (with 50% probability),
  • and SciPy's imresize() function for zooming.
    • Note that imresize() is based on the Python Image Library (PIL).

For more image manipulation functions, such as rotations, check out SciPy's documentation or this nice page.

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).

Let's check out the result on this image:

Loading output library...

There we go:

Loading output library...

Now let's look at a few other random images generated from the same original image:

Loading output library...

Looks good!

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 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.

Let's test this function!

Loading output library...

Looks perfect!

9.3.

#9.3.

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).

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).

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:

Loading output library...

Nope, that's part of the output layer (adding the biases). Let's continue walking backwards in the graph:

Loading output library...

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:

Loading output library...

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:

Loading output library...

As you can see, the "PreLogits" end point is precisely what we need:

Loading output library...

We can drop the 2nd and 3rd dimensions using the tf.squeeze() function:

Then we can add the final fully connected layer on top of this layer:

Finally, we need to add the usual bits and pieces:

  • the placeholder for the targets (y),
  • the loss function, which is the cross-entropy, as usual for a classification task,
  • an optimizer, that we use to create a training operation that will minimize the cost function,
  • a couple operations to measure the model's accuracy,
  • and finally an initializer and a saver.

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:

Loading output library...

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.

9.4.

#9.4.

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.

First, we will want to represent the classes as ints rather than strings:

Loading output library...

It will be easier to shuffle the dataset set if we represent it as a list of filepath/class pairs:

Next, lets shuffle the dataset and split it into the training set and the test set:

Let's look at the first 3 instances in the training set:

Loading output library...

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:

Loading output library...
Loading output library...
Loading output library...
Loading output library...

Looking good. Now let's use this function to prepare the test set:

Loading output library...

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.

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.

Loading output library...

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.

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.

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 goes into more details and reaches 96% accuracy.

10.

#10.

Exercise: Go through TensorFlow's DeepDream tutorial. 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.

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 you can then create a video from these images. For example, here is a DeepDream video I made... as you will see, it quickly turns into a nightmare. ;-) You can find hundreds of similar videos (often much more artistic) on the web.