Machine Learning Engineer Nanodegree

Deep Learning

📑   Practice Project 4: Convolutional Neural Networks

In this notebook, we train a CNN on augmented images from the CIFAR-10 database.

1. Load CIFAR-10 Database

In [2]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: #add8e6;} 
a {color: darkblue; font-family: 'Roboto';} 
h1 {color: steelblue; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;} 
h2, h3 {color: #483d8b; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;}
h4 {color: slategray; font-family: 'Roboto';}
span {text-shadow: 4px 4px 4px #ccc;}
div.output_prompt, div.output_area pre {color: #483d8b;}
div.input_prompt, div.output_subarea {color: darkblue;}      
div.output_stderr pre {background-color: #add8e6;}  
div.output_stderr {background-color: #483d8b;}        
</style>
In [1]:
import keras
from keras.datasets import cifar10

# load the pre-shuffled train and test data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
Using TensorFlow backend.

2. Visualize the First 24 Training Images

In [3]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,5))
for i in range(36):
    ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(x_train[i]))

3. Rescale the Images by Dividing Every Pixel in Every Image by 255

In [4]:
# rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255 

4. Break Dataset into Training, Testing, and Validation Sets

In [5]:
from keras.utils import np_utils

# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]

# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_valid = keras.utils.to_categorical(y_valid, num_classes)

# print shape of training set
print('x_train shape:', x_train.shape)

# print number of training, validation, and test images
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')
x_train shape: (45000, 32, 32, 3)
45000 train samples
10000 test samples
5000 validation samples

5. Create and Configure Augmented Image Generator

In [6]:
from keras.preprocessing.image import ImageDataGenerator

# create and configure augmented image generator
datagen_train = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True) # randomly flip images horizontally

# create and configure augmented image generator
datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True) # randomly flip images horizontally

# fit augmented image generator on data
datagen_train.fit(x_train)
datagen_valid.fit(x_valid)

6. Visualize Original and Augmented Images

In [7]:
import matplotlib.pyplot as plt

# take subset of training data
x_train_subset = x_train[:12]

# visualize subset of training data
fig = plt.figure(figsize=(20,2))
for i in range(0, len(x_train_subset)):
    ax = fig.add_subplot(1, 12, i+1)
    ax.imshow(x_train_subset[i])
fig.suptitle('Subset of Original Training Images', fontsize=20)
plt.show()

# visualize augmented images
fig = plt.figure(figsize=(20,2))
for x_batch in datagen_train.flow(x_train_subset, batch_size=12):
    for i in range(0, 12):
        ax = fig.add_subplot(1, 12, i+1)
        ax.imshow(x_batch[i])
    fig.suptitle('Augmented Images', fontsize=20)
    plt.show()
    break;

7. Define the Model Architecture

In [11]:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout

model = Sequential()

model.add(Conv2D(filters=16, kernel_size=2, 
                 padding='same', activation='relu', 
                 input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))

model.add(Conv2D(filters=32, kernel_size=2, 
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))

model.add(Conv2D(filters=64, kernel_size=2, 
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))

model.add(Dropout(0.25))
model.add(Flatten())

model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(10, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_4 (Conv2D)            (None, 32, 32, 16)        208       
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 16, 16, 16)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 16, 16, 32)        2080      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 8, 8, 32)          0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 8, 8, 64)          8256      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 4, 4, 64)          0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 4, 4, 64)          0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 1024)              0         
_________________________________________________________________
dense_3 (Dense)              (None, 512)               524800    
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 10)                5130      
=================================================================
Total params: 540,474
Trainable params: 540,474
Non-trainable params: 0
_________________________________________________________________

8. Compile the Model

In [12]:
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', 
                  metrics=['accuracy'])

9. Train the Model

In [13]:
from keras.callbacks import ModelCheckpoint   

batch_size = 128
epochs = 10

# train the model
checkpointer = ModelCheckpoint(filepath='aug_model.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
model.fit_generator(datagen_train.flow(x_train, y_train, batch_size=batch_size),
                    steps_per_epoch=x_train.shape[0] // batch_size,
                    epochs=epochs, verbose=2, callbacks=[checkpointer],
                    validation_data=datagen_valid.flow(x_valid, y_valid, batch_size=batch_size),
                    validation_steps=x_valid.shape[0] // batch_size)
Epoch 1/10
Epoch 00000: val_loss improved from inf to 1.54148, saving model to aug_model.weights.best.hdf5
126s - loss: 1.8026 - acc: 0.3463 - val_loss: 1.5415 - val_acc: 0.4641
Epoch 2/10
Epoch 00001: val_loss improved from 1.54148 to 1.32769, saving model to aug_model.weights.best.hdf5
108s - loss: 1.5091 - acc: 0.4587 - val_loss: 1.3277 - val_acc: 0.5252
Epoch 3/10
Epoch 00002: val_loss did not improve
120s - loss: 1.3822 - acc: 0.5047 - val_loss: 1.3558 - val_acc: 0.5343
Epoch 4/10
Epoch 00003: val_loss improved from 1.32769 to 1.16864, saving model to aug_model.weights.best.hdf5
118s - loss: 1.2936 - acc: 0.5374 - val_loss: 1.1686 - val_acc: 0.5922
Epoch 5/10
Epoch 00004: val_loss improved from 1.16864 to 1.09306, saving model to aug_model.weights.best.hdf5
97s - loss: 1.2255 - acc: 0.5646 - val_loss: 1.0931 - val_acc: 0.6053
Epoch 6/10
Epoch 00005: val_loss improved from 1.09306 to 1.06451, saving model to aug_model.weights.best.hdf5
68s - loss: 1.1775 - acc: 0.5795 - val_loss: 1.0645 - val_acc: 0.6289
Epoch 7/10
Epoch 00006: val_loss improved from 1.06451 to 1.01431, saving model to aug_model.weights.best.hdf5
60s - loss: 1.1388 - acc: 0.5975 - val_loss: 1.0143 - val_acc: 0.6422
Epoch 8/10
Epoch 00007: val_loss did not improve
66s - loss: 1.1046 - acc: 0.6079 - val_loss: 1.0428 - val_acc: 0.6375
Epoch 9/10
Epoch 00008: val_loss improved from 1.01431 to 0.96278, saving model to aug_model.weights.best.hdf5
62s - loss: 1.0818 - acc: 0.6187 - val_loss: 0.9628 - val_acc: 0.6626
Epoch 10/10
Epoch 00009: val_loss improved from 0.96278 to 0.93836, saving model to aug_model.weights.best.hdf5
59s - loss: 1.0555 - acc: 0.6283 - val_loss: 0.9384 - val_acc: 0.6728
Out[13]:
<keras.callbacks.History at 0x11bbf1a90>

10. Load the Model with the Best Validation Accuracy

In [14]:
# load the weights that yielded the best validation accuracy
model.load_weights('aug_model.weights.best.hdf5')

11. Calculate Classification Accuracy on Test Set

In [15]:
# evaluate and print test accuracy
score = model.evaluate(x_test, y_test, verbose=0)
print('\n', 'Test accuracy:', score[1])
 Test accuracy: 0.6788

12. Visualize Some Predictions

This may give you some insight into why the network is misclassifying certain objects.

In [16]:
# get predictions on the test set
y_hat = model.predict(x_test)

# define text labels (source: https://www.cs.toronto.edu/~kriz/cifar.html)
cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
In [18]:
# plot a random sample of test images, their predicted labels, and ground truth
fig = plt.figure(figsize=(20, 8))
for i, idx in enumerate(np.random.choice(x_test.shape[0], size=32, replace=False)):
    ax = fig.add_subplot(4, 8, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(x_test[idx]))
    pred_idx = np.argmax(y_hat[idx])
    true_idx = np.argmax(y_test[idx])
    ax.set_title("{} ({})".format(cifar10_labels[pred_idx], cifar10_labels[true_idx]),
                 color=("green" if pred_idx == true_idx else "red"))