Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data


In [16]:
# Load pickled data
import pickle

training_file   = "./data/train.p"
validation_file = "./data/valid.p"
testing_file    = "./data/test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test   = test['features'], test['labels']

assert len(X_train) == len(y_train)
assert len(X_valid) == len(y_valid)
assert len(X_test)  == len(y_test)

print("Data loaded!")


Data loaded!

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas


In [17]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import pandas as pd
import numpy as np

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of validation examples
n_valid = len(X_valid)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
df_labels = pd.read_csv("./signnames.csv")
n_classes = len(df_labels)

print("Number of training examples =", n_train)
print("Number of validation examples =", n_valid)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)


Number of training examples = 34799
Number of validation examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?


In [114]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import math
import matplotlib.pyplot as plt
import random
from tqdm import tqdm

# Visualizations will be shown in the notebook.
%matplotlib inline

def rgb2gray(X):
    X = np.copy(X)
    gray = np.dot(X, [0.299, 0.587, 0.114])
    gray = gray.reshape(len(X), 32, 32)
    return gray

def same(X):
    return X

def images_with_label(label, X=X_train, y=y_train):
    yi = [i for i, yy in enumerate(y) if yy == label]
    return np.array([X[i] for i in yi])

def plot_image(image, rows, cols, i, xlabel=""):
    if i > 0:
        plt.subplot(rows, cols, i)
    else:
        plt.figure(figsize=(rows, cols))
    
    plt.xticks(())
    plt.yticks(())
    plt.xlabel(xlabel, fontsize=30)
    plt.tight_layout()
    plt.imshow(image)
    
def plot_images(images, cols=5, xlabels=None):
    rows = math.ceil(len(images) / cols)
    fig = plt.figure(figsize=(rows, cols))
    fig.set_size_inches(30, 30)
    
    for i, image in enumerate(images):
        xlabel = xlabels[i] if xlabels is not None else i
        plot_image(image, rows, cols, i + 1, xlabel=xlabel)

def plot_each_label(X=X_train, y=y_train, cols=5):
    one_each = []
    for label in range(43):
        images = images_with_label(label, X, y)
        one_each.append(images[0])
    plot_images(one_each, cols)
    
def plot_label(label, count=5, cols=5, transform=same):
    images = images_with_label(label)[:count]
    plot_images(transform(images), cols)

In [125]:
def labels_dataframe(y):
    df = pd.DataFrame(data=y).iloc[:, 0].value_counts().sort_index().to_frame()
    df.rename(columns=pd.Series(["Count"]))
    return df

df_y_train = labels_dataframe(y_train)
df_y_train.plot(kind="bar", title="training label frequency", fontsize=10)

df_y_valid = labels_dataframe(y_valid)
df_y_valid.plot(kind="bar", title="validation label frequency", fontsize=10)

df_y_test = labels_dataframe(y_test)
df_y_test.plot(kind="bar", title="testing label frequency", fontsize=10)


Out[125]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f372344aa58>

In [19]:
# Plotting
plot_each_label()
# for label in range(43):
#     plot_label(label, transform=rgb2gray)



Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.


In [20]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle

X_train, y_train = shuffle(X_train, y_train)

In [21]:
# Jittering more images

import cv2

EXAMPLES_PER_LABEL = 3000

df_y_train["Needs"] = df_y_train.apply(lambda row: EXAMPLES_PER_LABEL - row[0], axis=1)

JITTER_STATS = {
    "rotate": 0,
    "translate": 0,
    "lighten": 0,
}

class Jitter(object):
    def __init__(self, images):
        self.images = np.copy(images)
        
    def jitter(self):
        image = self.random_image()
        
        method = random.choice(["rotate", "translate", "lighten"])
        JITTER_STATS[method] += 1
        return getattr(Jitter, method)(image)
        
    def random_image(self):
        return random.choice(self.images)
    
    @classmethod
    def rotate(cls, image):
        image = np.copy(image)
        h, w = image.shape[:2]
        angle = np.random.uniform(20)
        affine = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
        rotated = cv2.warpAffine(image, affine, (w, h))
        return rotated.reshape(image.shape)
    
    @classmethod
    def translate(cls, image):
        image = np.copy(image)
        h, w = image.shape[:2]
        tx = np.random.uniform(-4, 4)
        ty = np.random.uniform(-4, 4)
        affine = np.float32([[1, 0, tx], [0, 1, ty]])
        translated = cv2.warpAffine(image, affine, (w, h))
        return translated.reshape(image.shape)
    
    @classmethod
    def lighten(cls, image):
        image = np.copy(image)
        scaler = random.choice([
            0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
            2, 3, 4, 5, 6, 7, 8, 9, 10,
        ])
        image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
        image = np.array(image, dtype=np.float64)
        image[:,:,2] = image[:,:,2] * scaler
        image[:,:,2][image[:,:,2] > 255] = 255
        image = np.array(image, dtype=np.uint8)
        image = cv2.cvtColor(image, cv2.COLOR_HSV2RGB)
        return image
    
def equalize_training_data():
    new_data = {}
    for label in range(43):
        images = images_with_label(label)
        jit = Jitter(images)
        needs = df_y_train.iloc[label].Needs
        new_data[label] = [jit.jitter() for _ in range(needs)]
    return new_data

# image = X_train[5]
# jitters = [Jitter.rotate(image) for i in range(4)]
# plot_images([image] + jitters)
# raise "BOOM"

newnew = equalize_training_data()
print(JITTER_STATS)

# Plot 50 random images from newnew
flatten = np.concatenate(list(newnew.values())[:50])
plot_images([random.choice(flatten) for _ in range(50)])

print(df_y_train)

# Add newnew into X_train and y_train
X_train_3000 = np.copy(X_train)
y_train_3000 = np.copy(y_train)
for new_y, new_X in newnew.items():
    assert len(new_X) == df_y_train.iloc[new_y].Needs
    if len(new_X) == 0:
        continue
    
    add_y = np.zeros(len(new_X))
    add_y.fill(new_y)
    
    X_train_3000 = np.append(X_train_3000, new_X, axis=0)
    y_train_3000 = np.append(y_train_3000, add_y, axis=0)
    
    assert len(X_train_3000) == len(y_train_3000), "{} != {}".format(len(X_train_3000), len(y_train_3000))
    
print(len(X_train), len(y_train))
print(len(X_train_3000), len(y_train_3000))
    
assert len(X_train_3000) == 43 * EXAMPLES_PER_LABEL, "{} != {}".format(len(X_train_3000), 43 * 3000)
assert len(X_train_3000) == len(y_train_3000)


{'translate': 31160, 'lighten': 31414, 'rotate': 31627}
    Count  Needs
0     180   2820
1    1980   1020
2    2010    990
3    1260   1740
4    1770   1230
5    1650   1350
6     360   2640
7    1290   1710
8    1260   1740
9    1320   1680
10   1800   1200
11   1170   1830
12   1890   1110
13   1920   1080
14    690   2310
15    540   2460
16    360   2640
17    990   2010
18   1080   1920
19    180   2820
20    300   2700
21    270   2730
22    330   2670
23    450   2550
24    240   2760
25   1350   1650
26    540   2460
27    210   2790
28    480   2520
29    240   2760
30    390   2610
31    690   2310
32    210   2790
33    599   2401
34    360   2640
35   1080   1920
36    330   2670
37    180   2820
38   1860   1140
39    270   2730
40    300   2700
41    210   2790
42    210   2790
34799 34799
129000 129000

In [22]:
# Image Preprocessing

class PreProcessor(object):
    def __init__(self, X):
        self.X = np.copy(X)
        
    def execute(self):
        self.nada() \
            .grayscale() \
            .min_max() \
            .standardize()
        return self
    
    def nada(self):
        return self
        
    def grayscale(self):
        self.X = np.dot(self.X, [0.299, 0.587, 0.114])
        self.X = self.X.reshape(len(self.X), 32, 32, 1)
        return self
    
    def min_max(self):
        a = 0
        b = 1.0
        self.X = a + self.X * (b - a) / 255
        return self
    
    def standardize(self):
        mean = np.mean(self.X)
        std = np.std(self.X)
        self.X = (self.X - mean) / std
        return self
    
pp_train = PreProcessor(X_train_3000).execute()
pp_valid = PreProcessor(X_valid).execute()
pp_test  = PreProcessor(X_test).execute()

# count = 40
# plot_images(pp_train.X[:count].reshape(count, 32, 32))

pp_X = np.copy(pp_train.X)
n = pp_X.shape[0]
pp_X = pp_X.reshape(n, 32, 32)
plot_each_label(X=pp_X)


Model Architecture


In [111]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

import tensorflow as tf
from tensorflow.contrib.layers import flatten

PADDING = "VALID"
MU = 0
SIGMA = 0.1

def convolute(X, shape, strides=[1,1,1,1]):
    W = tf.Variable(tf.truncated_normal(shape=shape, mean=MU, stddev=SIGMA))
    b = tf.Variable(tf.zeros(shape[-1]))
    conv = tf.nn.conv2d(X, W, strides=strides, padding=PADDING) + b
    conv = tf.nn.relu(conv)
    return conv

def max_pool(X, pool_size=[1,2,2,1]):
    pooled = tf.nn.max_pool(X, ksize=pool_size, strides=pool_size, padding=PADDING)
    return pooled

def fully_connect(X, shape, relu):
    W = tf.Variable(tf.truncated_normal(shape=shape, mean=MU, stddev=SIGMA))
    b = tf.Variable(tf.zeros(shape[-1]))
    fc = tf.matmul(X, W) + b
    
    if relu:
        fc = tf.nn.relu(fc)
    return fc

def dropout(X, keep_prob):
    dropped = tf.nn.dropout(X, keep_prob)
    return dropped

def SeaNet(X, initial_depth, keep_prob):
    padding = "VALID"
    
    c1 = convolute(X, (5, 5, initial_depth, 32))       # (32 x 32 x 3) => (28 x 28 x 32)
    p1 = max_pool(c1)                                  # (28 x 28 x 32) => (14 x 14 x 32)
    c2 = convolute(p1, (5, 5, 32, 128))                # (14 x 14 x 32) => (10 x 10 x 128)
    p2 = max_pool(c2)                                  # (10 x 10 x 128) => (5 x 5 x 128)
    flat = flatten(p2)                                 # (5 x 5 x 128) => (3200)
    fc1 = fully_connect(flat, (3200, 512), relu=True)  # (3200) => (512)
    fc1 = dropout(fc1, keep_prob)
    fc2 = fully_connect(fc1, (512, 128), relu=True)    # (512) => (128)
    fc2 = dropout(fc2, keep_prob)
    fc3 = fully_connect(fc2, (128, 43), relu=False)    # (128) => (43)
    
    logits = fc3
    return logits

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.


In [31]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.


# Set up network
EPOCHS = 50
BATCH_SIZE = 256
LEARNING_RATE = 0.001


train_y = y_train_3000
valid_y = y_valid

INITIAL_DEPTH = 1
train_X = pp_train.X
valid_X = pp_valid.X

X = tf.placeholder(tf.float32, (None, 32, 32, INITIAL_DEPTH))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, 43)

logits = SeaNet(X, INITIAL_DEPTH, keep_prob)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE)
training_operation = optimizer.minimize(loss_operation)


# Set up Evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_X, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={X: batch_X, y: batch_y, keep_prob: 1.0})
        total_accuracy += (accuracy * len(batch_X))
    return total_accuracy / num_examples

print("Ready to Train! {}".format(train_X.shape))


Ready to Train! (129000, 32, 32, 1)

In [34]:
# Training
from tqdm import tqdm
import math

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(train_X)
    num_batches = int(math.ceil(len(train_X) / BATCH_SIZE))

    for i in range(EPOCHS):
        with tqdm(range(num_examples), 
                  desc="Epoch {:>2}/{}".format(i+1, EPOCHS), 
                  unit=" examples") as pbar:

            train_X, train_y = shuffle(train_X, train_y)
            for offset in range(0, num_examples, BATCH_SIZE):
                end = offset + BATCH_SIZE
                batch_X, batch_y = train_X[offset:end], train_y[offset:end]
                sess.run(training_operation, feed_dict={
                    X: batch_X, 
                    y: batch_y,
                    keep_prob: 0.5
                })

                pbar.update(min(num_examples - offset, BATCH_SIZE))

#             training_accuracy = "{:3f}".format(evaluate(train_X, train_y))
            validation_accuracy = "{:3f}".format(evaluate(valid_X, valid_y))
            pbar.set_postfix(valid_acc=validation_accuracy, train_acc=training_accuracy)
            pbar.refresh()

    saver.save(sess, "./lenet-dropped")
    print("Model saved!!!")


Epoch  1/50: 100%|██████████| 129000/129000 [00:29<00:00, 4439.51 examples/s, train_acc=0.882279, valid_acc=0.929252]
Epoch  2/50: 100%|██████████| 129000/129000 [00:29<00:00, 4400.32 examples/s, train_acc=0.952767, valid_acc=0.964853]
Epoch  3/50: 100%|██████████| 129000/129000 [00:29<00:00, 4448.08 examples/s, train_acc=0.964132, valid_acc=0.975510]
Epoch  4/50: 100%|██████████| 129000/129000 [00:29<00:00, 4400.45 examples/s, train_acc=0.973612, valid_acc=0.974603]
Epoch  5/50: 100%|██████████| 129000/129000 [00:28<00:00, 4452.07 examples/s, train_acc=0.980512, valid_acc=0.980499]
Epoch  6/50: 100%|██████████| 129000/129000 [00:29<00:00, 4398.78 examples/s, train_acc=0.986093, valid_acc=0.984354]
Epoch  7/50: 100%|██████████| 129000/129000 [00:28<00:00, 4452.18 examples/s, train_acc=0.989318, valid_acc=0.979819]
Epoch  8/50: 100%|██████████| 129000/129000 [00:29<00:00, 4402.72 examples/s, train_acc=0.990977, valid_acc=0.979592]
Epoch  9/50: 100%|██████████| 129000/129000 [00:28<00:00, 4454.44 examples/s, train_acc=0.991535, valid_acc=0.975283]
Epoch 10/50: 100%|██████████| 129000/129000 [00:29<00:00, 4397.97 examples/s, train_acc=0.991922, valid_acc=0.982086]
Epoch 11/50: 100%|██████████| 129000/129000 [00:28<00:00, 4456.04 examples/s, train_acc=0.994171, valid_acc=0.983447]
Epoch 12/50: 100%|██████████| 129000/129000 [00:29<00:00, 4403.64 examples/s, train_acc=0.995124, valid_acc=0.985488]
Epoch 13/50: 100%|██████████| 129000/129000 [00:29<00:00, 4446.77 examples/s, train_acc=0.992961, valid_acc=0.984580]
Epoch 14/50: 100%|██████████| 129000/129000 [00:29<00:00, 4403.58 examples/s, train_acc=0.995721, valid_acc=0.983447]
Epoch 15/50: 100%|██████████| 129000/129000 [00:28<00:00, 4457.36 examples/s, train_acc=0.994310, valid_acc=0.978005]
Epoch 16/50: 100%|██████████| 129000/129000 [00:29<00:00, 4404.33 examples/s, train_acc=0.996132, valid_acc=0.981633]
Epoch 17/50: 100%|██████████| 129000/129000 [00:28<00:00, 4451.15 examples/s, train_acc=0.997217, valid_acc=0.976644]
Epoch 18/50: 100%|██████████| 129000/129000 [00:29<00:00, 4402.87 examples/s, train_acc=0.995667, valid_acc=0.985034]
Epoch 19/50: 100%|██████████| 129000/129000 [00:28<00:00, 4456.45 examples/s, train_acc=0.995845, valid_acc=0.980499]
Epoch 20/50: 100%|██████████| 129000/129000 [00:29<00:00, 4400.99 examples/s, train_acc=0.997318, valid_acc=0.985714]
Epoch 21/50: 100%|██████████| 129000/129000 [00:28<00:00, 4457.58 examples/s, train_acc=0.996853, valid_acc=0.986395]
Epoch 22/50: 100%|██████████| 129000/129000 [00:29<00:00, 4406.62 examples/s, train_acc=0.997829, valid_acc=0.980045]
Epoch 23/50: 100%|██████████| 129000/129000 [00:28<00:00, 4452.30 examples/s, train_acc=0.998202, valid_acc=0.980045]
Epoch 24/50: 100%|██████████| 129000/129000 [00:29<00:00, 4394.60 examples/s, train_acc=0.997806, valid_acc=0.986848]
Epoch 25/50: 100%|██████████| 129000/129000 [00:28<00:00, 4457.87 examples/s, train_acc=0.997729, valid_acc=0.981179]
Epoch 26/50: 100%|██████████| 129000/129000 [00:29<00:00, 4406.17 examples/s, train_acc=0.996938, valid_acc=0.978005]
Epoch 27/50: 100%|██████████| 129000/129000 [00:28<00:00, 4458.38 examples/s, train_acc=0.998380, valid_acc=0.982086]
Epoch 28/50: 100%|██████████| 129000/129000 [00:29<00:00, 4403.80 examples/s, train_acc=0.998504, valid_acc=0.987755]
Epoch 29/50: 100%|██████████| 129000/129000 [00:28<00:00, 4457.08 examples/s, train_acc=0.998713, valid_acc=0.982993]
Epoch 30/50: 100%|██████████| 129000/129000 [00:29<00:00, 4402.67 examples/s, train_acc=0.996380, valid_acc=0.990023]
Epoch 31/50: 100%|██████████| 129000/129000 [00:28<00:00, 4453.18 examples/s, train_acc=0.998899, valid_acc=0.990249]
Epoch 32/50: 100%|██████████| 129000/129000 [00:29<00:00, 4401.54 examples/s, train_acc=0.998326, valid_acc=0.987755]
Epoch 33/50: 100%|██████████| 129000/129000 [00:28<00:00, 4451.61 examples/s, train_acc=0.998589, valid_acc=0.985941]
Epoch 34/50: 100%|██████████| 129000/129000 [00:29<00:00, 4396.01 examples/s, train_acc=0.998938, valid_acc=0.986621]
Epoch 35/50: 100%|██████████| 129000/129000 [00:28<00:00, 4457.41 examples/s, train_acc=0.999225, valid_acc=0.983220]
Epoch 36/50: 100%|██████████| 129000/129000 [00:29<00:00, 4404.46 examples/s, train_acc=0.999054, valid_acc=0.985714]
Epoch 37/50: 100%|██████████| 129000/129000 [00:28<00:00, 4454.00 examples/s, train_acc=0.999558, valid_acc=0.988209]
Epoch 38/50: 100%|██████████| 129000/129000 [00:29<00:00, 4402.47 examples/s, train_acc=0.998853, valid_acc=0.988889]
Epoch 39/50: 100%|██████████| 129000/129000 [00:28<00:00, 4455.64 examples/s, train_acc=0.998891, valid_acc=0.984580]
Epoch 40/50: 100%|██████████| 129000/129000 [00:29<00:00, 4405.09 examples/s, train_acc=0.997705, valid_acc=0.980045]
Epoch 41/50: 100%|██████████| 129000/129000 [00:28<00:00, 4453.84 examples/s, train_acc=0.999473, valid_acc=0.986848]
Epoch 42/50: 100%|██████████| 129000/129000 [00:29<00:00, 4405.47 examples/s, train_acc=0.998853, valid_acc=0.987755]
Epoch 43/50: 100%|██████████| 129000/129000 [00:28<00:00, 4455.35 examples/s, train_acc=0.999248, valid_acc=0.983447]
Epoch 44/50: 100%|██████████| 129000/129000 [00:29<00:00, 4401.52 examples/s, train_acc=0.999256, valid_acc=0.981179]
Epoch 45/50: 100%|██████████| 129000/129000 [00:29<00:00, 4444.31 examples/s, train_acc=0.999519, valid_acc=0.978912]
Epoch 46/50: 100%|██████████| 129000/129000 [00:29<00:00, 4407.13 examples/s, train_acc=0.999527, valid_acc=0.980726]
Epoch 47/50: 100%|██████████| 129000/129000 [00:28<00:00, 4458.18 examples/s, train_acc=0.997341, valid_acc=0.985941]
Epoch 48/50: 100%|██████████| 129000/129000 [00:29<00:00, 4407.45 examples/s, train_acc=0.998953, valid_acc=0.988662]
Epoch 49/50: 100%|██████████| 129000/129000 [00:28<00:00, 4458.11 examples/s, train_acc=0.999248, valid_acc=0.986168]
Epoch 50/50: 100%|██████████| 129000/129000 [00:29<00:00, 4407.76 examples/s, train_acc=0.999481, valid_acc=0.985034]
Model saved!!!

In [44]:
# Evaluation
with tf.Session() as sess:
#     saver.restore(sess, tf.train.latest_checkpoint(".", latest_filename="./lenet-dropped"))
    saver.restore(sess, "./lenet-dropped")
    
    test_accuracy = evaluate(pp_test.X, y_test)
    print("Test Accuracy: {:.3f}".format(test_accuracy))


Test Accuracy: 0.972

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images


In [83]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.

import matplotlib.image as mpimg

filenames = [
    "./resources/s-01.jpg",
    "./resources/s-03.jpg",
    "./resources/s-04.jpg",
    "./resources/s-25.jpg",
    "./resources/s-27.jpg",
#     "./resources/s-99.jpg",
]

def read_image(filename):
    i = mpimg.imread(filename)
    if i.shape[-1] == 4:
        i = i[:, :, :-1]
    return i

X_new = np.array([read_image(f) for f in filenames])
print(X_new.shape)
plot_images(X_new)

y_new = [
    1,
    3,
    4,
    25,
    27,
#     99
]


(5, 32, 32, 3)

Predict the Sign Type for Each Image


In [97]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

pp_new = PreProcessor(X_new).execute()

with tf.Session() as sess:
    saver.restore(sess, "./lenet-dropped")
    predictions = sess.run(logits, feed_dict={X: pp_new.X, keep_prob: 1.0})
    
errors = 0
for i, p in enumerate(predictions):
    print("expected label {}, got label {}".format(y_new[i], np.argmax(p)))
    if np.argmax(p) != y_new[i]:
        errors += 1
        
print("correct:", len(predictions) - errors)


expected label 1, got label 1
expected label 3, got label 3
expected label 4, got label 4
expected label 25, got label 25
expected label 27, got label 11
correct: 4

Analyze Performance


In [98]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

print("Accuracy: {}%".format(100 * float(len(predictions) - errors) / len(predictions)))


Accuracy: 80.0%

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.


In [128]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.


with tf.Session() as sess:
    saver.restore(sess, "./lenet-dropped")
    softmax_values = sess.run(tf.nn.softmax(logits), feed_dict={X: pp_new.X, keep_prob: 1.0})


for i, sm in enumerate(softmax_values):
    top_k = tf.nn.top_k(sm, k=5)
    labels = top_k.indices.eval(session=tf.Session())
    values = top_k.values.eval(session=tf.Session())
    
    df = pd.DataFrame({
        "Labels": labels, 
        "Probabilities": ["{:3.2f}".format(100.0 * v) for v in values]
    })
    print("Image: {}".format(filenames[i]))
    print(df)
    print()


Image: ./resources/s-01.jpg
   Labels Probabilities
0       1         99.95
1       4          0.05
2       5          0.00
3       2          0.00
4       0          0.00

Image: ./resources/s-03.jpg
   Labels Probabilities
0       3        100.00
1       5          0.00
2       2          0.00
3       9          0.00
4      28          0.00

Image: ./resources/s-04.jpg
   Labels Probabilities
0       4        100.00
1       1          0.00
2       2          0.00
3       5          0.00
4      15          0.00

Image: ./resources/s-25.jpg
   Labels Probabilities
0      25        100.00
1      22          0.00
2      24          0.00
3      29          0.00
4      20          0.00

Image: ./resources/s-27.jpg
   Labels Probabilities
0      11         99.99
1      27          0.01
2      30          0.00
3      25          0.00
4      18          0.00

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Your output should look something like this (above)


In [ ]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")