Traffic Sign Classification with Keras

Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to use Keras to build a convolutional neural network in a few dozen lines of code.

You’ll be connecting the concepts from the previous lessons to the methods that Keras provides.

Dataset

The network you'll build with Keras is similar to the example in Keras’s GitHub repository that builds out a convolutional neural network for MNIST.

However, instead of using the MNIST dataset, you're going to use the German Traffic Sign Recognition Benchmark dataset that you've used previously.

You can download pickle files with sanitized traffic sign data here:


In [1]:
from urllib.request import urlretrieve
from os.path import isfile
from tqdm import tqdm

class DLProgress(tqdm):
    last_block = 0

    def hook(self, block_num=1, block_size=1, total_size=None):
        self.total = total_size
        self.update((block_num - self.last_block) * block_size)
        self.last_block = block_num

if not isfile('train.p'):
    with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Train Dataset') as pbar:
        urlretrieve(
            'https://s3.amazonaws.com/udacity-sdc/datasets/german_traffic_sign_benchmark/train.p',
            'train.p',
            pbar.hook)

if not isfile('test.p'):
    with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Test Dataset') as pbar:
        urlretrieve(
            'https://s3.amazonaws.com/udacity-sdc/datasets/german_traffic_sign_benchmark/test.p',
            'test.p',
            pbar.hook)

print('Training and Test data downloaded.')


Training and Test data downloaded.

Overview

Here are the steps you'll take to build the network:

  1. Load the training data.
  2. Preprocess the data.
  3. Build a feedforward neural network to classify traffic signs.
  4. Build a convolutional neural network to classify traffic signs.
  5. Evaluate the final neural network on testing data.

Keep an eye on the network’s accuracy over time. Once the accuracy reaches the 98% range, you can be confident that you’ve built and trained an effective model.


In [2]:
import pickle
import numpy as np
import math

# Fix error with TF and Keras
import tensorflow as tf
tf.python.control_flow_ops = tf

print('Modules loaded.')


Modules loaded.

Load the Data

Start by importing the data from the pickle file.


In [3]:
with open('train.p', 'rb') as f:
    data = pickle.load(f)

# TODO: Load the feature data to the variable X_train
X_train = data['features']

# TODO: Load the label data to the variable y_train
y_train = data['labels']

In [4]:
# STOP: Do not change the tests below. Your implementation should pass these tests. 
assert np.array_equal(X_train, data['features']), 'X_train not set to data[\'features\'].'
assert np.array_equal(y_train, data['labels']), 'y_train not set to data[\'labels\'].'
print('Tests passed.')


Tests passed.

Preprocess the Data

  1. Shuffle the data
  2. Normalize the features using Min-Max scaling between -0.5 and 0.5
  3. One-Hot Encode the labels

Shuffle the data

Hint: You can use the scikit-learn shuffle function to shuffle the data.


In [5]:
# TODO: Shuffle the data
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)

In [6]:
# STOP: Do not change the tests below. Your implementation should pass these tests. 
assert X_train.shape == data['features'].shape, 'X_train has changed shape. The shape shouldn\'t change when shuffling.'
assert y_train.shape == data['labels'].shape, 'y_train has changed shape. The shape shouldn\'t change when shuffling.'
assert not np.array_equal(X_train, data['features']), 'X_train not shuffled.'
assert not np.array_equal(y_train, data['labels']), 'y_train not shuffled.'
print('Tests passed.')


Tests passed.

Normalize the features

Hint: You solved this in TensorFlow lab Problem 1.


In [7]:
# TODO: Normalize the data features to the variable X_normalized

def normalize_grayscale(image_data):
    """
    Normalize the image data with Min-Max scaling to a range of [-0.5, 0.5]
    :param image_data: The image data to be normalized
    :return: Normalized image data
    """
    a = -0.5
    b = 0.5
    grayscale_min = 0
    grayscale_max = 255
    return a + ( ( (image_data - grayscale_min)*(b - a) )/( grayscale_max - grayscale_min ) )

X_normalized = normalize_grayscale(X_train)

In [8]:
# STOP: Do not change the tests below. Your implementation should pass these tests. 
assert math.isclose(np.min(X_normalized), -0.5, abs_tol=1e-5) and math.isclose(np.max(X_normalized), 0.5, abs_tol=1e-5), 'The range of the training data is: {} to {}.  It must be -0.5 to 0.5'.format(np.min(X_normalized), np.max(X_normalized))
print('Tests passed.')


Tests passed.

One-Hot Encode the labels

Hint: You can use the scikit-learn LabelBinarizer function to one-hot encode the labels.


In [9]:
# TODO: One Hot encode the labels to the variable y_one_hot
from sklearn import preprocessing

lb = preprocessing.LabelBinarizer()
y_one_hot = lb.fit_transform(y_train)

In [10]:
# STOP: Do not change the tests below. Your implementation should pass these tests. 
import collections

assert y_one_hot.shape == (39209, 43), 'y_one_hot is not the correct shape.  It\'s {}, it should be (39209, 43)'.format(y_one_hot.shape)
assert next((False for y in y_one_hot if collections.Counter(y) != {0: 42, 1: 1}), True), 'y_one_hot not one-hot encoded.'
print('Tests passed.')


Tests passed.

Keras Sequential Model

from keras.models import Sequential

# Create the Sequential model
model = Sequential()

The keras.models.Sequential class is a wrapper for the neural network model. Just like many of the class models in scikit-learn, it provides common functions like fit(), evaluate(), and compile(). We'll cover these functions as we get to them. Let's start looking at the layers of the model.

Keras Layer

A Keras layer is just like a neural network layer. It can be fully connected, max pool, activation, etc. You can add a layer to the model using the model's add() function. For example, a simple model would look like this:

from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten

# Create the Sequential model
model = Sequential()

# 1st Layer - Add a flatten layer
model.add(Flatten(input_shape=(32, 32, 3)))

# 2nd Layer - Add a fully connected layer
model.add(Dense(100))

# 3rd Layer - Add a ReLU activation layer
model.add(Activation('relu'))

# 4th Layer - Add a fully connected layer
model.add(Dense(60))

# 5th Layer - Add a ReLU activation layer
model.add(Activation('relu'))

Keras will automatically infer the shape of all layers after the first layer. This means you only have to set the input dimensions for the first layer.

The first layer from above, model.add(Flatten(input_shape=(32, 32, 3))), sets the input dimension to (32, 32, 3) and output dimension to (3072=32*32*3). The second layer takes in the output of the first layer and sets the output dimenions to (100). This chain of passing output to the next layer continues until the last layer, which is the output of the model.

Build a Multi-Layer Feedforward Network

Build a multi-layer feedforward neural network to classify the traffic sign images.

  1. Set the first layer to a Flatten layer with the input_shape set to (32, 32, 3)
  2. Set the second layer to Dense layer width to 128 output.
  3. Use a ReLU activation function after the second layer.
  4. Set the output layer width to 43, since there are 43 classes in the dataset.
  5. Use a softmax activation function after the output layer.

To get started, review the Keras documentation about models and layers.

The Keras example of a Multi-Layer Perceptron network is similar to what you need to do here. Use that as a guide, but keep in mind that there are a number of differences.


In [11]:
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
model = Sequential()
# TODO: Build a Multi-layer feedforward neural network with Keras here.
# 1st Layer - Add a flatten layer
model.add(Flatten(input_shape=(32, 32, 3)))
# 2nd Layer - Add a fully connected layer
model.add(Dense(128))
# 3rd Layer - Add a ReLU activation layer
model.add(Activation('relu'))
# 4th Layer - Add a fully connected layer
model.add(Dense(43))
# 5th Layer - Add a ReLU activation layer
model.add(Activation('softmax'))


Using TensorFlow backend.

In [12]:
# STOP: Do not change the tests below. Your implementation should pass these tests.
from keras.layers.core import Dense, Activation, Flatten
from keras.activations import relu, softmax

def check_layers(layers, true_layers):
    assert len(true_layers) != 0, 'No layers found'
    for layer_i in range(len(layers)):
        assert isinstance(true_layers[layer_i], layers[layer_i]), 'Layer {} is not a {} layer'.format(layer_i+1, layers[layer_i].__name__)
    assert len(true_layers) == len(layers), '{} layers found, should be {} layers'.format(len(true_layers), len(layers))

check_layers([Flatten, Dense, Activation, Dense, Activation], model.layers)

assert model.layers[0].input_shape == (None, 32, 32, 3), 'First layer input shape is wrong, it should be (32, 32, 3)'
assert model.layers[1].output_shape == (None, 128), 'Second layer output is wrong, it should be (128)'
assert model.layers[2].activation == relu, 'Third layer not a relu activation layer'
assert model.layers[3].output_shape == (None, 43), 'Fourth layer output is wrong, it should be (43)'
assert model.layers[4].activation == softmax, 'Fifth layer not a softmax activation layer'
print('Tests passed.')


Tests passed.

Training a Sequential Model

You built a multi-layer neural network in Keras, now let's look at training a neural network.

from keras.models import Sequential
from keras.layers.core import Dense, Activation

model = Sequential()
...

# Configures the learning process and metrics
model.compile('sgd', 'mean_squared_error', ['accuracy'])

# Train the model
# History is a record of training loss and metrics
history = model.fit(x_train_data, Y_train_data, batch_size=128, nb_epoch=2, validation_split=0.2)

# Calculate test score
test_score = model.evaluate(x_test_data, Y_test_data)

The code above configures, trains, and tests the model. The line model.compile('sgd', 'mean_squared_error', ['accuracy']) configures the model's optimizer to 'sgd'(stochastic gradient descent), the loss to 'mean_squared_error', and the metric to 'accuracy'.

You can find more optimizers here, loss functions here, and more metrics here.

To train the model, use the fit() function as shown in model.fit(x_train_data, Y_train_data, batch_size=128, nb_epoch=2, validation_split=0.2). The validation_split parameter will split a percentage of the training dataset to be used to validate the model. The model can be further tested with the test dataset using the evaluation() function as shown in the last line.

Train the Network

  1. Compile the network using adam optimizer and categorical_crossentropy loss function.
  2. Train the network for ten epochs and validate with 20% of the training data.

In [13]:
# TODO: Compile and train the model here.
# Configures the learning process and metrics
model.compile('adam', 'categorical_crossentropy', ['accuracy'])
print(model.summary())

# Train the model
# History is a record of training loss and metrics
history = model.fit(X_normalized, y_one_hot, batch_size=128, nb_epoch=10, validation_split=0.2)


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
flatten_1 (Flatten)              (None, 3072)          0           flatten_input_1[0][0]            
____________________________________________________________________________________________________
dense_1 (Dense)                  (None, 128)           393344      flatten_1[0][0]                  
____________________________________________________________________________________________________
activation_1 (Activation)        (None, 128)           0           dense_1[0][0]                    
____________________________________________________________________________________________________
dense_2 (Dense)                  (None, 43)            5547        activation_1[0][0]               
____________________________________________________________________________________________________
activation_2 (Activation)        (None, 43)            0           dense_2[0][0]                    
====================================================================================================
Total params: 398,891
Trainable params: 398,891
Non-trainable params: 0
____________________________________________________________________________________________________
None
Train on 31367 samples, validate on 7842 samples
Epoch 1/10
31367/31367 [==============================] - 5s - loss: 1.7796 - acc: 0.5396 - val_loss: 1.1134 - val_acc: 0.6969
Epoch 2/10
31367/31367 [==============================] - 3s - loss: 0.8676 - acc: 0.7704 - val_loss: 0.8706 - val_acc: 0.7424
Epoch 3/10
31367/31367 [==============================] - 4s - loss: 0.6203 - acc: 0.8383 - val_loss: 0.6162 - val_acc: 0.8193
Epoch 4/10
31367/31367 [==============================] - 3s - loss: 0.4920 - acc: 0.8734 - val_loss: 0.6326 - val_acc: 0.8029
Epoch 5/10
31367/31367 [==============================] - 3s - loss: 0.4165 - acc: 0.8922 - val_loss: 0.4443 - val_acc: 0.8772
Epoch 6/10
31367/31367 [==============================] - 3s - loss: 0.3636 - acc: 0.9060 - val_loss: 0.3527 - val_acc: 0.9079
Epoch 7/10
31367/31367 [==============================] - 3s - loss: 0.3122 - acc: 0.9200 - val_loss: 0.3397 - val_acc: 0.9047
Epoch 8/10
31367/31367 [==============================] - 4s - loss: 0.2900 - acc: 0.9242 - val_loss: 0.4611 - val_acc: 0.8527
Epoch 9/10
31367/31367 [==============================] - 4s - loss: 0.2771 - acc: 0.9245 - val_loss: 0.3384 - val_acc: 0.8976
Epoch 10/10
31367/31367 [==============================] - 4s - loss: 0.2560 - acc: 0.9309 - val_loss: 0.3576 - val_acc: 0.8968

In [14]:
# STOP: Do not change the tests below. Your implementation should pass these tests.
from keras.optimizers import Adam

assert model.loss == 'categorical_crossentropy', 'Not using categorical_crossentropy loss function'
assert isinstance(model.optimizer, Adam), 'Not using adam optimizer'
assert len(history.history['acc']) == 10, 'You\'re using {} epochs when you need to use 10 epochs.'.format(len(history.history['acc']))

assert history.history['acc'][-1] > 0.92, 'The training accuracy was: %.3f. It shoud be greater than 0.92' % history.history['acc'][-1]
assert history.history['val_acc'][-1] > 0.85, 'The validation accuracy is: %.3f. It shoud be greater than 0.85' % history.history['val_acc'][-1]
print('Tests passed.')


Tests passed.

Convolutions

  1. Re-construct the previous network
  2. Add a convolutional layer with 32 filters, a 3x3 kernel, and valid padding before the flatten layer.
  3. Add a ReLU activation after the convolutional layer.

Hint 1: The Keras example of a convolutional neural network for MNIST would be a good example to review.


In [15]:
# TODO: Re-construct the network and add a convolutional layer before the flatten layer.
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D
model = Sequential()
# 1st Layer - Add a convolution with 32 filters, 3x3 kernel, and valid padding
model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(32, 32, 3)))
# 2nd Layer - Add a ReLU activation layer
model.add(Activation('relu'))
# 3rd Layer - Add a flatten layer
model.add(Flatten())
# 4th Layer - Add a fully connected layer
model.add(Dense(128))
# 5th Layer - Add a ReLU activation layer
model.add(Activation('relu'))
# 6th Layer - Add a fully connected layer
model.add(Dense(43))
# 7th Layer - Add a ReLU activation layer
model.add(Activation('softmax'))

In [16]:
# STOP: Do not change the tests below. Your implementation should pass these tests.
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D

check_layers([Convolution2D, Activation, Flatten, Dense, Activation, Dense, Activation], model.layers)

assert model.layers[0].input_shape == (None, 32, 32, 3), 'First layer input shape is wrong, it should be (32, 32, 3)'
assert model.layers[0].nb_filter == 32, 'Wrong number of filters, it should be 32'
assert model.layers[0].nb_col == model.layers[0].nb_row == 3, 'Kernel size is wrong, it should be a 3x3'
assert model.layers[0].border_mode == 'valid', 'Wrong padding, it should be valid'

model.compile('adam', 'categorical_crossentropy', ['accuracy'])
history = model.fit(X_normalized, y_one_hot, batch_size=128, nb_epoch=2, validation_split=0.2)
assert(history.history['val_acc'][-1] > 0.91), "The validation accuracy is: %.3f.  It should be greater than 0.91" % history.history['val_acc'][-1]
print('Tests passed.')


Train on 31367 samples, validate on 7842 samples
Epoch 1/2
31367/31367 [==============================] - 17s - loss: 1.1945 - acc: 0.6902 - val_loss: 0.4400 - val_acc: 0.8775
Epoch 2/2
31367/31367 [==============================] - 17s - loss: 0.3033 - acc: 0.9247 - val_loss: 0.2567 - val_acc: 0.9345
Tests passed.

Pooling

  1. Re-construct the network
  2. Add a 2x2 max pooling layer immediately following your convolutional layer.

In [17]:
# TODO: Re-construct the network and add a pooling layer after the convolutional layer.
# TODO: Re-construct the network and add a convolutional layer before the flatten layer.
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

model = Sequential()
# Add a convolution with 32 filters, 3x3 kernel, and valid padding
model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(32, 32, 3)))
# Add a max pooling of 2x2
model.add(MaxPooling2D(pool_size=(2, 2)))
# Add a ReLU activation layer
model.add(Activation('relu'))
# Add a flatten layer
model.add(Flatten())
# Add a fully connected layer
model.add(Dense(128))
# Add a ReLU activation layer
model.add(Activation('relu'))
# Add a fully connected layer
model.add(Dense(43))
# Add a ReLU activation layer
model.add(Activation('softmax'))

In [19]:
# STOP: Do not change the tests below. Your implementation should pass these tests.
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

check_layers([Convolution2D, MaxPooling2D, Activation, Flatten, Dense, Activation, Dense, Activation], model.layers)
assert model.layers[1].pool_size == (2, 2), 'Second layer must be a max pool layer with pool size of 2x2'

model.compile('adam', 'categorical_crossentropy', ['accuracy'])
history = model.fit(X_normalized, y_one_hot, batch_size=128, nb_epoch=4, validation_split=0.2)
assert(history.history['val_acc'][-1] > 0.91), "The validation accuracy is: %.3f.  It should be greater than 0.91" % history.history['val_acc'][-1]
print('Tests passed.')


Train on 31367 samples, validate on 7842 samples
Epoch 1/2
31367/31367 [==============================] - 12s - loss: 0.2298 - acc: 0.9460 - val_loss: 0.1984 - val_acc: 0.9482
Epoch 2/2
31367/31367 [==============================] - 13s - loss: 0.1372 - acc: 0.9709 - val_loss: 0.1481 - val_acc: 0.9645
Tests passed.

Dropout

  1. Re-construct the network
  2. Add a dropout layer after the pooling layer. Set the dropout rate to 50%.

In [20]:
# TODO: Re-construct the network and add dropout after the pooling layer.
# TODO: Re-construct the network and add a pooling layer after the convolutional layer.
# TODO: Re-construct the network and add a convolutional layer before the flatten layer.
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

model = Sequential()
# Add a convolution with 32 filters, 3x3 kernel, and valid padding
model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(32, 32, 3)))
# Add a max pooling of 2x2
model.add(MaxPooling2D(pool_size=(2, 2)))
# Add a dropout of 50%
model.add(Dropout(0.5))
# Add a ReLU activation layer
model.add(Activation('relu'))
# Add a flatten layer
model.add(Flatten())
# Add a fully connected layer
model.add(Dense(128))
# Add a ReLU activation layer
model.add(Activation('relu'))
# Add a fully connected layer
model.add(Dense(43))
# Add a ReLU activation layer
model.add(Activation('softmax'))

In [21]:
# STOP: Do not change the tests below. Your implementation should pass these tests.
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

check_layers([Convolution2D, MaxPooling2D, Dropout, Activation, Flatten, Dense, Activation, Dense, Activation], model.layers)
assert model.layers[2].p == 0.5, 'Third layer should be a Dropout of 50%'

model.compile('adam', 'categorical_crossentropy', ['accuracy'])
history = model.fit(X_normalized, y_one_hot, batch_size=128, nb_epoch=2, validation_split=0.2)
assert(history.history['val_acc'][-1] > 0.91), "The validation accuracy is: %.3f.  It should be greater than 0.91" % history.history['val_acc'][-1]
print('Tests passed.')


Train on 31367 samples, validate on 7842 samples
Epoch 1/2
31367/31367 [==============================] - 14s - loss: 1.5714 - acc: 0.5899 - val_loss: 0.6484 - val_acc: 0.8514
Epoch 2/2
31367/31367 [==============================] - 14s - loss: 0.5002 - acc: 0.8717 - val_loss: 0.3242 - val_acc: 0.9297
Tests passed.

Optimization

Congratulations! You've built a neural network with convolutions, pooling, dropout, and fully-connected layers, all in just a few lines of code.

Have fun with the model and see how well you can do! Add more layers, or regularization, or different padding, or batches, or more training epochs.

What is the best validation accuracy you can achieve?


In [27]:
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
from keras.regularizers import l2, activity_l2

model = Sequential()
# Add a convolution with 32 filters, 3x3 kernel, and valid padding
model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(32, 32, 3)))
# Add a max pooling of 2x2
model.add(MaxPooling2D(pool_size=(2, 2)))
# Add a dropout of 50%
model.add(Dropout(0.5))
# Add a ReLU activation layer
model.add(Activation('relu'))

# Add a convolution with 64 filters, 2x2 kernel, and valid padding
model.add(Convolution2D(64, 2, 2, border_mode='valid'))
# Add a max pooling of 2x2
model.add(MaxPooling2D(pool_size=(2, 2)))
# Add a dropout of 50%
model.add(Dropout(0.5))
# Add a ReLU activation layer
model.add(Activation('relu'))

# Add a flatten layer
model.add(Flatten())
# Add a fully connected layer
model.add(Dense(128, W_regularizer=l2(0.0001), activity_regularizer=activity_l2(0.0001)))
# Add a ReLU activation layer
model.add(Activation('relu'))
# Add a fully connected layer
model.add(Dense(43, W_regularizer=l2(0.0001), activity_regularizer=activity_l2(0.0001)))
# Add a ReLU activation layer
model.add(Activation('softmax'))
print(model.summary())

model.compile('adam', 'categorical_crossentropy', ['accuracy'])
history = model.fit(X_normalized, y_one_hot, batch_size=256, nb_epoch=20, validation_split=0.2)


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
convolution2d_14 (Convolution2D) (None, 30, 30, 32)    896         convolution2d_input_9[0][0]      
____________________________________________________________________________________________________
maxpooling2d_13 (MaxPooling2D)   (None, 15, 15, 32)    0           convolution2d_14[0][0]           
____________________________________________________________________________________________________
dropout_12 (Dropout)             (None, 15, 15, 32)    0           maxpooling2d_13[0][0]            
____________________________________________________________________________________________________
activation_32 (Activation)       (None, 15, 15, 32)    0           dropout_12[0][0]                 
____________________________________________________________________________________________________
convolution2d_15 (Convolution2D) (None, 14, 14, 64)    8256        activation_32[0][0]              
____________________________________________________________________________________________________
maxpooling2d_14 (MaxPooling2D)   (None, 7, 7, 64)      0           convolution2d_15[0][0]           
____________________________________________________________________________________________________
dropout_13 (Dropout)             (None, 7, 7, 64)      0           maxpooling2d_14[0][0]            
____________________________________________________________________________________________________
activation_33 (Activation)       (None, 7, 7, 64)      0           dropout_13[0][0]                 
____________________________________________________________________________________________________
flatten_10 (Flatten)             (None, 3136)          0           activation_33[0][0]              
____________________________________________________________________________________________________
dense_19 (Dense)                 (None, 128)           401536      flatten_10[0][0]                 
____________________________________________________________________________________________________
activation_34 (Activation)       (None, 128)           0           dense_19[0][0]                   
____________________________________________________________________________________________________
dense_20 (Dense)                 (None, 43)            5547        activation_34[0][0]              
____________________________________________________________________________________________________
activation_35 (Activation)       (None, 43)            0           dense_20[0][0]                   
====================================================================================================
Total params: 416,235
Trainable params: 416,235
Non-trainable params: 0
____________________________________________________________________________________________________
None
Train on 31367 samples, validate on 7842 samples
Epoch 1/20
31367/31367 [==============================] - 15s - loss: 3.3950 - acc: 0.2973 - val_loss: 2.8790 - val_acc: 0.5506
Epoch 2/20
31367/31367 [==============================] - 13s - loss: 2.6446 - acc: 0.6248 - val_loss: 2.3367 - val_acc: 0.7622
Epoch 3/20
31367/31367 [==============================] - 13s - loss: 2.3051 - acc: 0.7678 - val_loss: 2.0695 - val_acc: 0.8423
Epoch 4/20
31367/31367 [==============================] - 14s - loss: 2.1108 - acc: 0.8331 - val_loss: 1.8904 - val_acc: 0.8887
Epoch 5/20
31367/31367 [==============================] - 14s - loss: 1.9811 - acc: 0.8672 - val_loss: 1.7640 - val_acc: 0.9132
Epoch 6/20
31367/31367 [==============================] - 15s - loss: 1.8944 - acc: 0.8914 - val_loss: 1.6818 - val_acc: 0.9347
Epoch 7/20
31367/31367 [==============================] - 16s - loss: 1.8343 - acc: 0.9044 - val_loss: 1.6005 - val_acc: 0.9492
Epoch 8/20
31367/31367 [==============================] - 17s - loss: 1.7793 - acc: 0.9189 - val_loss: 1.5861 - val_acc: 0.9561
Epoch 9/20
31367/31367 [==============================] - 17s - loss: 1.7429 - acc: 0.9266 - val_loss: 1.5204 - val_acc: 0.9670
Epoch 10/20
31367/31367 [==============================] - 19s - loss: 1.7077 - acc: 0.9327 - val_loss: 1.4911 - val_acc: 0.9672
Epoch 11/20
31367/31367 [==============================] - 18s - loss: 1.6861 - acc: 0.9377 - val_loss: 1.4737 - val_acc: 0.9725
Epoch 12/20
31367/31367 [==============================] - 21s - loss: 1.6598 - acc: 0.9427 - val_loss: 1.4536 - val_acc: 0.9751
Epoch 13/20
31367/31367 [==============================] - 20s - loss: 1.6428 - acc: 0.9462 - val_loss: 1.4327 - val_acc: 0.9756
Epoch 14/20
31367/31367 [==============================] - 20s - loss: 1.6246 - acc: 0.9506 - val_loss: 1.4133 - val_acc: 0.9764
Epoch 15/20
31367/31367 [==============================] - 20s - loss: 1.6132 - acc: 0.9528 - val_loss: 1.4150 - val_acc: 0.9800
Epoch 16/20
31367/31367 [==============================] - 19s - loss: 1.6001 - acc: 0.9547 - val_loss: 1.3966 - val_acc: 0.9799
Epoch 17/20
31367/31367 [==============================] - 20s - loss: 1.5816 - acc: 0.9579 - val_loss: 1.3806 - val_acc: 0.9841
Epoch 18/20
31367/31367 [==============================] - 20s - loss: 1.5814 - acc: 0.9575 - val_loss: 1.3866 - val_acc: 0.9839
Epoch 19/20
31367/31367 [==============================] - 21s - loss: 1.5688 - acc: 0.9596 - val_loss: 1.3671 - val_acc: 0.9839
Epoch 20/20
31367/31367 [==============================] - 21s - loss: 1.5618 - acc: 0.9606 - val_loss: 1.3654 - val_acc: 0.9830

Best Validation Accuracy:

So far I've achieved 98.3%.

Testing

Once you've picked out your best model, it's time to test it.

Load up the test data and use the evaluate() method to see how well it does.

Hint 1: The evaluate() method should return an array of numbers. Use the metrics_names property to get the labels.


In [32]:
# TODO: Load test data
with open('test.p', 'rb') as f:
    data = pickle.load(f)

X_test = data['features']

y_test = data['labels']
    
# TODO: Preprocess data & one-hot encode the labels
def normalize_grayscale(image_data):
    """
    Normalize the image data with Min-Max scaling to a range of [-0.5, 0.5]
    :param image_data: The image data to be normalized
    :return: Normalized image data
    """
    a = -0.5
    b = 0.5
    grayscale_min = 0
    grayscale_max = 255
    return a + ( ( (image_data - grayscale_min)*(b - a) )/( grayscale_max - grayscale_min ) )

X_test_normalized = normalize_grayscale(X_test)

from sklearn import preprocessing

lb = preprocessing.LabelBinarizer()
y_test_one_hot = lb.fit_transform(y_test)

# TODO: Evaluate model on test data
print(model.metrics_names)
model.evaluate(X_test_normalized, y_test_one_hot, batch_size=256, verbose=1, sample_weight=None)


['loss', 'acc']
12630/12630 [==============================] - 7s     
Out[32]:
[1.5483419682804027, 0.93626286633318601]

Test Accuracy:

Obtained a 93.6% accuracy.

Summary

Keras is a great tool to use if you want to quickly build a neural network and evaluate performance.