Deep Learning

Assignment 3

Previously in 2_fullyconnected.ipynb, you trained a logistic regression and a neural network model.

The goal of this assignment is to explore regularization techniques.


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

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)


Training set (200000, 28, 28) (200000,)
Validation set (10000, 28, 28) (10000,)
Test set (10000, 28, 28) (10000,)

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 1 to [0.0, 1.0, 0.0 ...], 2 to [0.0, 0.0, 1.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)
print('Test set', test_dataset.shape, test_labels.shape)


Training set (200000, 784) (200000, 10)
Validation set (10000, 784) (10000, 10)
Test set (10000, 784) (10000, 10)

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

Problem 1

Introduce and tune L2 regularization for both logistic and neural network models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor t using nn.l2_loss(t). The right amount of regularization should improve your validation / test accuracy.



Solution 1 - A

Let's first try to apply L2 Regularization for logistic regressioin model. Accuracy will be increased and you can compare the same with the Logistic regression done in 2_fullyconnected.ipynb



In [5]:
batch_size = 128

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)
  # Setting the beta value as 0.001
  beta_l2_reg = tf.constant(1e-3)
  
  # Variables.
  weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]))
  biases = tf.Variable(tf.zeros([num_labels]))
  
  # Training computation.
  logits = tf.matmul(tf_train_dataset, weights) + biases
  # new loss for L2 Regularization is L' = L + beta * l2_loss(weights)
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits)) \
    + beta_l2_reg * tf.nn.l2_loss(weights)
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

In [6]:
num_steps = 3001

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" % (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))


Initialized
Minibatch loss at step 0: 19.221306
Minibatch accuracy: 10.2%
Validation accuracy: 12.9%
Minibatch loss at step 500: 2.526054
Minibatch accuracy: 76.6%
Validation accuracy: 76.2%
Minibatch loss at step 1000: 1.702284
Minibatch accuracy: 78.9%
Validation accuracy: 78.4%
Minibatch loss at step 1500: 0.972689
Minibatch accuracy: 84.4%
Validation accuracy: 79.6%
Minibatch loss at step 2000: 0.781553
Minibatch accuracy: 90.6%
Validation accuracy: 80.5%
Minibatch loss at step 2500: 0.825031
Minibatch accuracy: 81.2%
Validation accuracy: 81.4%
Minibatch loss at step 3000: 0.767695
Minibatch accuracy: 82.8%
Validation accuracy: 81.5%
Test accuracy: 88.8%

Solution 1 - B

Now let's try to apply L2 Regularization for neural network model. Accuracy will be increased and you can compare the same with the neural network done in 2_fullyconnected.ipynb



In [7]:
batch_size = 128
num_hidden_nodes = 1024

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)
  # Setting the beta value as 0.001
  beta_l2_reg = tf.constant(1e-3)
  
  # Variables.
  weights = {
      'hidden': tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden_nodes])),
      'output': tf.Variable(tf.truncated_normal([num_hidden_nodes, num_labels]))
  }

  biases = {
      'hidden': tf.Variable(tf.zeros([num_hidden_nodes])),
      'output': tf.Variable(tf.zeros([num_labels]))
  }
  
  # Training computation.
  hidden_train = tf.nn.relu(tf.matmul(tf_train_dataset, weights['hidden']) + biases['hidden'])
  logits = tf.matmul(hidden_train, weights['output']) + biases['output']
  # Adding l2_loss of weights for hidden and output summed up multiplied by beta_l2_reg to the loss
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels)) + \
         beta_l2_reg * (tf.nn.l2_loss(weights['hidden']) + tf.nn.l2_loss(weights['output']))
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  hidden_valid = tf.nn.relu(tf.matmul(tf_valid_dataset, weights['hidden']) + biases['hidden'])
  valid_prediction = tf.nn.softmax(tf.matmul(hidden_valid, weights['output']) + biases['output'])
  hidden_test = tf.nn.relu(tf.matmul(tf_test_dataset, weights['hidden']) + biases['hidden'])
  test_prediction = tf.nn.softmax(tf.matmul(hidden_test, weights['output']) + biases['output'])

In [8]:
num_steps = 3001

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" % (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))


Initialized
Minibatch loss at step 0: 657.960571
Minibatch accuracy: 9.4%
Validation accuracy: 23.4%
Minibatch loss at step 500: 197.729004
Minibatch accuracy: 82.0%
Validation accuracy: 78.7%
Minibatch loss at step 1000: 114.965958
Minibatch accuracy: 80.5%
Validation accuracy: 81.7%
Minibatch loss at step 1500: 68.107376
Minibatch accuracy: 89.8%
Validation accuracy: 83.4%
Minibatch loss at step 2000: 41.164169
Minibatch accuracy: 89.1%
Validation accuracy: 85.1%
Minibatch loss at step 2500: 25.113413
Minibatch accuracy: 89.1%
Validation accuracy: 85.7%
Minibatch loss at step 3000: 15.443836
Minibatch accuracy: 85.9%
Validation accuracy: 86.7%
Test accuracy: 93.0%

Problem 2

Let's demonstrate an extreme case of overfitting. Restrict your training data to just a few batches. What happens?


Try the neural network model with less number of batches, no L2 Regularization and observe the pattern of Mini batch accuracy reaches 100 % - i.e. overfitting, loss becomes 0 and there is no change in accuracy of validation batch.


In [9]:
batch_size = 128
num_hidden_nodes = 1024

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.
  weights = {
      'hidden': tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden_nodes])),
      'output': tf.Variable(tf.truncated_normal([num_hidden_nodes, num_labels]))
  }

  biases = {
      'hidden': tf.Variable(tf.zeros([num_hidden_nodes])),
      'output': tf.Variable(tf.zeros([num_labels]))
  }
  
  # Training computation.
  hidden_train = tf.nn.relu(tf.matmul(tf_train_dataset, weights['hidden']) + biases['hidden'])
  logits = tf.matmul(hidden_train, weights['output']) + biases['output']
  # Adding l2_loss of weights for hidden and output summed up multiplied by beta_l2_reg to the loss
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels))
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  hidden_valid = tf.nn.relu(tf.matmul(tf_valid_dataset, weights['hidden']) + biases['hidden'])
  valid_prediction = tf.nn.softmax(tf.matmul(hidden_valid, weights['output']) + biases['output'])
  hidden_test = tf.nn.relu(tf.matmul(tf_test_dataset, weights['hidden']) + biases['hidden'])
  test_prediction = tf.nn.softmax(tf.matmul(hidden_test, weights['output']) + biases['output'])

In [12]:
num_steps = 201
num_batches = 4

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)
    # Changing the offset value to run for less number of batches
    # Dividing the step by num_branches
    offset = ((step % num_batches) * 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 % 10 == 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))


Initialized
Minibatch loss at step 0: 285.836792
Minibatch accuracy: 4.7%
Validation accuracy: 33.6%
Minibatch loss at step 10: 37.158504
Minibatch accuracy: 90.6%
Validation accuracy: 74.6%
Minibatch loss at step 20: 5.067512
Minibatch accuracy: 96.9%
Validation accuracy: 73.3%
Minibatch loss at step 30: 0.975846
Minibatch accuracy: 99.2%
Validation accuracy: 74.0%
Minibatch loss at step 40: 13.441036
Minibatch accuracy: 99.2%
Validation accuracy: 75.5%
Minibatch loss at step 50: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 60: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 70: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 80: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 90: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 100: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 110: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 120: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 130: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 140: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 150: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 160: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 170: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 180: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 190: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Minibatch loss at step 200: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 75.0%
Test accuracy: 82.7%

Problem 3

Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides nn.dropout() for that, but you have to make sure it's only inserted during training.

What happens to our extreme overfitting case?


Now let's try to introduce dropout at the hidden layer, i.e after building hidden layer, construct new hidden layer with the drop out.


In [13]:
batch_size = 128
num_hidden_nodes = 1024

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.
  weights = {
      'hidden': tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden_nodes])),
      'output': tf.Variable(tf.truncated_normal([num_hidden_nodes, num_labels]))
  }

  biases = {
      'hidden': tf.Variable(tf.zeros([num_hidden_nodes])),
      'output': tf.Variable(tf.zeros([num_labels]))
  }
  
  # Training computation.
  hidden_train = tf.nn.relu(tf.matmul(tf_train_dataset, weights['hidden']) + biases['hidden'])
  # Seeting half of them to zero
  hidden_train_with_dropout = tf.nn.dropout(hidden_train, 0.5)
  logits = tf.matmul(hidden_train, weights['output']) + biases['output']
  # Adding l2_loss of weights for hidden and output summed up multiplied by beta_l2_reg to the loss
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels))
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  hidden_valid = tf.nn.relu(tf.matmul(tf_valid_dataset, weights['hidden']) + biases['hidden'])
  valid_prediction = tf.nn.softmax(tf.matmul(hidden_valid, weights['output']) + biases['output'])
  hidden_test = tf.nn.relu(tf.matmul(tf_test_dataset, weights['hidden']) + biases['hidden'])
  test_prediction = tf.nn.softmax(tf.matmul(hidden_test, weights['output']) + biases['output'])

In [14]:
num_steps = 201
num_batches = 4

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)
    # Changing the offset value to run for less number of batches
    # Dividing the step by num_branches
    offset = ((step % num_batches) * 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 % 10 == 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))


Initialized
Minibatch loss at step 0: 439.762329
Minibatch accuracy: 8.6%
Validation accuracy: 21.9%
Minibatch loss at step 10: 57.449600
Minibatch accuracy: 78.9%
Validation accuracy: 72.9%
Minibatch loss at step 20: 62.771461
Minibatch accuracy: 85.9%
Validation accuracy: 73.0%
Minibatch loss at step 30: 16.557804
Minibatch accuracy: 93.8%
Validation accuracy: 77.1%
Minibatch loss at step 40: 20.362616
Minibatch accuracy: 94.5%
Validation accuracy: 75.9%
Minibatch loss at step 50: 2.674005
Minibatch accuracy: 96.9%
Validation accuracy: 76.8%
Minibatch loss at step 60: 11.597603
Minibatch accuracy: 94.5%
Validation accuracy: 77.7%
Minibatch loss at step 70: 0.454059
Minibatch accuracy: 98.4%
Validation accuracy: 77.8%
Minibatch loss at step 80: 1.474483
Minibatch accuracy: 98.4%
Validation accuracy: 77.5%
Minibatch loss at step 90: 0.662903
Minibatch accuracy: 98.4%
Validation accuracy: 77.0%
Minibatch loss at step 100: 4.212022
Minibatch accuracy: 96.1%
Validation accuracy: 78.1%
Minibatch loss at step 110: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 77.2%
Minibatch loss at step 120: 0.071829
Minibatch accuracy: 99.2%
Validation accuracy: 77.4%
Minibatch loss at step 130: 4.838550
Minibatch accuracy: 96.9%
Validation accuracy: 78.0%
Minibatch loss at step 140: 0.217957
Minibatch accuracy: 99.2%
Validation accuracy: 77.6%
Minibatch loss at step 150: 1.517569
Minibatch accuracy: 98.4%
Validation accuracy: 77.7%
Minibatch loss at step 160: 3.657223
Minibatch accuracy: 98.4%
Validation accuracy: 77.7%
Minibatch loss at step 170: 0.000000
Minibatch accuracy: 100.0%
Validation accuracy: 77.3%
Minibatch loss at step 180: 0.000011
Minibatch accuracy: 100.0%
Validation accuracy: 78.1%
Minibatch loss at step 190: 0.120963
Minibatch accuracy: 99.2%
Validation accuracy: 77.7%
Minibatch loss at step 200: 0.179683
Minibatch accuracy: 99.2%
Validation accuracy: 78.2%
Test accuracy: 85.3%

You can notice after introducing Dropout even if we achieve 100% accuracy at one stage, the next stage is not overfit, and there is change and improvement in both validation and test accuracy.


Problem 4

Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is 97.1%.

One avenue you can explore is to add multiple layers.

Another one is to use learning rate decay:

global_step = tf.Variable(0)  # count the number of steps taken.
learning_rate = tf.train.exponential_decay(0.5, global_step, ...)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)


Lets build multi-layer neural network model i.e. with more hidden layers including L2 Regularization and dropout.


In [33]:
batch_size = 128
num_hidden_nodes_1 = 1024
num_hidden_nodes_2 = 256
num_hidden_nodes_3 = 128
dropout_prob = 0.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))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)
  beta_l2_reg = tf.constant(1e-3)
  global_step = tf.Variable(0)
  
  # Variables.
  weights = {
      'hidden_1': tf.Variable(tf.truncated_normal([image_size * image_size, num_hidden_nodes_1], 
                                                 stddev=np.sqrt(2.0 / (image_size * image_size)))),
      'hidden_2': tf.Variable(tf.truncated_normal([num_hidden_nodes_1, num_hidden_nodes_2],
                                                 stddev=np.sqrt(2.0 / (num_hidden_nodes_1)))),
      'hidden_3': tf.Variable(tf.truncated_normal([num_hidden_nodes_2, num_hidden_nodes_3],
                                                 stddev=np.sqrt(2.0 / (num_hidden_nodes_2)))),
      'output': tf.Variable(tf.truncated_normal([num_hidden_nodes_3, num_labels],
                                               stddev=np.sqrt(2.0 / (num_hidden_nodes_3))))
  }

  biases = {
      'hidden_1': tf.Variable(tf.zeros([num_hidden_nodes_1])),
      'hidden_2': tf.Variable(tf.zeros([num_hidden_nodes_2])),
      'hidden_3': tf.Variable(tf.zeros([num_hidden_nodes_3])),
      'output': tf.Variable(tf.zeros([num_labels]))
  }
  
  # Training computation. 1st hidden layer
  hidden_train_1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights['hidden_1']) + biases['hidden_1'])
  # Dropout - Seeting half of them to zero
  hidden_train_1_with_dropout = tf.nn.dropout(hidden_train_1, dropout_prob)
  # 2nd Hidden Layer
  hidden_train_2 = tf.nn.relu(tf.matmul(hidden_train_1_with_dropout, weights['hidden_2']) + biases['hidden_2'])
  hidden_train_2_with_dropout = tf.nn.dropout(hidden_train_2, dropout_prob)
  # 3rd hidden layer
  hidden_train_3 = tf.nn.relu(tf.matmul(hidden_train_2_with_dropout, weights['hidden_3']) + biases['hidden_3'])
  hidden_train_3_with_dropout = tf.nn.dropout(hidden_train_3, dropout_prob)
  
  logits = tf.matmul(hidden_train_3_with_dropout, weights['output']) + biases['output']
  # Adding l2_loss of weights for hidden and output summed up multiplied by beta_l2_reg to the loss
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels)) + \
         beta_l2_reg * (tf.nn.l2_loss(weights['hidden_1']) + tf.nn.l2_loss(weights['hidden_2']) + \
                        tf.nn.l2_loss(weights['hidden_3']) + tf.nn.l2_loss(weights['output']))
  
  # Optimizer.
  learning_rate = tf.train.exponential_decay(0.5, global_step, 4000, 0.65, staircase=True)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
  
  #optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  hidden_1_valid = tf.nn.relu(tf.matmul(tf_valid_dataset, weights['hidden_1']) + biases['hidden_1'])
  hidden_2_valid = tf.nn.relu(tf.matmul(hidden_1_valid, weights['hidden_2']) + biases['hidden_2'])
  hidden_3_valid = tf.nn.relu(tf.matmul(hidden_2_valid, weights['hidden_3']) + biases['hidden_3'])
  valid_prediction = tf.nn.softmax(tf.matmul(hidden_3_valid, weights['output']) + biases['output'])
  # Testing
  hidden_1_test = tf.nn.relu(tf.matmul(tf_test_dataset, weights['hidden_1']) + biases['hidden_1'])
  hidden_2_test = tf.nn.relu(tf.matmul(hidden_1_test, weights['hidden_2']) + biases['hidden_2'])
  hidden_3_test = tf.nn.relu(tf.matmul(hidden_2_test, weights['hidden_3']) + biases['hidden_3'])
  test_prediction = tf.nn.softmax(tf.matmul(hidden_3_test, weights['output']) + biases['output'])

In [34]:
num_steps = 18001

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" % (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))


Initialized
Minibatch loss at step 0: 3.841861
Minibatch accuracy: 10.9%
Validation accuracy: 21.5%
Minibatch loss at step 500: 1.271618
Minibatch accuracy: 86.7%
Validation accuracy: 83.8%
Minibatch loss at step 1000: 1.067141
Minibatch accuracy: 84.4%
Validation accuracy: 84.6%
Minibatch loss at step 1500: 0.787337
Minibatch accuracy: 86.7%
Validation accuracy: 85.5%
Minibatch loss at step 2000: 0.683433
Minibatch accuracy: 90.6%
Validation accuracy: 86.0%
Minibatch loss at step 2500: 0.730593
Minibatch accuracy: 83.6%
Validation accuracy: 85.6%
Minibatch loss at step 3000: 0.807467
Minibatch accuracy: 83.6%
Validation accuracy: 86.1%
Minibatch loss at step 3500: 0.802319
Minibatch accuracy: 82.8%
Validation accuracy: 85.7%
Minibatch loss at step 4000: 0.662625
Minibatch accuracy: 88.3%
Validation accuracy: 86.6%
Minibatch loss at step 4500: 0.559090
Minibatch accuracy: 87.5%
Validation accuracy: 86.9%
Minibatch loss at step 5000: 0.647757
Minibatch accuracy: 85.9%
Validation accuracy: 87.6%
Minibatch loss at step 5500: 0.641412
Minibatch accuracy: 85.9%
Validation accuracy: 87.2%
Minibatch loss at step 6000: 0.674697
Minibatch accuracy: 85.2%
Validation accuracy: 87.4%
Minibatch loss at step 6500: 0.506392
Minibatch accuracy: 92.2%
Validation accuracy: 87.6%
Minibatch loss at step 7000: 0.733440
Minibatch accuracy: 81.2%
Validation accuracy: 87.4%
Minibatch loss at step 7500: 0.626982
Minibatch accuracy: 86.7%
Validation accuracy: 87.6%
Minibatch loss at step 8000: 0.871364
Minibatch accuracy: 79.7%
Validation accuracy: 87.0%
Minibatch loss at step 8500: 0.537834
Minibatch accuracy: 89.1%
Validation accuracy: 88.2%
Minibatch loss at step 9000: 0.610870
Minibatch accuracy: 88.3%
Validation accuracy: 88.0%
Minibatch loss at step 9500: 0.589124
Minibatch accuracy: 87.5%
Validation accuracy: 88.4%
Minibatch loss at step 10000: 0.629830
Minibatch accuracy: 83.6%
Validation accuracy: 88.5%
Minibatch loss at step 10500: 0.524978
Minibatch accuracy: 85.2%
Validation accuracy: 88.3%
Minibatch loss at step 11000: 0.490621
Minibatch accuracy: 89.8%
Validation accuracy: 88.5%
Minibatch loss at step 11500: 0.634321
Minibatch accuracy: 86.7%
Validation accuracy: 88.3%
Minibatch loss at step 12000: 0.641640
Minibatch accuracy: 82.0%
Validation accuracy: 88.8%
Minibatch loss at step 12500: 0.556120
Minibatch accuracy: 89.1%
Validation accuracy: 88.9%
Minibatch loss at step 13000: 0.557997
Minibatch accuracy: 86.7%
Validation accuracy: 88.9%
Minibatch loss at step 13500: 0.521754
Minibatch accuracy: 91.4%
Validation accuracy: 88.9%
Minibatch loss at step 14000: 0.560268
Minibatch accuracy: 86.7%
Validation accuracy: 89.1%
Minibatch loss at step 14500: 0.598513
Minibatch accuracy: 87.5%
Validation accuracy: 88.8%
Minibatch loss at step 15000: 0.536655
Minibatch accuracy: 87.5%
Validation accuracy: 89.0%
Minibatch loss at step 15500: 0.593464
Minibatch accuracy: 82.0%
Validation accuracy: 88.9%
Minibatch loss at step 16000: 0.420335
Minibatch accuracy: 93.0%
Validation accuracy: 89.2%
Minibatch loss at step 16500: 0.457320
Minibatch accuracy: 89.8%
Validation accuracy: 89.3%
Minibatch loss at step 17000: 0.385993
Minibatch accuracy: 92.2%
Validation accuracy: 89.3%
Minibatch loss at step 17500: 0.261831
Minibatch accuracy: 97.7%
Validation accuracy: 89.5%
Minibatch loss at step 18000: 0.404273
Minibatch accuracy: 93.0%
Validation accuracy: 89.3%
Test accuracy: 95.3%

Improved Performance and reached 95% using multi-layer neural net, by fine tuning the parameters

  • Number of hidden units in each layer
  • Setting standard deviation of weights initialization
  • Exponential decay learning rate parameters
  • Number of steps to Run, increased from previous code.