I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
19. 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.
Can you write Python code for it?

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

import matplotlib.gridspec as gridspec

with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    softmax_prob = sess.run(tf.nn.top_k(probabilities,k = 5), feed_dict={x: X_web, keep_prob: 1.0})

signnames = pd.read_csv('signnames.csv')

for i in range(len(test_images)):
    plt.figure(figsize = (6,2))
    gs = gridspec.GridSpec(1, 2,width_ratios=[2,3])
    plt.subplot(gs[0])
    plt.imshow(X_web[i].squeeze(),cmap="gray")
    plt.axis('off')
    plt.subplot(gs[1])
    plt.barh(6-np.arange(5),softmax_prob[0][i], align='center')

    if logits_web[i] != y_web[i]:
        color_str = 'red'
    else:
        color_str = 'green'

    for i_label in range(5):
        temp_string = "%.1f %% : %s" % (softmax_prob[0][i][i_label]*100, str(signnames.iloc[softmax_prob[1][i][i_label], 1]))
        plt.text(softmax_prob[0][i][0]*1.1,6-i_label-.15, temp_string, color = color_str)
    plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
5. Show a sample of the augmented dataset
Can you write Python code for it?

# Visualization
show_training_dataset_histogram(y_train,y_valid,y_test)
show_sample(X_train, y_train, histogram = 0, sample_num = 8, sample_index = 35000)


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
6. Pre-process functions
Can you write Python code for it?

import cv2
from numpy import newaxis

def equalize_Y_histogram(features):
    images = []
    for image in features:

        # Convert RGB to YUV
        temp = cv2.cvtColor(image, cv2.COLOR_BGR2YUV);

        # Equalize Y histogram in order to get better contrast accross the dataset
        temp[:,:,0] = cv2.equalizeHist(temp[:,:,0])

        # Convert back YUV to RGB
        temp = cv2.cvtColor(temp, cv2.COLOR_YUV2BGR)

        images.append(temp)

    return np.array(images)

def CLAHE_contrast_normalization(features):
    images = []
    for image in features:

        # create a CLAHE object
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4))
        temp = clahe.apply(image)

        images.append(temp)

    return np.array(images)

def convert_to_grayscale(features):
    gray_images = []
    for image in features:

        # Convert RGB to grayscale
        temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        gray_images.append(temp)

    return np.array(gray_images)

def normalize_grayscale(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
    """
    a = 0.1
    b = 0.9

    image_data_norm = a + ((image_data - np.amin(image_data))*(b-a))/(np.amax(image_data) - np.amin(image_data))

    return image_data_norm


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
7. Show a sample of the preprocess functions outputs
Can you write Python code for it?

index = 255

X_temp1 = convert_to_grayscale(X_train)
X_temp2 = CLAHE_contrast_normalization(X_temp1)
X_temp3 = normalize_grayscale(X_temp2)

show_sample(X_train, y_train, histogram = 1, sample_num = 1, sample_index = index)
show_sample(X_temp1, y_train, histogram = 1, sample_num = 1, sample_index = index, color_map ='gray')
show_sample(X_temp2, y_train, histogram = 1, sample_num = 1, sample_index = index, color_map ='gray')
print(X_temp2[index])
print(X_temp3[index])


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
8. Preprocess the Dataset
Can you write Python code for it?

#Preprocessing pipeline
print('Preprocessing training features...')
X_train = convert_to_grayscale(X_train)
X_train = CLAHE_contrast_normalization(X_train)
X_train = normalize_grayscale(X_train)
X_train = X_train[..., newaxis]

print("Processed shape =", X_train.shape)

print('Preprocessing validation features...')
X_valid = convert_to_grayscale(X_valid)
X_valid = CLAHE_contrast_normalization(X_valid)
X_valid = normalize_grayscale(X_valid)
X_valid = X_valid[..., newaxis]

print("Processed shape =", X_valid.shape)

print('Preprocessing test features...')
X_test = convert_to_grayscale(X_test)
X_test = CLAHE_contrast_normalization(X_test)
X_test = normalize_grayscale(X_test)
X_test = X_test[..., newaxis]

print("Processed shape =", X_test.shape)

# Shuffle the training dataset
X_train, y_train = shuffle(X_train, y_train)

print("Pre-processing done!")


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
Analyze Performance
Can you write Python code for it?

### 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.
with tf.Session() as sess:
    saver.restore(sess, "./lenet")
    pred = sess.run(logits, feed_dict={x: img, keep_prob: 1.0})

signnames = []
signnames_file = "signnames.csv"
with open(signnames_file) as f:
    rows = csv.reader(f, delimiter=',')
    next(rows, None)
    for i, r in enumerate(rows):
        assert(i == int(r[0]))
        signnames.append(r[1])

num_correct = 0
for p, i in zip(pred, range(len(pred))):
    actual = correct_labels[i]
    predicted = np.argmax(p)
    actual_sign = signnames[actual]
    pred_sign = signnames[predicted]
    print("Actual: {} ({}), Predicted: {} ({})".format(actual, actual_sign, predicted, pred_sign))
    if predicted == actual:
        num_correct += 1

print('Correct:', num_correct)

with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     saver_test = tf.train.import_meta_graph('./lenet.meta')
    saver.restore(sess, "./lenet")
    acc = evaluate(img, correct_labels)
    print("Accuracy: {:.3f}".format(acc))


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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?
Can you write Python code for it?

### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import numpy as np
# Visualizations will be shown in the notebook.
%matplotlib inline

# Define a function to display image
def display_image_per_class(X_train, y_train):
    # Get the classes and counts of each class
    unique_classes, idx, counts = np.unique(y_train, return_index=True, return_counts=True)
    plt.figure(figsize=(20,20))
    i = 1
    # For each unique class in dataset, display an image and number of occurances of that class
    for sign_class in unique_classes:
        image = X_train[idx[i-1]]
        plt.subplot(8,8,i)
        plt.axis('off')
        plt.title("Class {0} ({1})".format(sign_class, counts[i-1]))
        i = i + 1
        plt.imshow(image)
    plt.show()
    return

display_image_per_class(X_train, y_train)

# Define a function to display distribution
def display_class_dist(y_train, n_classes):
    plt.figure(figsize=(20,5))
    plt.xlabel("Class")
    plt.ylabel("Frequency")
    plt.hist(y_train, bins=n_classes-1)
    plt.show()

display_class_dist(y_train, n_classes)


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
Model Architecture
Can you write Python code for it?

### Define your architecture here.
### Feel free to use as many code cells as needed.
from tensorflow.contrib.layers import flatten
import tensorflow as tf

# params
EPOCHS = 30
BATCH_SIZE = 128
mu = 0
sigma = 0.010
dropout_prob = 0.70
rate = 0.002

# Layer 1 from original LeNet
def LeNet_Layer1(x, mu, sigma):
    # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(6))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

    # Activation.
    conv1 = tf.nn.relu(conv1)

    # Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    return conv1

# Layer 2 from original LeNet
def LeNet_Layer2(x, mu, sigma):
    # Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(16))
    conv2   = tf.nn.conv2d(x, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b

    # Activation.
    conv2 = tf.nn.relu(conv2)

    # Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)

    return fc0

# Layer 3 from original LeNet
def LeNet_Layer3(x, mu, sigma):
    # Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1   = tf.matmul(x, fc1_W) + fc1_b

    # Activation.
    fc1    = tf.nn.relu(fc1)

    return fc1

# Layer 4 from original LeNet
def LeNet_Layer4(x, mu, sigma):
    # Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  =...


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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.
Can you write Python code for it?

### 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')
    prob = tf.nn.softmax(logits)
    soft_pred = sess.run(prob, feed_dict={x: img, keep_prob: 1.0})
    topK = sess.run(tf.nn.top_k(tf.constant(soft_pred), k=5))

print("Values:", topK[0])
print("Indices:", topK[1])


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
Predict the Sign Type for Each Image
Can you write Python code for it?

### 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.
print("images after normalization, grayscale, and histogram equalization:")

img = process_img(img)
img = np.asarray(img)
print(img.shape)

for i in range(0, 5):
    this_img = img[i, :, :, 0]
    plt.figure(i, figsize = (5, 5))
    plt.imshow(this_img, cmap='gray')


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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...
Can you write Python code for it?

### 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,:,:,...


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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
Can you write Python code for it?

### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results

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

# TODO: Number of validation examples
n_validation = 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.
n_classes = len(set(y_train))

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


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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.
4. Augment the Data Set
Can you write Python code for it?

import cv2
from tqdm import tqdm
from sklearn.utils import shuffle

def random_transform_image(dataset, index):

    # Hyperparameters
    # Values inspired from Pierre Sermanet and Yann LeCun Paper : Traffic Sign Recognition with Multi-Scale Convolutional Networks
    Scale_change_max = 0.1
    Translation_max  =  2  #pixels
    Rotation_max     = 15  #degrees
    Brightness_max   = 0.1

    # Generate random transformation values
    trans_x = np.random.uniform(-Translation_max,Translation_max)
    trans_y = np.random.uniform(-Translation_max,Translation_max)
    angle   = np.random.uniform(-Rotation_max,Rotation_max)
    scale   = np.random.uniform(1-Scale_change_max,1+Scale_change_max)
    bright  = np.random.uniform(-Brightness_max,Brightness_max)

    #Brightness
    #create white image
    white_img = 255*np.ones((32,32,3), np.uint8)
    black_img = np.zeros((32,32,3), np.uint8)

    if bright >= 0:
        img = cv2.addWeighted(dataset[index].squeeze(),1-bright,white_img,bright,0)
    else:
        img = cv2.addWeighted(dataset[index].squeeze(),bright+1,black_img,bright*-1,0)

    # Scale
    img = cv2.resize(img,None,fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)

    # Get image shape afeter scaling
    rows,cols,chan = img.shape

    # Pad with zeroes before rotation if image shape is less than 32*32*3
    if rows < 32:
        offset = int((32-img.shape[0])/2)
        # If shape is an even number
        if img.shape[0] %2 == 0:
            img = cv2.copyMakeBorder(img,offset,offset,offset,offset,cv2.BORDER_CONSTANT,value=[0,0,0])
        else:
            img = cv2.copyMakeBorder(img,offset,offset+1,offset+1,offset,cv2.BORDER_CONSTANT,value=[0,0,0])

    # Update image shape after padding
    rows,cols,chan = img.shape

    # Rotate
    M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
    img = cv2.warpAffine(img,M,(cols,rows))

    # Translation
    M = np.float32([[1,0,trans_x],[0,1,trans_y]])
    img = cv2.warpAffine(img,M,(cols,rows))

    # Crop...


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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
Can you write Python code for it?

### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
%matplotlib inline

folder = 'new-images/'

print("input images:")

img = []

correct_labels = [17, 3, 13, 33, 23]

for i in range(0, 5):
    plt.figure(i, figsize = (5, 5))
    imgnum = str(i + 1)
    img.append(plt.imread(folder + imgnum + '.png'))
    plt.imshow(img[i])


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_Classifier.ipynb".
The first task is:
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.
Can you write Python code for it?

### 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.
from sklearn.utils import shuffle

tf.reset_default_graph()

x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 43)
keep_prob = tf.placeholder(tf.float32) # dropout
IS_TRAIN_PHASE = tf.placeholder(dtype=tf.bool, name='is_train_phase')

logits = LeNet_mod(x, mu, sigma)

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
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

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)

    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout_prob})

        validation_accuracy =...


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
11. Features and Labels
x is a placeholder for a batch of input images.
y is a placeholder for a batch of output labels.
Can you write Python code for it?

#Declare placeholder tensors
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, n_classes)


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
12. Training Pipeline
Create a training pipeline that uses the model to classify German Traffic Sign Benchmarks data.
Can you write Python code for it?

logits = model(x, keep_prob)
probabilities = tf.nn.softmax(logits)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
13. Model Evaluation
Evaluate how well the loss and accuracy of the model for a given dataset.
Can you write Python code for it?

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


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
17. Predict the Sign Type for Each Image
Can you write Python code for it?

### 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.
import tensorflow as tf

# hardcoded..
y_web = [9,22,2,18,1,17,4,10,38,4,4,23]

#We have to set the keep probability to 1.0 in the model..
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    logits_web = sess.run(tf.argmax(logits,1), feed_dict={x: X_web, keep_prob: 1.0})

print("Prediction =", logits_web)

# show_sample(X_web, logits_web, histogram = 0, sample_num = len(test_images), sample_index = 0, color_map = 'gray')

#Number of column to show
sample_num = len(test_images)
col_num = 4

if sample_num%col_num == 0:
    row_num = int(sample_num/col_num)
else:
    row_num = int(sample_num/col_num)+1

#Create training sample plot
f, axarr = plt.subplots(row_num, col_num, figsize=(col_num*4,(row_num+1)*2))

signnames = pd.read_csv('signnames.csv')

for i in range(0, sample_num, 1):
    image = X_web[i].squeeze()

    if logits_web[i] != y_web[i]:
        color_str = 'red'
    else:
        color_str = 'green'

    title_str = 'Predicted : %s \n Real: %s' % (signnames.iloc[logits_web[i], 1],signnames.iloc[y_web[i], 1])

    axarr[int(i/col_num),i%col_num].set_title(title_str, color = color_str)
    axarr[int(i/col_num),i%col_num].imshow(image,'gray')
    axarr[int(i/col_num),i%col_num].axis('off')
    axarr[int(i/col_num),i%col_num].axis('off')
    axarr[int(i/col_num),i%col_num].axis('off')

f.tight_layout()
plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
18. Analyze Performance
Can you write Python code for it?

### Calculate the accuracy for these 5 new images.
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    test_accuracy = evaluate(X_web, y_web)
    print("Web images Accuracy = {:.3f}".format(test_accuracy))


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
19. 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.
Can you write Python code for it?

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

import matplotlib.gridspec as gridspec

with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    softmax_prob = sess.run(tf.nn.top_k(probabilities,k = 5), feed_dict={x: X_web, keep_prob: 1.0})

signnames = pd.read_csv('signnames.csv')

for i in range(len(test_images)):
    plt.figure(figsize = (6,2))
    gs = gridspec.GridSpec(1, 2,width_ratios=[2,3])
    plt.subplot(gs[0])
    plt.imshow(X_web[i].squeeze(),cmap="gray")
    plt.axis('off')
    plt.subplot(gs[1])
    plt.barh(6-np.arange(5),softmax_prob[0][i], align='center')

    if logits_web[i] != y_web[i]:
        color_str = 'red'
    else:
        color_str = 'green'

    for i_label in range(5):
        temp_string = "%.1f %% : %s" % (softmax_prob[0][i][i_label]*100, str(signnames.iloc[softmax_prob[1][i][i_label], 1]))
        plt.text(softmax_prob[0][i][0]*1.1,6-i_label-.15, temp_string, color = color_str)
    plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
6. Pre-process functions
Can you write Python code for it?

import cv2
from numpy import newaxis

def equalize_Y_histogram(features):
    images = []
    for image in features:

        # Convert RGB to YUV
        temp = cv2.cvtColor(image, cv2.COLOR_BGR2YUV);

        # Equalize Y histogram in order to get better contrast accross the dataset
        temp[:,:,0] = cv2.equalizeHist(temp[:,:,0])

        # Convert back YUV to RGB
        temp = cv2.cvtColor(temp, cv2.COLOR_YUV2BGR)

        images.append(temp)

    return np.array(images)

def CLAHE_contrast_normalization(features):
    images = []
    for image in features:

        # create a CLAHE object
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4))
        temp = clahe.apply(image)

        images.append(temp)

    return np.array(images)

def convert_to_grayscale(features):
    gray_images = []
    for image in features:

        # Convert RGB to grayscale
        temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        gray_images.append(temp)

    return np.array(gray_images)

def normalize_grayscale(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
    """
    a = 0.1
    b = 0.9

    image_data_norm = a + ((image_data - np.amin(image_data))*(b-a))/(np.amax(image_data) - np.amin(image_data))

    return image_data_norm


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
9. Model Architecture

| Layer         |     Description                               |  Input            |  Output                     |
|:-------------:|:---------------------------------------------:|:-----------------:|:---------------------------:|
| Input         | 32x32x1 Grayscale image                       | Image             | Convolution 1               |
| Convolution 1 | 1x1 stride, valid padding, outputs 28x28x100  | Input             | RELU                        |
| RELU 1        |                                               | Convolution 1     | Max Pooling 1               |
| Max pooling 1 | 2x2 stride,  outputs 14x14x100                | RELU 1            | Convolution 2, Max Pooling 3|
| Convolution 2 | 1x1 stride, valid padding, outputs 10x10x200  | Max pooling 1     | RELU 2                      |
| RELU 2        |                                               | Convolution 2     | Max pooling 2               |
| Max pooling 2 | 2x2 stride,  outputs 5x5x200                  | RELU 2            | Flatten 2                   |
| Max pooling 3 | 2x2 stride,  outputs 7x7x100                  | Max pooling 1     | Flatten 1                   |
| Flatten 1     | Input = 7x7x100, Output = 4900                | Max pooling 3     | Concatenate 1               |
| Flatten 2     | Input = 5x5x200, Output = 5000                | Max pooling 2     | Concatenate 1               |
| Concatenate 1 | Input1 = 4900, Input1 = 5000, Output = 9900   | Max pooling 2 and 3 |Fully connected            |
| Fully connected | Fully Connected. Input = 9900, Output = 100 | Concatenate 1     | Dropout                     |
| Dropout       | Keep prob = 0.75                           | Fully connected   | Softmax                     |
| Softmax       | Fully Connected. Input = 100, Output = 43     | Dropout           | Probabilities               |
Can you write Python code for it?

import tensorflow as tf

from tensorflow.contrib.layers import flatten

def model(x, keep_prob):
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1

    # Network Parameters
    n_classes = 10  # MNIST total classes (0-9 digits)
    filter_size = 5

    # Store layers weight & bias
    weights = {
        'wc1' : tf.Variable(tf.truncated_normal([filter_size, filter_size, 1, 100], mean = mu, stddev = sigma)),
        'wc2' : tf.Variable(tf.truncated_normal([filter_size, filter_size, 100, 200], mean = mu, stddev = sigma)),
        'wfc1': tf.Variable(tf.truncated_normal([9900, 100], mean = mu, stddev = sigma)),
        'out' : tf.Variable(tf.truncated_normal([100, n_classes], mean = mu, stddev = sigma))}

    biases = {
        'bc1' : tf.Variable(tf.zeros([100])),
        'bc2' : tf.Variable(tf.zeros([200])),
        'bfc1': tf.Variable(tf.zeros([100])),
        'out' : tf.Variable(tf.zeros([n_classes]))}

    def conv2d(x, W, b, strides=1., padding='SAME'):
        x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)
        x = tf.nn.bias_add(x, b)
        return tf.nn.relu(x)

    def maxpool2d(x, k=2, padding='SAME'):
        return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding=padding)

    # Layer 1: Convolution 1 - 32*32*1 to 28*28*100
    conv1 = conv2d(x, weights['wc1'], biases['bc1'], padding='VALID')
    # Max Pool - 28*28*100 to 14*14*100
    conv1 = maxpool2d(conv1, k=2)

    # Layer 2: Convolution 2 - 14*14*100 to 10*10*200
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'], padding='VALID')
    # Max Pool - 10*10*200 to 5*5*200
    conv2 = maxpool2d(conv2, k=2)

    #Fork second max pool - 14*14*100 to 7*7*100
    conv1 = maxpool2d(conv1, k=2)

    #Flatten conv1. Input = 7*7*100, Output = 4900
    conv1 = tf.contrib.layers.flatten(conv1)

    # Flatten conv2. Input = 5x5x200. Output = 5000.
    conv2 = tf.contrib.layers.flatten(conv2)
 ...


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
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.
2. Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas
Can you write Python code for it?

### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results

import numpy as np

# Number of training examples
n_train = len(X_train)

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

# Number of validation examples
n_valid = len(X_valid)

# 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.
n_classes = np.unique(y_train).size

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)


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
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.
4. Augment the Data Set
Can you write Python code for it?


I am working on the file "CarND-Traffic-Sign-Classifier-P2/Traffic_Sign_ClassifierCIfar10.ipynb".
The first task is:
Step 4: 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...
Can you write Python code for it?

### 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 maybe 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,:,:,...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Question 1
Describe how you preprocessed the data. Why did you choose that technique?
Answer:
1) Convert RGB to Gray and in order to make model insensitive to color variations
2) Apply histogram equalization to mitigate the influence caused by illumination changes.
3) Data normalization to make the problem well conditioned, which is helpful to initialization and learning convergence.
Uncorrect augmented data results in worse performance.
The uncorrect augmentation generates images with black border which cut the performance.
The correct data augmentation should like this https://github.com/navoshta/traffic-signs/blob/master/Traffic_Signs_Recognition.ipynb .
Can you write Python code for it?

### Generate additional data (OPTIONAL!).
### and split the data into training/validation/testing sets here.
### Feel free to use as many code cells as needed.

# data split with shuffle
# from sklearn.model_selection import train_test_split
# import os
# X_tr_val,  X_ts,  y_tr_val,  y_ts = train_test_split(
#     X_gray,
#     y,
#     test_size=0.1,
#     random_state=832289)
# X_tr,  X_val,  y_tr,  y_val = train_test_split(
#     X_tr_val,
#     y_tr_val,
#     test_size=0.1,
#     random_state=832289)

# print('Training features and labels randomized and split.')

# ### Generate additional data (OPTIONAL!)
# def augment_brightness_camera_images(image):
#     image1 = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
#     random_bright = .25+np.random.uniform()
#     #print(random_bright)
#     image1[:,:,2] = image1[:,:,2]*random_bright
#     image1 = cv2.cvtColor(image1,cv2.COLOR_HSV2RGB)
#     return image1

# def transform_image(img,ang_range,shear_range,trans_range,brightness=0):
#     '''
#     This function transforms images to generate new images.
#     The function takes in following arguments,
#     1- Image
#     2- ang_range: Range of angles for rotation
#     3- shear_range: Range of values to apply affine transform to
#     4- trans_range: Range of values to apply translations over.

#     A Random uniform distribution is used to generate different parameters for transformation
#     '''
#     # Rotation
#     ang_rot = np.random.uniform(ang_range)-ang_range/2
#     rows,cols,ch = img.shape
#     Rot_M = cv2.getRotationMatrix2D((cols/2,rows/2),ang_rot,1)
#     # Translation
#     tr_x = trans_range*np.random.uniform()-trans_range/2
#     tr_y = trans_range*np.random.uniform()-trans_range/2
#     Trans_M = np.float32([[1,0,tr_x],[0,1,tr_y]])
#     # Shear
#     pts1 = np.float32([[5,5],[20,5],[5,20]])
#     pt1 = 5+shear_range*np.random.uniform()-shear_range/2
#     pt2 = 20+shear_range*np.random.uniform()-shear_range/2
#     # Brightness
#     pts2 = np.float32([[pt1,5],[pt2,pt1],[5,pt2]])
#    ...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Question 2
Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?
Answer:
1) I first shuffle the dataset, and divid the dataset in to 1/10 for testing stage data and 9/10 for training stage data. Then, during traing stage, I again divide the training stage data into 1/10 for validation and 9/10 for training.
2) I use Rotation, Translation, Shear operations to generate data, since the data are very unbalanced among different classes. In the new dataset, each class has at least 1205 images.
Can you write Python code for it?

### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf
from tensorflow.contrib.layers import flatten

def LeNet(x):
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1

    # TODO: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma), name='conv1_W')    # the filters' weights
    conv1_b = tf.Variable(tf.zeros(6), name='conv1_b')    # the filters' biases
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

    # TODO: Activation.
    conv1 = tf.nn.relu(conv1)

    # TODO: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, [1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # TODO: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma), name='conv2_W')    # the filters' weights
    conv2_b = tf.Variable(tf.zeros(16), name='conv2_b')    # the filters' biases
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b

    # TODO: Activation.
    conv2 = tf.nn.relu(conv2)

    # TODO: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2= tf.nn.max_pool(conv2, [1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # TODO: Flatten. Input = 5x5x16. Output = 400.
    fc0 = flatten(conv2)

    # TODO: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma), name='fc1_W')
    fc1_b = tf.Variable(tf.zeros(120), name='fc1_b')
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b

    # TODO: Activation.
    fc1 = tf.nn.relu(fc1)

    # TODO: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma), name='fc2_W')
   ...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Question 4
How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)
Answer:
I use Adam optimizer, and the hyperparameters are set as following,
    EPOCHS = 50
    BATCH_SIZE = 128
    rate = 0.001
Question 5
What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.
Answer:
5 steps:
1) Data preprocessing: RGB-->GRAY (color insensitive), Illumination equalization (illumination robust), Data augmentation (mitigate data inbalanced)
2) CNN model choose: LeNet containing 5 layers (simple and efficient)
3) Optimizer choose: Adam, simple and efficient with less hyperparameters
4) mini-batch training with many epoches, and validation
5) Testing

Step 3: Test a Model on New Images
Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
Implementation
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
Can you write Python code for it?

### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
rootDir = './sign-imgs'
img_num = len(os.listdir(rootDir))
X_web = np.array([])
y_web = np.array([])
for idx, file in enumerate(os.listdir(rootDir)):
        path = os.path.join(rootDir, file)
        img = cv2.imread(path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    # opencv's imread return BGR, but here is RGB
        gray = cv2.resize(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), (32, 32))
        gray = cv2.equalizeHist(gray)    # equalize the histogram
        gray = (gray-128)/128 # normalization
        label = file.split('.')[0]
        if idx==0:
            X_web = gray.reshape(1, 32, 32, 1)
            y_web = np.array([int(label)])
        else:
            X_web = np.append(X_web, gray.reshape(1, 32, 32, 1), axis=0)
            y_web = np.append(y_web, [int(label)])
        plt.subplot(1, img_num, idx+1)
        plt.imshow(img)
        plt.title('label:' + label)
        plt.axis('off')
plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Question 6
Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.
Answer:
The fifth image suffers a serious distorition which makes classification difficult.
Can you write Python code for it?

### Run the predictions here.
### Feel free to use as many code cells as needed.
saver = tf.train.Saver()
with tf.Session(config=config) as sess:
    saver.restore(sess, './lenet2')
    y_perd = sess.run(predict_operation, feed_dict={x: X_web, y: y_web})
    print(y_perd)


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Question 7
Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.
NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.
Answer:
The accuracy on captured pictures is 40%, which is lower than 77%, the accuracy on the testing dataset. Since here are only 5 captured traffic sign images, the result is not so convinced in statistics.
Can you write Python code for it?

### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
saver = tf.train.Saver()
with tf.Session(config=config) as sess:
    saver.restore(sess, './lenet2')
    softmax_prob = sess.run(softmax_operation, feed_dict={x: X_web, y: y_web})
    topk = sess.run(tf.nn.top_k(softmax_prob, k=5))
    plt.figure(figsize=(20,10))
    n_classes = len(softmax_prob[0])
    for i in range(len(softmax_prob)):
        plt.subplot(len(softmax_prob), 1, i+1)
#         plt.hist(softmax_prob[i], bins=n_classes)
        plt.bar(np.arange(n_classes), softmax_prob[i])
        plt.title('GT: ' + str(y_web[i]))
        plt.grid(True)
        plt.tight_layout()
        print('topk-values:' + str(topk.values[i]) + '            topk-indices:' + str(topk.indices[i]))
    plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
Save Checkpoint
Can you write Python code for it?

# Save the data for easy access
pickle_file = 'sign.pickle'
if not os.path.isfile(pickle_file):
    print('Saving data to pickle file...')
    try:
        with open('sign.pickle', 'wb') as pfile:
            pickle.dump(
                {
                    'train_dataset': X_tr,
                    'train_labels': y_tr,
                    'valid_dataset': X_val,
                    'valid_labels': y_val,
                    'test_dataset': X_ts,
                    'test_labels': y_ts,
                },
                pfile, pickle.HIGHEST_PROTOCOL)
    except Exception as e:
        print('Unable to save data to', pickle_file, ':', e)
        raise

print('Data cached in pickle file.')


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
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 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.
Can you write Python code for it?

### Replace each question mark with the appropriate value.
import numpy as np
# TODO: Number of training examples
n_train = len(y_train)

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

# TODO: What's the shape of an traffic sign image?
image_shape = X_test.shape[1:3]

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_test))

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


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
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.
There are various aspects to consider when thinking about this problem:

Neural network architecture
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.
NOTE: 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!
Implementation
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
Can you write Python code for it?

### Preprocess the data here.
from tqdm import tqdm
import cv2
X = np.concatenate((X_train, X_test), axis=0)
y = np.concatenate((y_train, y_test), axis=0)

# convert RGB to Gray, apply histogram equalization, data normalization
X_gray = np.array([])
# Progress bar
batches_pbar = tqdm(range(len(y)), desc='Percent ', unit='images')

for i in batches_pbar:
    img = X[i]
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)    # opencv's imread return BGR, but here is RGB
    gray = cv2.equalizeHist(gray)    # equalize the histogram
    gray = (gray-128)/128 # normalization
    gray = gray.reshape(1,32,32,1)
    if i==0:
        X_gray = gray
    else:
        X_gray = np.append(X_gray, gray, axis=0)

print(X_gray.shape)


I am working on the file "CarND-Traffic-Sign-Classifier-Project/Traffic_Sign_Classifier.ipynb".
The first task is:
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.
Can you write Python code for it?

### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
plt.figure()
for i in range(0, n_classes):
    plt.subplot(5, 9, i+1)
    idx = [y_test == i]
    img = X_test[idx][0]
    plt.imshow(img)
    plt.title(str(i))
    plt.axis('off')
plt.show()


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Convolutions

Re-construct the previous network
Add a convolutional layer with 32 filters, a 3x3 kernel, and valid padding before the flatten layer.
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.
Can you write Python code for it?

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

# 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,...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Dropout

Re-construct the network
Add a dropout layer after the pooling layer. Set the dropout rate to 50%.
Can you write Python code for it?

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

# 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" %...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Keras Sequential Model
```python
from keras.models import Sequential
Create the Sequential model
model = Sequential()
``
Thekeras.models.Sequentialclass is a wrapper for the neural network model. Just like many of the class models in scikit-learn, it provides common functions likefit(),evaluate(), andcompile()`.  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:
```python
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.

Set the first layer to a Flatten layer with the input_shape set to (32, 32, 3)
Set the second layer to Dense layer width to 128 output.
Use a ReLU activation function after the second layer.
Set the output layer width to 43, since there are 43 classes in the...
Can you write Python code for it?

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

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


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Normalize the features
Hint: You solved this in TensorFlow lab Problem 1.
Can you write Python code for it?

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

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


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
One-Hot Encode the labels
Hint: You can use the scikit-learn LabelBinarizer function to one-hot encode the labels.
Can you write Python code for it?

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

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


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
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?
Can you write Python code for it?

# TODO: Build a model

# TODO: Compile and train the model


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Pooling

Re-construct the network
Add a 2x2 max pooling layer immediately following your convolutional layer. (NO! max_pooling layer should follows the activation layer)
Can you write Python code for it?

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

# 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" %...


I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Preprocess the Data

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

Shuffle the data
Hint: You can use the scikit-learn shuffle function to shuffle the data.
Can you write Python code for it?

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

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


I am working on the file "CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb".
The first task is:
3. Print a dataset summary
This cell:
* Prints a summary of the dataset
Can you write Python code for it?

import matplotlib.image as mpimg
%matplotlib inline

if display_output == 1:
    # Load the 1rst image to get its size
    train_img = mpimg.imread(X_train[0])

    # Dataset image shape
    image_shape = train_img.shape

    # Number of unique classes/labels there are in the dataset.
    n_classes = np.unique(y_train).size

    print("Number of training examples =", X_train.shape[0])
    print("Number of validation examples =", X_valid.shape[0])
    print("Image data shape =", image_shape)
    print("Number of classes =", n_classes)


I am working on the file "CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb".
The first task is:
4. Exploratory visualization of the dataset
This cell:
* Defines the show_dataset_classes_histogram function
* Defines the show_sample() function
* Shows an hstogram distribution of the dataset classes
* Shows a random sample of the dataset
Can you write Python code for it?

import matplotlib.pyplot as plt
import random

def show_dataset_classes_histogram(labels_train, labels_valid):
    f, ax = plt.subplots(figsize=(5, 5))

    # Generate histogram and bins
    hist_train, bins = np.histogram(labels_train, 2)
    hist_valid, bins = np.histogram(labels_valid, 2)

    # Bar width
    width = 1.0 * (bins[1] - bins[0])

    ax.bar([-1, 1], hist_train, width=width, label="Train")
    ax.bar([-1, 1], hist_valid, width=width, label="Valid")

    ax.set_xlabel('Classes')
    ax.set_ylabel('Number of occurence')
    ax.set_title('Histogram of the data set')

    ax.legend(bbox_to_anchor=(1.01, 1), loc="upper left")
    f.tight_layout()

    plt.savefig("./output_images/histogram_dataset.png")

def show_sample(features, labels, preprocess=0, sample_num=1, sample_index=-1):
    col_num = 2
    # Create training sample + histogram plot
    f, axarr = plt.subplots(sample_num, col_num, figsize=(col_num * 4, sample_num * 3))

    index = sample_index - 1
    for i in range(0, sample_num, 1):

        if sample_index == -1:
            index = random.randint(0, len(features))
        else:
            index = index + 1

        if labels[index] == 1:
            label_str = "Car"
        else:
            label_str = "Non-Car"

        image = (mpimg.imread(features[index]) * 255).astype(np.uint8)

        if preprocess == 1:
            image = image_preprocessing(image)

        axarr[i, 0].set_title('%s' % label_str)
        axarr[i, 0].imshow(image)

        hist, bins = np.histogram(image.flatten(), 256, [0, 256])
        cdf = hist.cumsum()
        cdf_normalized = cdf * hist.max()/ cdf.max()

        axarr[i, 1].plot(cdf_normalized, color='b')
        axarr[i, 1].plot(hist, color='r')
        axarr[i, 1].legend(('cdf', 'histogram'), loc='upper left')

        axarr[i, 0].axis('off')

    # Tweak spacing to prevent clipping of title labels
    f.tight_layout()

    if preprocess == 1:
        plt.savefig("./output_images/dataset_sample_preprocessed.png")
    else:
       ...


I am working on the file "CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb".
The first task is:
5. Get Model
As we have seen in the "intro to convolutionnal network" lesson, a nice property of a convolutional filter is that is reuses the weights gwhile slidding through the image and feature maps, the weight number is thus not dependent on the input image size. Therefore, it is possible to train a full ConvNet to classify small size images (64x64) as an image classifier (like we have done for Project 2) and output the result on one neuron.
In our case the output will be either there is a car in the image or not (tanh=1 or tanh=-1). The weights resulting from the training can then be reused on the same full ConvNet to build an output feature map from larger images. This feature map can be seen as a heatmap in which each pixel represents the output of the original trained ConvNet for a section of the input image. These pixels thus give the "car probability" for a specific location in the input image.
This cell:
* Gets an all convolutionnal Keras model to train from the file model.py.
Can you write Python code for it?

from model import get_model
from keras.layers import Flatten

# Get the "base" ConvNet Model
model = get_model()

# Flat out the last layer for training
model.add(Flatten())

# Print out model summary
if display_output == 1:
    model.summary()


I am working on the file "CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb".
The first task is:
6. Declare generators/load dataset
This cell:
* Declares a Keras generator (keras_generator()) to enable training on low end hardware
* Declares a loader (loader()) to load all the dataset in memory (faster training, higher end hardware required)
Can you write Python code for it?

from sklearn.utils import shuffle

def keras_generator(features, labels, batch_size=32):
    num_features = len(features)
    # Loop forever so the generator never terminates
    while 1:
        # shuffles the input sample
        shuffle(features, labels)
        for offset in range(0, num_features, batch_size):
            # File path subset
            batch_features = features[offset:offset + batch_size]
            batch_labels = labels[offset:offset + batch_size]
            imgs = []

            for feature in batch_features:
                image = (mpimg.imread(feature) * 255).astype(np.uint8)

                # Image preprocessing
                # none..
                imgs.append(image)

            # Convert images to numpy arrays
            X = np.array(imgs, dtype=np.uint8)
            y = np.array(batch_labels)

            yield shuffle(X, y)

def loader(features, labels):
    for iterable in keras_generator(features, labels, batch_size=len(features)):
        return iterable

# Prepare generator functions /dataset
if use_generator == 1:
    # Use the generator function
    train_generator =      keras_generator(X_train, y_train, batch_size=32)
    validation_generator = keras_generator(X_valid, y_valid, batch_size=32)
else:
    # Load all the preprocessed images in memory
    train_set =      loader(X_train, y_train)
    validation_set = loader(X_valid, y_valid)


I am working on the file "CarND-Vehicle-Detection-P5/P5-TrainModel.ipynb".
The first task is:
9. Test the classifier on random images
This cell:
* Picks random images from the dataset
* Infers the label using the trained model
* Measures the inference time
* Shows a figure of the images and predicted label, title color changes according to correctness of the inference (green = correct, red = incorrect).
Can you write Python code for it?

if display_output == 1:

    import matplotlib.pyplot as plt
    %matplotlib inline
    import time
    import numpy as np

    sample_num = 12

    col_num = 4
    row_num = int(sample_num/col_num)

    # Create training sample + histogram plot
    f, axarr = plt.subplots(row_num, col_num, figsize=(col_num * 4, row_num * 3))

    for i in range(sample_num):

        # Pick a random image from the validation set
        index = np.random.randint(validation_set[0].shape[0])

        # Add one dimension to the image to fit the CNN input shape...
        sample = np.reshape(validation_set[0][index], (1, 64,64,3))

        # Record starting time
        start_time = time.time()

        # Infer the label
        inference = model.predict(sample, batch_size=64, verbose=0)

        # Print time difference...
        print("Image %2d inference time : %.4f s" % (i, time.time() - start_time))

        # Extract inference value
        inference = inference[0][0]

        # Show the image
        color_str = 'green'
        if inference >= 0.0:
            title_str = "Car: {:4.2f}" .format(inference)
            if validation_set[1][index] != 1:
                color_str = 'red'
        else:
            title_str = "No Car: {:4.2f}" .format(inference)

            if validation_set[1][index] != -1:
                color_str = 'red'

        axarr[int(i/col_num), i % col_num].imshow(validation_set[0][index])
        axarr[int(i/col_num), i % col_num].set_title(title_str, color = color_str)
        axarr[int(i/col_num), i % col_num].axis('off')

    f.tight_layout()
    plt.savefig("./output_images/inference.png")


I am working on the file "Car_classifier_with_Google_Cloud_Vision.ipynb".
The first task is:
Vous devez importer un fichier .json avec les crédentiels nécessaires pour utiliser le service de Google Cloud Vision.
Pour simplifier l'exercise, votre instructeur dispose déjà d'un compte Google Cloud et d'un projet avec la facturation et les permissions nécessaires.
Votre instructeur va vous fournir les crédentiels, assurez-vous de les importer correctement
Can you write Python code for it?

# Maintenant, nous allons pointer vers le fichier json avec nos crédentiels

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="car-classificator-credentials.json"


I am working on the file "Caravel/Visualising Tweets.ipynb".
The first task is:
2) Get key for your apps:
Can you write Python code for it?


I am working on the file "Caravel/Visualising Tweets.ipynb".
The first task is:
Converting created_at datatype from Object to Datetime
Can you write Python code for it?

tweets_df['created_at'] = pd.to_datetime(tweets_df['created_at'].astype(str))
tweets_df.dtypes

tweets_df.head()

tweets_df.to_csv('/home/nipun/Downloads/Test_Twitter/Twitter_scrape.csv',encoding='utf-8')

tweets_df['Username'].value_counts()


I am working on the file "Caravel/Visualising Tweets.ipynb".
The first task is:
Data cleaning
Can you write Python code for it?

new_tweet_df = pd.read_csv('/home/nipun/Downloads/Test_Twitter/Twitter_IPL2016.csv',header=0)
new_tweet_df['location'].value_counts()[0:20]

#for simplicity in visualisation we will take only those locations
#where count is greater than or equal to 10
tweet_filter_df = new_tweet_df.groupby("location").filter(lambda x: len(x) >= 10)
tweet_filter_df['location'].value_counts()

tweet_filter_df['lang'].value_counts()

tweet_filter_df['created_at'] = pd.to_datetime(tweet_filter_df['created_at'].astype(str))
tweet_filter_df.dtypes
tweet_filter_df.to_csv('/home/nipun/Downloads/Test_Twitter/Finished_Twitter_IPL2016.csv',index=0,encoding='utf-8')


I am working on the file "Caravel/Visualising Tweets.ipynb".
The first task is:
Ordinary way to visualise data
Can you write Python code for it?

tweets_by_lang = tweet_filter_df['lang'].value_counts()

fig, ax = plt.subplots()
ax.tick_params(axis='x', labelsize=15)
ax.tick_params(axis='y', labelsize=10)
ax.set_xlabel('Languages', fontsize=15)
ax.set_ylabel('Number of tweets' , fontsize=15)
ax.set_title('Top 5 languages', fontsize=15, fontweight='bold')
tweets_by_lang[:5].plot(ax=ax, kind='bar', color='cyan')


I am working on the file "Caravel/Visualising Tweets.ipynb".
The first task is:
Scraping Tweets
Necessary python packages: <br>
Tweepy: https://github.com/tweepy/tweepy
$pip install tweepy
Can you write Python code for it?

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

#Variables that contains the user credentials to access Twitter API
consumer_key= "################"
consumer_secret = "################"
access_token = "################"
access_token_secret= "################"
tweet_file_path="/home/nipun/Downloads/Twitter_scrape/Twitter_scrape.txt"
tweet_file_handle=open(tweet_file_path,"a")

#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):

    def on_data(self, data):
        print data
        tweet_file_handle.write(str(data)+"\n")
        return True

    def on_error(self, status):
        print status

#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)

#This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['IPL2016'])


I am working on the file "Case - Ecology.ipynb".
The first task is:
Below we plot the histograms of author count for all three periods, this time normalizing the histograms so that we can compare them.
Can you write Python code for it?

plt.hist([len(authors) for authors in corpus_early.features['authors'].features.values()],
         bins=range(1, 10), label='1920-1944', histtype='step', lw=4, normed=True)
plt.hist([len(authors) for authors in corpus_mid.features['authors'].features.values()],
         bins=range(1, 10), label='1945-1969', histtype='step', lw=4, normed=True)
plt.hist([len(authors) for authors in corpus_late.features['authors'].features.values()],
         bins=range(1, 10), label='1970-1995', histtype='step', lw=4, normed=True)

plt.legend()
plt.ylim(0, 1.)
plt.show()


I am working on the file "Case - Ecology.ipynb".
The first task is:
Clearly the average number of neighbors is increasing -- people are collaborating with more people.
Another interesting feature of these networks is the amount of clustering. Clustering is when a node's neighbors tend also to be connected to each other. The clustering coefficient can be calculated for individual nodes, but looking at the average clustering coefficient gives us an indication of the degree of clustering globally. A low average clustering coefficient means that nodes tend to be connected at random.
Can you write Python code for it?

print '1920-1944:', nx.average_clustering(coauthor_graph_early)
print '1945-1969:', nx.average_clustering(coauthor_graph_mid)
print '1970-1994:', nx.average_clustering(coauthor_graph_late)


I am working on the file "Case - Ecology.ipynb".
The first task is:
First, we import the wos module from tethne.readers. We'll use this module to parse our data.
Can you write Python code for it?


I am working on the file "Case - Ecology.ipynb".
The first task is:
Here we can look explicitly at the relation between the average number of authors per paper and the number of nodes in each slice. They are related in a fairly linear fashion:
Can you write Python code for it?

mean_authors = zip(*[(k, mean([len(authors) for authors in sub.features['authors'].features.values()]))
                    for k, sub in corpus.slice(window_size=6, step_size=4)])

plt.scatter(mean_authors[1], node_distribution[1])


I am working on the file "Case - Ecology.ipynb".
The first task is:
Here we can see that the number of nodes increases in what looks like an exponential fashion, disproportionate to the number of papers in each slice. This is consistent with our earlier observation that the average number of authors per paper is increasing: more authors will be included in the network.
Can you write Python code for it?

paper_distribution = corpus.distribution(window_size=6, step_size=4)
plt.plot(*paper_distribution, label='Papers')

node_distribution = zip(*G.node_distribution().items())
plt.plot(*node_distribution, label='Nodes')

plt.legend()
plt.show()


I am working on the file "Case - Ecology.ipynb".
The first task is:
Let's do the same thing for the mid- and late-period subcorpora:
Can you write Python code for it?

coauthor_graph_mid = coauthors(corpus_mid)
coauthor_graph_late = coauthors(corpus_late)

coauthor_graph_mid.order(), coauthor_graph_mid.size()

coauthor_graph_late.order(), coauthor_graph_late.size()


I am working on the file "Case - Ecology.ipynb".
The first task is:
Let's start with something simple, like degree. The degree of a node is the number of other nodes that are connected to that node (i.e. its neighbors). NetworkX has a function called degree() that calculates the degree of all of the nodes in a network. Below, we calculate the average degree for each co-author network.
Can you write Python code for it?

print '1920-1944:', mean(nx.degree(coauthor_graph_early).values())
print '1945-1969:', mean(nx.degree(coauthor_graph_mid).values())
print '1970-1994:', mean(nx.degree(coauthor_graph_late).values())


I am working on the file "Case - Ecology.ipynb".
The first task is:
Let's take a look at the topology of the literature for each of our three periods, from earlier.
Can you write Python code for it?

graph_bc_early = bibliographic_coupling(corpus_early, node_attrs=['date', 'title'])
graph_bc_mid = bibliographic_coupling(corpus_mid, node_attrs=['date', 'title'])
graph_bc_late = bibliographic_coupling(corpus_late, node_attrs=['date', 'title'])


I am working on the file "Case - Ecology.ipynb".
The first task is:
Let's visualize these as well:
Can you write Python code for it?


I am working on the file "Case - Ecology.ipynb".
The first task is:
Let's zoom in on the first 25 years of publication.
We first create a subcorpus for the years 1920-1944 (in Python, the end value of a range is excluded). We can then plot the volume of papers, as before.
Can you write Python code for it?

corpus_early = corpus.subcorpus(('date', range(1920, 1945)))
plt.bar(*corpus_early.distribution())
plt.show()


I am working on the file "Case - Ecology.ipynb".
The first task is:
Not only do the actors in these networks tend to form more connections (degree) in later periods, but they also tend to form more clusters.
Finally, assortativity gives us an indication of how actors organize themselves within the network. High assortativity means that nodes with a high number of neighbors tend to be connected to other well-connected nodes.
Can you write Python code for it?

print '1920-1944:', nx.degree_assortativity_coefficient(coauthor_graph_early)
print '1945-1969:', nx.degree_assortativity_coefficient(coauthor_graph_mid)
print '1970-1994:', nx.degree_assortativity_coefficient(coauthor_graph_late)


I am working on the file "Case - Ecology.ipynb".
The first task is:
Number of authors per paper
In the early period, the vast majority of publications are single-author papers. We can use the hist() function to display a histogram of the number of authors per paper.
Can you write Python code for it?

# Calculate the number of authors per paper.
N_authors = [len(authors) for authors in corpus_early.features['authors'].features.values()]

# Generate a histogram.
plt.hist(N_authors, bins=range(1, 10))
plt.show()


I am working on the file "Case - Ecology.ipynb".
The first task is:
Number of nodes (order) and edges (size):
Can you write Python code for it?