In the previous lessons you saw how to do fashion recognition using a Deep Neural Network (DNN) containing three layers — the input layer (in the shape of the data), the output layer (in the shape of the desired output) and a hidden layer. You experimented with the impact of different sized of hidden layer, number of training epochs etc on the final accuracy.
For convenience, here’s the entire code again. Run it and take a note of the test accuracy that is printed out at the end.
import tensorflow as tf
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [==============================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz 8192/5148 [===============================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz 4423680/4422102 [==============================] - 0s 0us/step WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. Epoch 1/5 60000/60000 [==============================] - 8s 131us/sample - loss: 0.5016 - acc: 0.8235 Epoch 2/5 60000/60000 [==============================] - 7s 119us/sample - loss: 0.3723 - acc: 0.8658 Epoch 3/5 60000/60000 [==============================] - 7s 116us/sample - loss: 0.3366 - acc: 0.8770 Epoch 4/5 60000/60000 [==============================] - 7s 115us/sample - loss: 0.3108 - acc: 0.8873 Epoch 5/5 60000/60000 [==============================] - 7s 113us/sample - loss: 0.2961 - acc: 0.8911 10000/10000 [==============================] - 0s 43us/sample - loss: 0.3413 - acc: 0.8808
Your accuracy is probably about 89% on training and 87% on validation…not bad…But how do you make that even better? One way is to use something called Convolutions. I’m not going to details on Convolutions here, but the ultimate concept is that they narrow down the content of the image to focus on specific, distinct, details.
If you’ve ever done image processing using a filter (like this: https://en.wikipedia.org/wiki/Kernel_(image_processing)) then convolutions will look very familiar.
In short, you take an array (usually 3x3 or 5x5) and pass it over the image. By changing the underlying pixels based on the formula within that matrix, you can do things like edge detection. So, for example, if you look at the above link, you’ll see a 3x3 that is defined for edge detection where the middle cell is 8, and all of its neighbors are -1. In this case, for each pixel, you would multiply its value by 8, then subtract the value of each neighbor. Do this for every pixel, and you’ll end up with a new image that has the edges enhanced.
This is perfect for computer vision, because often it’s features that can get highlighted like this that distinguish one item for another, and the amount of information needed is then much less…because you’ll just train on the highlighted features.
That’s the concept of Convolutional Neural Networks. Add some layers to do convolution before you have the dense layers, and then the information going to the dense layers is more focussed, and possibly more accurate.
Run the below code — this is the same neural network as earlier, but this time with Convolutional layers added first. It will take longer, but look at the impact on the accuracy:
import tensorflow as tf
1.13.1 _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 26, 26, 64) 640 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 13, 13, 64) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 11, 11, 64) 36928 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 1600) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 204928 _________________________________________________________________ dense_3 (Dense) (None, 10) 1290 ================================================================= Total params: 243,786 Trainable params: 243,786 Non-trainable params: 0 _________________________________________________________________ Epoch 1/5 60000/60000 [==============================] - 106s 2ms/sample - loss: 0.4447 - acc: 0.8383 Epoch 2/5 60000/60000 [==============================] - 104s 2ms/sample - loss: 0.3024 - acc: 0.8891 Epoch 3/5 60000/60000 [==============================] - 105s 2ms/sample - loss: 0.2557 - acc: 0.9052 Epoch 4/5 60000/60000 [==============================] - 103s 2ms/sample - loss: 0.2237 - acc: 0.9165 Epoch 5/5 60000/60000 [==============================] - 103s 2ms/sample - loss: 0.1969 - acc: 0.9260 10000/10000 [==============================] - 5s 509us/sample - loss: 0.2639 - acc: 0.9047
It’s likely gone up to about 93% on the training data and 91% on the validation data.
That’s significant, and a step in the right direction!
Try running it for more epochs — say about 20, and explore the results! But while the results might seem really good, the validation results may actually go down, due to something called ‘overfitting’ which will be discussed later.
(In a nutshell, ‘overfitting’ occurs when the network learns the data from the training set really well, but it’s too specialised to only that data, and as a result is less effective at seeing other data. For example, if all your life you only saw red shoes, then when you see a red shoe you would be very good at identifying it, but blue suade shoes might confuse you…and you know you should never mess with my blue suede shoes.)
Then, look at the code again, and see, step by step how the Convolutions were built:
Step 1 is to gather the data. You’ll notice that there’s a bit of a change here in that the training data needed to be reshaped. That’s because the first convolution expects a single tensor containing everything, so instead of 60,000 28x28x1 items in a list, we have a single 4D list that is 60,000x28x28x1, and the same for the test images. If you don’t do this, you’ll get an error when training as the Convolutions do not recognize the shape.
import tensorflow as tf
Next is to define your model. Now instead of the input layer at the top, you’re going to add a Convolution. The parameters are:
- The number of convolutions you want to generate. Purely arbitrary, but good to start with something in the order of 32
- The size of the Convolution, in this case a 3x3 grid
- The activation function to use — in this case we’ll use relu, which you might recall is the equivalent of returning x when x>0, else returning 0
- In the first layer, the shape of the input data.
You’ll follow the Convolution with a MaxPooling layer which is then designed to compress the image, while maintaining the content of the features that were highlighted by the convlution. By specifying (2,2) for the MaxPooling, the effect is to quarter the size of the image. Without going into too much detail here, the idea is that it creates a 2x2 array of pixels, and picks the biggest one, thus turning 4 pixels into 1. It repeats this across the image, and in so doing halves the number of horizontal, and halves the number of vertical pixels, effectively reducing the image by 25%.
You can call model.summary() to see the size and shape of the network, and you’ll notice that after every MaxPooling layer, the image size is reduced in this way.
model = tf.keras.models.Sequential([
Add another convolution
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
Now flatten the output. After this you’ll just have the same DNN structure as the non convolutional version
The same 128 dense layers, and 10 output layers as in the pre-convolution example:
Now compile the model, call the fit method to do the training, and evaluate the loss and accuracy from the test set.
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
This code will show us the convolutions graphically. The print (test_labels[;100]) shows us the first 100 labels in the test set, and you can see that the ones at index 0, index 23 and index 28 are all the same value (9). They’re all shoes. Let’s take a look at the result of running the convolution on each, and you’ll begin to see common features between them emerge. Now, when the DNN is training on that data, it’s working with a lot less, and it’s perhaps finding a commonality between shoes based on this convolution/pooling combination.
[9 2 1 1 6 1 4 6 5 7 4 5 7 3 4 1 2 4 8 0 2 5 7 9 1 4 6 0 9 3 8 8 3 3 8 0 7 5 7 9 6 1 3 7 6 7 2 1 2 2 4 4 5 8 2 2 8 4 8 0 7 7 8 5 1 1 2 3 9 8 7 0 2 6 2 3 1 2 8 4 1 8 5 9 5 0 3 2 0 6 5 3 6 7 1 8 0 1 4 2]
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
Try editing the convolutions. Change the 32s to either 16 or 64. What impact will this have on accuracy and/or training time.
Remove the final Convolution. What impact will this have on accuracy or training time?
How about adding more Convolutions? What impact do you think this will have? Experiment with it.
Remove all Convolutions but the first. What impact do you think this will have? Experiment with it.
In the previous lesson you implemented a callback to check on the loss function and to cancel training once it hit a certain amount. See if you can implement that here!
import tensorflow as tf
1.12.0 Epoch 1/10 60000/60000==============================] - 6s 104us/sample - loss: 0.1510 - acc: 0.9551 Epoch 2/10 60000/60000==============================] - 5s 79us/sample - loss: 0.0512 - acc: 0.9843 Epoch 3/10 60000/60000==============================] - 5s 77us/sample - loss: 0.0319 - acc: 0.9902 Epoch 4/10 60000/60000==============================] - 5s 78us/sample - loss: 0.0209 - acc: 0.9934 Epoch 5/10 60000/60000==============================] - 5s 78us/sample - loss: 0.0136 - acc: 0.9956 Epoch 6/10 60000/60000==============================] - 5s 78us/sample - loss: 0.0111 - acc: 0.9964 Epoch 7/10 60000/60000==============================] - 5s 79us/sample - loss: 0.0076 - acc: 0.9974 Epoch 8/10 60000/60000==============================] - 5s 78us/sample - loss: 0.0052 - acc: 0.9985 Epoch 9/10 60000/60000==============================] - 5s 81us/sample - loss: 0.0046 - acc: 0.9988 Epoch 10/10 60000/60000==============================] - 5s 81us/sample - loss: 0.0053 - acc: 0.9981 10000/10000==============================] - 1s 53us/sample - loss: 0.0583 - acc: 0.9873 0.9873