# 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

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)


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

def forward(_input,weights,biases,drop_out=False):
	layer_1=tf.nn.relu(tf.add(tf.matmul(_input, weights['h1']),biases['b1']))
	if drop_out:
		layer_1 =tf.nn.dropout(layer_1 ,0.5)*2 #Hidden layer with RELU activation
		layer_2 =tf.nn.dropout( tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])),0.5)*2 #Hidden layer with RELU activation
		layer_3 =tf.nn.dropout( tf.nn.relu(tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])),0.5)*2
	else:	
		layer_2 =tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']))
		layer_3 =tf.nn.relu(tf.add(tf.matmul(layer_2, weights['h3']), biases['b3']))
	return tf.matmul(layer_3, weights['out']) + biases['out']

batch_size = 128
num_nodes=1024
beta=1e-5
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))
  print(valid_dataset.shape)


  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  
  # Variables.
  # Store layers weight & bias
  weights = {
    	'h1': tf.Variable(tf.truncated_normal([image_size * image_size,num_nodes])),
    	'h2': tf.Variable(tf.truncated_normal([num_nodes, num_nodes])),
   	'h3': tf.Variable(tf.truncated_normal([num_nodes, num_nodes])),
    	'out': tf.Variable(tf.truncated_normal([num_nodes, num_labels]))
    	}
  biases = {
    	'b1': tf.Variable(tf.truncated_normal([num_nodes])),
    	'b2': tf.Variable(tf.truncated_normal([num_nodes])),
    	'b3': tf.Variable(tf.truncated_normal([num_nodes])),
    	'out': tf.Variable(tf.truncated_normal([num_labels]))
	}


  logits=forward(tf_train_dataset,weights,biases,drop_out=True)
  # # # Training computation.
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # l2 regularization 
  regulatization_l2=loss+beta*(tf.nn.l2_loss(weights['out'])+tf.nn.l2_loss(weights['h1'])+tf.nn.l2_loss(weights['h2'])+tf.nn.l2_loss(weights['h3']))

  global_step=tf.Variable(0)
  learning_rate=tf.train.exponential_decay(0.00001,global_step,3001,0.96)
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(regulatization_l2)
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(forward(tf_valid_dataset, weights,biases,drop_out=False))
  test_prediction = tf.nn.softmax(forward(tf_test_dataset,weights,biases,drop_out=False))

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

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().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" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

