
# coding: utf-8

# Deep Learning
# =============
# 
# Assignment 2
# ------------
# 
# Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html).
# 
# The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow.

# In[1]:


# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range


# First reload the data we generated in `1_notmnist.ipynb`.

# In[2]:


pickle_file = '../notMNIST.pickle'

with open(pickle_file, 'rb') as f:
  save = pickle.load(f)
  train_dataset = save['train_dataset']
  train_labels = save['train_labels']
  valid_dataset = save['valid_dataset']
  valid_labels = save['valid_labels']
  test_dataset = save['test_dataset']
  test_labels = save['test_labels']
  del save  # hint to help gc free up memory
  print('Training set', train_dataset.shape, train_labels.shape)
  print('Validation set', valid_dataset.shape, valid_labels.shape)
  print('Test set', test_dataset.shape, test_labels.shape)


# Reformat into a shape that's more adapted to the models we're going to train:
# - data as a flat matrix,
# - labels as float 1-hot encodings.

# In[3]:


image_size = 28
num_labels = 10

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  return dataset, labels

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])


train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)



batch_size = 128
num_hidden_nodes1 = 1024
num_hidden_nodes2 = 1024
num_hidden_nodes3 = 305
num_hidden_nodes4 = 75
beta = 0
num_steps = 95001
keep_rate = 0.75
#learning_rate=1e-4

graph = tf.Graph()
with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  
  # Variables.
  weights1 = tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden_nodes1], stddev=np.sqrt(2/(image_size * image_size))))
  biases1 = tf.Variable(tf.zeros([num_hidden_nodes1]))
  weights2 = tf.Variable(tf.truncated_normal([num_hidden_nodes1, num_hidden_nodes2], stddev=np.sqrt(2/(num_hidden_nodes1))))
  biases2 = tf.Variable(tf.zeros([num_hidden_nodes2]))
  weights3 = tf.Variable(tf.truncated_normal([num_hidden_nodes2, num_hidden_nodes3], stddev=np.sqrt(2/(num_hidden_nodes2))))
  biases3 = tf.Variable(tf.zeros([num_hidden_nodes3]))
  weights4 = tf.Variable(tf.truncated_normal([num_hidden_nodes3, num_hidden_nodes4], stddev=np.sqrt(2/(num_hidden_nodes3))))
  biases4 = tf.Variable(tf.zeros([num_hidden_nodes4]))
  weights5 = tf.Variable(tf.truncated_normal([num_hidden_nodes4, num_labels], stddev=np.sqrt(2/(num_hidden_nodes4))))
  biases5 = tf.Variable(tf.zeros([num_labels]))
  
  #global_step = tf.Variable(0)  # count the number of steps taken.
  #learning_rate = tf.train.exponential_decay(0.001, global_step, 100, 0.95)

  # Training computation.
  hidden_layer1 = tf.matmul(tf_train_dataset, weights1) + biases1
  activated_hidden_layer1 = tf.nn.relu(hidden_layer1)
  dropout1 = tf.nn.dropout(activated_hidden_layer1, keep_rate) #dropout if applied after activation

  hidden_layer2 = tf.matmul(dropout1, weights2) + biases2
  activated_hidden_layer2 = tf.nn.relu(hidden_layer2)
  dropout2 = tf.nn.dropout(activated_hidden_layer2, keep_rate) #dropout if applied after activation

  hidden_layer3 = tf.matmul(dropout2, weights3) + biases3
  activated_hidden_layer3 = tf.nn.relu(hidden_layer3)
  dropout3 = tf.nn.dropout(activated_hidden_layer3, keep_rate) #dropout if applied after activation
  
  hidden_layer4 = tf.matmul(dropout3, weights4) + biases4
  activated_hidden_layer4 = tf.nn.relu(hidden_layer4)
  dropout4 = tf.nn.dropout(activated_hidden_layer4, keep_rate) #dropout if applied after activation

  logits = tf.matmul(dropout4, weights5) + biases5 
  #Note that we don't apply dropout for the last layer
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))+ \
    tf.scalar_mul(beta, tf.nn.l2_loss(weights1) + tf.nn.l2_loss(weights2) + tf.nn.l2_loss(weights3) + tf.nn.l2_loss(weights4) + tf.nn.l2_loss(weights5)) 
  
  # Optimizer.
  global_step = tf.Variable(0)  # count the number of steps taken.
  learning_rate = tf.train.exponential_decay(0.3, global_step, 3500, 0.86, staircase=True)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
 
  layer1 = tf.nn.relu(tf.matmul(tf_test_dataset, weights1) + biases1)
  layer2 = tf.nn.relu(tf.matmul(layer1, weights2) + biases2)
  layer3 = tf.nn.relu(tf.matmul(layer2, weights3) + biases3)
  layer4 = tf.nn.relu(tf.matmul(layer3, weights4) + biases4)
  test_prediction = tf.nn.softmax(  tf.matmul(layer4, weights5 ) + biases5 )

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)

    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f. learning_rate=%f" % (step, l, learning_rate.eval()))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      #print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))
  print('#############################')
  print("Test accuracy: %.1f%% with beta=%f, keep_rate =%f" % \
     (accuracy(test_prediction.eval(), test_labels), beta,keep_rate))


