# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Self-Driving Car Engineer Nanodegree
#
# ## Deep Learning
#
# ## Project: Build a Traffic Sign Recognition Classifier
#
# In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. 
#
# > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to  \n",
#     "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. 
#
# In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.
#
# The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
#
#
# >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.

##import all packages
import random
import csv
import cv2
import numpy as np
import matplotlib.pyplot as plt
import pickle
import tensorflow as tf
from tensorflow.contrib.layers import flatten

# ---
# ## Step 0: Load The Data

# +
# Load pickled data

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

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

X_train_original=X_train
X_valid_original=X_valid
X_test_original=X_test

xtrain=(np.asarray(X_train,dtype=np.int16)-128)/128
xvalid=(np.asarray(X_valid,dtype=np.int16)-128)/128
xtest=(np.asarray(X_test,dtype=np.int16)-128)/128

# ### Creating a dictionary with the signs names and the numbers as keys

with open('signnames.csv', mode='r') as infile:
    reader = csv.reader(infile)
    next(reader, None)
    labels_dict = {int(rows[0]):rows[1] for rows in reader}


# ---
#
# ## 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](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. 

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

# +
### 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(train['labels'])

# TODO: Number of validation examples
n_validation = len(valid['labels'])

# TODO: Number of testing examples.
n_test = len(test['labels'])

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

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

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

# ### 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](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) 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?

### Data exploration visualization code 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


# ### First, it is shown one exemple of each class in the dataset

# +
## Showing every class example

l=y_train.tolist()
num_row=np.ceil(n_classes/3)
f,ax =plt.subplots(int(num_row),3,figsize=(15,70))
# plt.tight_layout()
for i in range(n_classes):
    index=l.index(i)
    img=X_train[index]
    ax[i//3][i%3].imshow(img)
    ax[i//3][i%3].set_title(labels_dict[y_train[index]],fontsize=14)
ax[-1,-2].set_axis_off()
ax[-1,-1].set_axis_off()

    
# -

# ### For showing the images from a dataset, the function show_images() displays by default 5 figures randomly from the dataset.

def show_images(dataset, dataset_labels, dataset_type,nfigs=5):
    f, ax= plt.subplots(1,nfigs,figsize=(20,20))
    for i in range(nfigs):
        index=random.randint(0,len(dataset_labels))
        ax[i].imshow(dataset[index])
        ax[i].set_xlabel(labels_dict[dataset_labels[index]],fontsize=10)
        ax[i].set_ylabel(dataset_type,fontsize=20)
    plt.tight_layout()
    


# ### As an example, it is shown some images of the Training, Validation and Testing datasets 

show_images(X_train_original,y_train,"Train")
show_images(X_valid_original,y_valid,"Valid")
show_images(X_test_original,y_test,"Test")

# ### As the distribution of the classes within each dataset, histograms are plotted for each dataset

f, ax = plt.subplots(3, 1,figsize=(15,10))
labels=["Training","Validation","Testing"]
list=[y_train,y_valid,y_test]
for i in range(3):
    ax[i].hist(list[i],bins=n_classes,range=(0,n_classes),edgecolor = 'black')
    ax[i].set_ylabel(labels[i],fontsize=16)
plt.tight_layout()

# ### The most common signs in the testing database are shown below

# +
data=np.histogram(y_train, bins=n_classes,range=(0,n_classes))[0]
n=10
idx = np.argpartition(data, -n)[-n:]
out=[]
indices = idx[np.argsort((-data)[idx])]
# print(indices)
for i in range(len(indices)):
    out.append(labels_dict[indices[i]])

print("Most common signs in the testing database:\n ")
print(*out, sep = "\n")
# -

# ----
#
# ## 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](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).
#
# The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) 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](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

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

# Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. 
#
# Other pre-processing steps are optional. You can try different techniques to see if it improves performance. 
#
# Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

# +
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.

# +
##Shuffle:

from sklearn.utils import shuffle

X_train, y_train = shuffle(X_train, y_train)


# -

# ### Normalizing the data
#
# Normalizing includes converting to grayscale and normalizing the values of each image in order to have zero mean and unitary standart deviation

# +
### Normalize data:

def norm(X_train):
    xtrain_gray=[]
    for i in range(len(X_train)):
        gray=cv2.cvtColor(X_train[i],cv2.COLOR_RGB2GRAY)
        gray_norm=(gray-gray.mean())/gray.std()
        xtrain_gray.append(gray_norm)
    return np.expand_dims(np.array(xtrain_gray),-1)

X_train=norm(X_train)
X_valid=norm(X_valid)
X_test=norm(X_test)
# -

# Now the data is grayscale and normalized with zero mean and standard deviation of 1

# ### Model Architecture

# +
### Define your architecture here.
### Feel free to use as many code cells as needed.

# +
#Defining the hyperparameters:

rate = 0.0005
BATCH_SIZE=256
keep_prob=tf.placeholder(dtype=tf.float32)

# +
## Defining the Model Architecture:

mu = 0
sigma = 0.1
Layer1_depth=6
Layer2_depth=24
full_conect_depth=25*Layer2_depth
hidden1_depth=180
hidden2_depth=120


## Initializing the weights and biases:


conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, Layer1_depth), mean = mu, stddev = sigma))
conv1_b = tf.Variable(tf.zeros(Layer1_depth))
conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, Layer1_depth, Layer2_depth), mean = mu, stddev = sigma))
conv2_b = tf.Variable(tf.zeros(Layer2_depth))

fc1_W = tf.Variable(tf.truncated_normal(shape=(full_conect_depth, hidden1_depth), mean = mu, stddev = sigma))
fc1_b = tf.Variable(tf.zeros(hidden1_depth))

fc2_W  = tf.Variable(tf.truncated_normal(shape=(hidden1_depth, hidden2_depth), mean = mu, stddev = sigma))
fc2_b  = tf.Variable(tf.zeros(hidden2_depth))

fc3_W  = tf.Variable(tf.truncated_normal(shape=(hidden2_depth, n_classes), mean = mu, stddev = sigma))
fc3_b  = tf.Variable(tf.zeros(n_classes))

# -

# ### Building the Convnet Model:

def LeNet(x):
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.

    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

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

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

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x24.
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

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

    # SOLUTION: Flatten. Input = 5x5x24. Output = 600.
    fc0   = flatten(conv2)
    
    
    # SOLUTION: Layer 3: Fully Connected. Input = 600. Output = 180.
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)
    fc1    = tf.nn.dropout(fc1,keep_prob)

    # SOLUTION: Layer 4: Fully Connected. Input = 180. Output = 120.
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)
    fc2    = tf.nn.dropout(fc2,keep_prob)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    return logits

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

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

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

logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = 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})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples


# -

# ### Main code for training the network. 
#
# Uncomment if retraining is wanted

# +
# with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     num_examples = len(X_train)
#     validation_accuracy_old=0.1
#     print("Training...")
#     print()
#     i=0
#     while (True):
#         i+=1
#         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:0.5})
            
#         validation_accuracy = evaluate(X_valid, y_valid)
#         print("EPOCH {} ...".format(i+1))
#         print("Validation Accuracy = {:.3f}".format(validation_accuracy))
#         print()
#         if ((validation_accuracy-validation_accuracy_old)/validation_accuracy_old<-0.002):
#             print("Max value found. Breaking...")
#             break
#         validation_accuracy_old=validation_accuracy
        
#     saver.save(sess, './save_file')
#     print("Model saved")
# -

# ### Restoring the saved model. 

with tf.Session() as sess:
    saver.restore(sess, "./backup_5")
    training_accuracy = evaluate(X_train, y_train)
    validation_accuracy = evaluate(X_valid, y_valid)
    test_accuracy = evaluate(X_test, y_test)
    print("Training accuracy: {}%".format(round(100*training_accuracy,1)))
    print("Validation accuracy: {}%".format(round(100*validation_accuracy,1)))
    print("Test accuracy: {}%".format(round(100*test_accuracy,1)))
#     saver.save(sess, './backup_5')

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

# +
### Load the images and plot them here.
### Feel free to use as many code cells as needed.

# +
n_import=9 #Number of imported images


images_import=[] # List of images
for i in range (n_import):
    img=plt.imread("sign{}.png".format(i+1),cv2.COLOR_RGBA2RGB)
    images_import.append(cv2.cvtColor(img,cv2.COLOR_RGBA2RGB))
# -

input_labels=[] # List with the images labels
with open('signnames-input.csv', mode='r') as infile:
    reader = csv.reader(infile)
    next(reader, None)
    for rows in reader:
        input_labels.append(rows[1]) 


# ### Showing the imported images with the correct labels

f, ax=plt.subplots(1,n_import,figsize=(20,20))
# f.suptitle('Imported images')
for i in range (n_import):
    ax[i].imshow(images_import[i])
    ax[i].set_xlabel(input_labels[i])
    ax[i].set_title('Imported')

b=int(np.ceil(n_import/2))
f, ax=plt.subplots(2,b,figsize=(20,10))
# f.suptitle('Imported images')
for i in range (n_import):
    ax[i//b][i%b].imshow(images_import[i])
    ax[i//b][i%b].set_xlabel(input_labels[i],fontsize=16)
    ax[i//b][i%b].set_title('Imported',fontsize=20)
ax[-1,-1].set_axis_off()

# ### Predict the Sign Type for Each Image

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

# Normalizing the images
images_norm=norm(images_import)

# ### Calculate the prediction with the convnet algorithm 

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, "./backup_5")

    logits_out=sess.run(logits,feed_dict={x:images_norm,keep_prob:1.})
    softmax_out=sess.run(tf.nn.top_k(tf.constant(logits_out), k=5))

    prediction=softmax_out[1][:,0]
    print("Convnet prediction: {}".format(softmax_out[1][:,0]))
#     show_images(images_import,prediction,"Prediction",nfigs=n_import,randomed=False)

softmax_label=[]
for line in range(len(softmax_out[1])):
    l=[]
    for row in range(len(softmax_out[1][0])):
        index=softmax_out[1][line][row]

        l.append(labels_dict[index])
    softmax_label.append(l)

# ### Displaying the prediction on the images
#
# If the prediciton is correct, the x_label is green. Otherwise is red.

b=int(np.ceil(n_import/2))
f, ax=plt.subplots(2,b,figsize=(20,10))
# f.suptitle('Imported images')
for i in range (n_import):
    ax[i//b][i%b].imshow(images_import[i])
    if (softmax_label[i][0]==input_labels[i]): color="g"
    else: color="r"
    ax[i//b][i%b].set_xlabel(softmax_label[i][0],color=color,fontsize=16)
    ax[i//b][i%b].set_title('Prediction',fontsize=20)
ax[-1,-1].set_axis_off()

# ### Analyze Performance

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

# ### 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`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#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. `tf.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.

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

# ### Output Top 5 Softmax Probabilities

for image in range(n_import):
    f, ax = plt.subplots(1, 2,figsize=(15,5))

    ax[0].imshow(images_import[image])
    names=softmax_label[image]
    ax[1].bar(names,softmax_out[0][image])
    ax[1].tick_params(rotation=45)
    plt.show()

# ### Accuracy on the importated images

# +
correct=0

for i in range(n_import):
    if np.array(softmax_label)[:,0][i]==input_labels[i]: correct+=1

print("Predicted correctly: {}".format(correct))
print("Predicted incorrectly: {}".format(n_import-correct))
print("Accuracy on imported images: {}%".format(round(100*correct/n_import,1)) )

StarcoderdataJupyterScriptsDedupFiltered