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 [3]:
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 [4]:
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 [5]:
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 [6]:
# 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 [7]:
# TODO: Shuffle the data
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)

In [8]:
# 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 [9]:
# TODO: Normalize the data features to the variable X_normalized
import cv2
def gray_normalize(image_data):
    """
    Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
    :param image_data: The image data to be normalized
    :return: Normalized image data
    """
    for i in range(image_data.shape[0]):
        gray =  cv2.resize(cv2.cvtColor(image_data[i], cv2.COLOR_RGB2GRAY), (32, 32)).reshape(1,32,32,1)
        if 0==i:
            X_normalized = gray
        else:
            X_normalized = np.append(X_normalized, gray, axis=0)
    # TODO: Implement Min-Max scaling for grayscale image data
    x_min = np.min(X_normalized)
    x_max = np.max(X_normalized)
    a = -0.5
    b = 0.5
    image_data_rescale = a+ (X_normalized - x_min)*(b-a)/(x_max - x_min)
    return image_data_rescale

def normalize(image_data):
    """
    Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
    :param image_data: The image data to be normalized
    :return: Normalized image data
    """
    # TODO: Implement Min-Max scaling for grayscale image data
    x_min = np.min(image_data)
    x_max = np.max(image_data)
    a = -0.5
    b = 0.5
    image_data_rescale = a+ (image_data - x_min)*(b-a)/(x_max - x_min)
    return image_data_rescale
X_normalized = normalize(X_train)
print('Data normalization finished')


Data normalization finished

In [10]:
# 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 [11]:
# TODO: One Hot encode the labels to the variable y_one_hot
# Turn labels into numbers and apply One-Hot Encoding
from sklearn.preprocessing import LabelBinarizer
encoder = LabelBinarizer()
encoder.fit(y_train)
y_one_hot = encoder.transform(y_train)

In [12]:
# 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 [30]:
# TODO: Build a Multi-layer feedforward neural network with Keras here.
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(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 softmax activation layer
model.add(Activation('softmax'))


Using TensorFlow backend.

In [31]:
# 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 [36]:
# TODO: Compile and train the model here.
# Configures the learning process and metrics
model.compile('adam', 'categorical_crossentropy', ['accuracy'])

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


Train on 31367 samples, validate on 7842 samples
Epoch 1/10
31367/31367 [==============================] - 6s - loss: 0.4899 - acc: 0.8729 - val_loss: 0.5014 - val_acc: 0.8683
Epoch 2/10
31367/31367 [==============================] - 6s - loss: 0.3969 - acc: 0.8965 - val_loss: 0.3701 - val_acc: 0.9030
Epoch 3/10
31367/31367 [==============================] - 6s - loss: 0.3555 - acc: 0.9048 - val_loss: 0.4499 - val_acc: 0.8622
Epoch 4/10
31367/31367 [==============================] - 7s - loss: 0.3180 - acc: 0.9162 - val_loss: 0.3237 - val_acc: 0.9018
Epoch 5/10
31367/31367 [==============================] - 6s - loss: 0.2689 - acc: 0.9301 - val_loss: 0.4297 - val_acc: 0.8639
Epoch 6/10
31367/31367 [==============================] - 6s - loss: 0.2571 - acc: 0.9338 - val_loss: 0.2899 - val_acc: 0.9216
Epoch 7/10
31367/31367 [==============================] - 6s - loss: 0.2494 - acc: 0.9323 - val_loss: 0.4384 - val_acc: 0.8629
Epoch 8/10
31367/31367 [==============================] - 6s - loss: 0.2309 - acc: 0.9380 - val_loss: 0.3110 - val_acc: 0.9041
Epoch 9/10
31367/31367 [==============================] - 6s - loss: 0.2063 - acc: 0.9442 - val_loss: 0.4773 - val_acc: 0.8690
Epoch 10/10
31367/31367 [==============================] - 6s - loss: 0.2165 - acc: 0.9414 - val_loss: 0.2640 - val_acc: 0.9223

In [37]:
# 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 [75]:
# 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 import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Flatten(input_shape=(32, 32, 3)))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(43))
model.add(Activation('softmax'))


(39209, 32, 32, 1)

In [76]:
# 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 [==============================] - 56s - loss: 1.3925 - acc: 0.6544 - val_loss: 0.5941 - val_acc: 0.8426
Epoch 2/2
31367/31367 [==============================] - 57s - loss: 0.4172 - acc: 0.9024 - val_loss: 0.3576 - val_acc: 0.9035
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-76-7944fe20bfc5> in <module>()
     12 model.compile('adam', 'categorical_crossentropy', ['accuracy'])
     13 history = model.fit(X_normalized, y_one_hot, batch_size=128, nb_epoch=2, validation_split=0.2)
---> 14 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]
     15 print('Tests passed.')

AssertionError: The validation accuracy is: 0.903.  It should be greater than 0.91

Pooling

  1. Re-construct the network
  2. Add a 2x2 max pooling layer immediately following your convolutional layer. (NO! max_pooling layer should follows the activation layer)

In [52]:
# TODO: Re-construct the network and add a pooling layer after the convolutional 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
from keras import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten(input_shape=(32, 32, 3)))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(43))
model.add(Activation('softmax'))

In [59]:
# 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, Activation, MaxPooling2D, Flatten, Dense, Activation, Dense, Activation], model.layers)
assert model.layers[2].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=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 [==============================] - 40s - loss: 1.1261 - acc: 0.7032 - val_loss: 0.6158 - val_acc: 0.8122
Epoch 2/2
31367/31367 [==============================] - 38s - loss: 0.4188 - acc: 0.8973 - val_loss: 0.3039 - val_acc: 0.9402
Tests passed.

Dropout

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

In [60]:
# TODO: Re-construct the network and add dropout after the pooling 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
from keras import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.5))
model.add(Flatten(input_shape=(32, 32, 3)))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(43))
model.add(Activation('softmax'))

In [63]:
# 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, Activation, MaxPooling2D, Dropout, Flatten, Dense, Activation, Dense, Activation], model.layers)
assert model.layers[3].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 [==============================] - 44s - loss: 1.6651 - acc: 0.5639 - val_loss: 0.6635 - val_acc: 0.8415
Epoch 2/2
31367/31367 [==============================] - 44s - loss: 0.5145 - acc: 0.8650 - val_loss: 0.3357 - val_acc: 0.9152
Tests passed.

Use more conv layers.


In [13]:
## Define traffic sign model
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 import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten(input_shape=(32, 32, 3)))
model.add(Dropout(0.5))
model.add(Dense(128, name="dense_1"))
model.add(Activation('relu'))
# model.add(Dropout(0.5))
model.add(Dense(43, name="dense_2"))
model.add(Activation('softmax'))

# Train and save traffic sign model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

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


Using TensorFlow backend.
Train on 31367 samples, validate on 7842 samples
Epoch 1/20
31367/31367 [==============================] - 61s - loss: 2.0332 - acc: 0.4377 - val_loss: 0.7617 - val_acc: 0.7809
Epoch 2/20
31367/31367 [==============================] - 60s - loss: 0.5870 - acc: 0.8229 - val_loss: 0.2997 - val_acc: 0.9286
Epoch 3/20
31367/31367 [==============================] - 59s - loss: 0.3239 - acc: 0.9065 - val_loss: 0.1762 - val_acc: 0.9569
Epoch 4/20
31367/31367 [==============================] - 59s - loss: 0.2268 - acc: 0.9359 - val_loss: 0.1287 - val_acc: 0.9711
Epoch 5/20
31367/31367 [==============================] - 59s - loss: 0.1688 - acc: 0.9530 - val_loss: 0.1004 - val_acc: 0.9788
Epoch 6/20
31367/31367 [==============================] - 59s - loss: 0.1366 - acc: 0.9623 - val_loss: 0.0946 - val_acc: 0.9799
Epoch 7/20
31367/31367 [==============================] - 59s - loss: 0.1213 - acc: 0.9656 - val_loss: 0.0727 - val_acc: 0.9850
Epoch 8/20
31367/31367 [==============================] - 59s - loss: 0.1007 - acc: 0.9715 - val_loss: 0.0602 - val_acc: 0.9878
Epoch 9/20
31367/31367 [==============================] - 59s - loss: 0.0879 - acc: 0.9754 - val_loss: 0.0667 - val_acc: 0.9867
Epoch 10/20
31367/31367 [==============================] - 59s - loss: 0.0807 - acc: 0.9771 - val_loss: 0.0524 - val_acc: 0.9881
Epoch 11/20
31367/31367 [==============================] - 60s - loss: 0.0749 - acc: 0.9782 - val_loss: 0.0522 - val_acc: 0.9904
Epoch 12/20
31367/31367 [==============================] - 59s - loss: 0.0655 - acc: 0.9812 - val_loss: 0.0480 - val_acc: 0.9908
Epoch 13/20
31367/31367 [==============================] - 60s - loss: 0.0587 - acc: 0.9832 - val_loss: 0.0499 - val_acc: 0.9889
Epoch 14/20
31367/31367 [==============================] - 59s - loss: 0.0616 - acc: 0.9823 - val_loss: 0.0423 - val_acc: 0.9909
Epoch 15/20
31367/31367 [==============================] - 59s - loss: 0.0522 - acc: 0.9844 - val_loss: 0.0353 - val_acc: 0.9925
Epoch 16/20
31367/31367 [==============================] - 59s - loss: 0.0451 - acc: 0.9871 - val_loss: 0.0432 - val_acc: 0.9890
Epoch 17/20
31367/31367 [==============================] - 61s - loss: 0.0415 - acc: 0.9875 - val_loss: 0.0358 - val_acc: 0.9929
Epoch 18/20
31367/31367 [==============================] - 59s - loss: 0.0462 - acc: 0.9858 - val_loss: 0.0365 - val_acc: 0.9923
Epoch 19/20
31367/31367 [==============================] - 58s - loss: 0.0377 - acc: 0.9885 - val_loss: 0.0322 - val_acc: 0.9932
Epoch 20/20
31367/31367 [==============================] - 58s - loss: 0.0368 - acc: 0.9883 - val_loss: 0.0341 - val_acc: 0.9923

Transfer learning from German Traffic Sign dataset to the Cifar10 dataset

Run the classifier used in the Traffic Sign project on the Cifar10 dataset. Cifar10 images are also (32, 32, 3), the only thing you'll need to change is the number of classes from 43 to 10.


In [14]:
## Define traffic sign model
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 import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape, name="conv_1"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.5))
model.add(Flatten(input_shape=(32, 32, 3)))
model.add(Dense(128, name="dense_1"))
model.add(Activation('relu'))
model.add(Dense(43, name="dense_2"))
model.add(Activation('softmax'))

# Train and save traffic sign model
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

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


Train on 31367 samples, validate on 7842 samples
Epoch 1/20
31367/31367 [==============================] - 41s - loss: 1.5734 - acc: 0.5867 - val_loss: 0.6911 - val_acc: 0.8156
Epoch 2/20
31367/31367 [==============================] - 41s - loss: 0.4890 - acc: 0.8731 - val_loss: 0.3337 - val_acc: 0.9271
Epoch 3/20
31367/31367 [==============================] - 41s - loss: 0.3017 - acc: 0.9239 - val_loss: 0.2357 - val_acc: 0.9461
Epoch 4/20
31367/31367 [==============================] - 45s - loss: 0.2288 - acc: 0.9410 - val_loss: 0.2049 - val_acc: 0.9492
Epoch 5/20
31367/31367 [==============================] - 49s - loss: 0.1805 - acc: 0.9534 - val_loss: 0.1625 - val_acc: 0.9616
Epoch 6/20
31367/31367 [==============================] - 45s - loss: 0.1569 - acc: 0.9579 - val_loss: 0.1537 - val_acc: 0.9644
Epoch 7/20
31367/31367 [==============================] - 45s - loss: 0.1323 - acc: 0.9657 - val_loss: 0.1342 - val_acc: 0.9702
Epoch 8/20
31367/31367 [==============================] - 42s - loss: 0.1184 - acc: 0.9692 - val_loss: 0.1174 - val_acc: 0.9737
Epoch 9/20
31367/31367 [==============================] - 42s - loss: 0.1090 - acc: 0.9714 - val_loss: 0.1120 - val_acc: 0.9742
Epoch 10/20
31367/31367 [==============================] - 42s - loss: 0.1006 - acc: 0.9729 - val_loss: 0.1187 - val_acc: 0.9719
Epoch 11/20
31367/31367 [==============================] - 46s - loss: 0.0906 - acc: 0.9751 - val_loss: 0.1074 - val_acc: 0.9759
Epoch 12/20
31367/31367 [==============================] - 46s - loss: 0.0857 - acc: 0.9767 - val_loss: 0.1028 - val_acc: 0.9765
Epoch 13/20
31367/31367 [==============================] - 48s - loss: 0.0824 - acc: 0.9769 - val_loss: 0.0950 - val_acc: 0.9788
Epoch 14/20
31367/31367 [==============================] - 45s - loss: 0.0711 - acc: 0.9813 - val_loss: 0.1052 - val_acc: 0.9764
Epoch 15/20
31367/31367 [==============================] - 44s - loss: 0.0710 - acc: 0.9802 - val_loss: 0.0910 - val_acc: 0.9807
Epoch 16/20
31367/31367 [==============================] - 42s - loss: 0.0679 - acc: 0.9818 - val_loss: 0.1018 - val_acc: 0.9758
Epoch 17/20
31367/31367 [==============================] - 42s - loss: 0.0652 - acc: 0.9812 - val_loss: 0.0765 - val_acc: 0.9848
Epoch 18/20
31367/31367 [==============================] - 42s - loss: 0.0548 - acc: 0.9850 - val_loss: 0.1006 - val_acc: 0.9783
Epoch 19/20
31367/31367 [==============================] - 42s - loss: 0.0525 - acc: 0.9857 - val_loss: 0.0895 - val_acc: 0.9814
Epoch 20/20
31367/31367 [==============================] - 42s - loss: 0.0541 - acc: 0.9847 - val_loss: 0.0892 - val_acc: 0.9816

In [15]:
## Download Cifar10 dataset
from keras.datasets import cifar10
from keras.utils import np_utils
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# y_train.shape is 2d, (50000, 1). While Keras is smart enough to handle this
# it's a good idea to flatten the array.
y_train = y_train.reshape(-1)
y_test = y_test.reshape(-1)

def normalize(image_data):
    """
    Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
    :param image_data: The image data to be normalized
    :return: Normalized image data
    """
    # TODO: Implement Min-Max scaling for grayscale image data
    x_min = np.min(image_data)
    x_max = np.max(image_data)
    a = -0.5
    b = 0.5
    image_data_rescale = a+ (image_data - x_min)*(b-a)/(x_max - x_min)
    return image_data_rescale
X_train = normalize(X_train)
X_test = normalize(X_test)
print('Data normalization finished')


Data normalization finished

In [35]:
## Define Cifar10 model
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 import backend as K

# input image dimensions
img_rows, img_cols = 32, 32
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

if K.image_dim_ordering() == 'th':
    X_normalized = X_normalized.reshape(X_normalized.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    X_normalized = X_normalized.reshape(X_normalized.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

# Create the Sequential model
model_cifar10 = Sequential()

model_cifar10.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape, name="conv_1"))
model_cifar10.add(Activation('relu'))
model_cifar10.add(MaxPooling2D(pool_size=pool_size))
model_cifar10.add(Dropout(0.5))
model_cifar10.add(Flatten(input_shape=(32, 32, 3)))
model_cifar10.add(Dense(128, name="dense_1"))
model_cifar10.add(Activation('relu'))
model_cifar10.add(Dense(10, name="dense_2_new"))
model_cifar10.add(Activation('softmax', name="acivation_3_new"))

# load and use model weight from traffic sign
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D

model_cifar10.compile('adam', 'categorical_crossentropy', ['accuracy'])
model_cifar10.load_weights('traffic_weights.h5', by_name=True)
score = model_cifar10.evaluate(X_test, y_test, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
model_cifar10.compile('adam', 'categorical_crossentropy', ['accuracy'])
history = model_cifar10.fit(X_train, y_train, batch_size=128, nb_epoch=10, validation_split=0.2)


10000/10000 [==============================] - 6s     
Test score: 11.8484480026
Test accuracy: 0.104
Train on 40000 samples, validate on 10000 samples
Epoch 1/10
40000/40000 [==============================] - 58s - loss: 2.1023 - acc: 0.3927 - val_loss: 1.3712 - val_acc: 0.5164
Epoch 2/10
40000/40000 [==============================] - 57s - loss: 1.3052 - acc: 0.5429 - val_loss: 1.2398 - val_acc: 0.5670
Epoch 3/10
40000/40000 [==============================] - 58s - loss: 1.1916 - acc: 0.5843 - val_loss: 1.1712 - val_acc: 0.5972
Epoch 4/10
40000/40000 [==============================] - 57s - loss: 1.1218 - acc: 0.6067 - val_loss: 1.1422 - val_acc: 0.6072
Epoch 5/10
40000/40000 [==============================] - 56s - loss: 1.0613 - acc: 0.6298 - val_loss: 1.1087 - val_acc: 0.6163
Epoch 6/10
40000/40000 [==============================] - 54s - loss: 1.0157 - acc: 0.6450 - val_loss: 1.0827 - val_acc: 0.6308
Epoch 7/10
40000/40000 [==============================] - 57s - loss: 0.9734 - acc: 0.6603 - val_loss: 1.0749 - val_acc: 0.6273
Epoch 8/10
40000/40000 [==============================] - 60s - loss: 0.9348 - acc: 0.6722 - val_loss: 1.0649 - val_acc: 0.6341
Epoch 9/10
40000/40000 [==============================] - 59s - loss: 0.8994 - acc: 0.6882 - val_loss: 1.0553 - val_acc: 0.6347
Epoch 10/10
40000/40000 [==============================] - 55s - loss: 0.8560 - acc: 0.7025 - val_loss: 1.0395 - val_acc: 0.6441

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 [ ]:
# TODO: Build a model

# TODO: Compile and train the model

Best Validation Accuracy: (fill in here)

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 [ ]:
# TODO: Load test data
    
# TODO: Preprocess data & one-hot encode the labels

# TODO: Evaluate model on test data

Test Accuracy: (fill in here)

Summary

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