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 notmist.ipynb.


In [3]:
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 [4]:
image_size = 28
num_labels = 10

def reformat(dataset, labels):
  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
  # Map 2 to [0.0, 1.0, 0.0 ...], 3 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 [5]:
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.



In [13]:
batch_size = 128
hidden_layer_length = 1024
regularization_factor1 = 0.01
regularization_factor2 = 0.01

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)
  tf_regularization_factor1 = tf.constant(regularization_factor1)
  tf_regularization_factor2 = tf.constant(regularization_factor2)
  
  # Variables.
  weights1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, hidden_layer_length]))
  biases1 = tf.Variable(tf.zeros([hidden_layer_length]))
  
  weights2 = tf.Variable(
    tf.truncated_normal([hidden_layer_length, num_labels]))
  biases2 = tf.Variable(tf.zeros([num_labels]))
  
  # Training computation.
  train_logits1 = tf.matmul(tf_train_dataset, weights1) + biases1
  train_activations1 = tf.nn.relu(train_logits1)
  train_logits2 = tf.matmul(train_activations1, weights2) + biases2
  
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(train_logits2, tf_train_labels)) + \
    tf_regularization_factor1*tf.nn.l2_loss(weights1) + \
    tf_regularization_factor2*tf.nn.l2_loss(weights2)
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(train_logits2)
  
  valid_logits1 = tf.matmul(tf_valid_dataset, weights1) + biases1
  valid_activations1 = tf.nn.relu(valid_logits1)
  valid_logits2 = tf.matmul(valid_activations1, weights2) + biases2
  valid_prediction = tf.nn.softmax(valid_logits2)
  
  test_logits1 = tf.matmul(tf_test_dataset, weights1) + biases1
  test_activations1 = tf.nn.relu(test_logits1)
  test_logits2 = tf.matmul(test_activations1, weights2) + biases2
  test_prediction = tf.nn.softmax(test_logits2)

In [14]:
num_steps = 3000

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps+1):
    # 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("Train accuracy: %.1f%%" % accuracy(train_prediction.eval(), train_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))


Initialized
Minibatch loss at step 0: 3522.701904
Minibatch accuracy: 3.9%
Validation accuracy: 35.3%
Minibatch loss at step 500: 21.218346
Minibatch accuracy: 85.9%
Validation accuracy: 84.3%
Minibatch loss at step 1000: 1.122627
Minibatch accuracy: 74.2%
Validation accuracy: 83.5%
Minibatch loss at step 1500: 0.697249
Minibatch accuracy: 82.8%
Validation accuracy: 83.7%
Minibatch loss at step 2000: 0.717370
Minibatch accuracy: 85.2%
Validation accuracy: 84.1%
Minibatch loss at step 2500: 0.752475
Minibatch accuracy: 82.0%
Validation accuracy: 83.2%
Minibatch loss at step 3000: 0.811853
Minibatch accuracy: 81.2%
Validation accuracy: 84.1%
Test accuracy: 90.0%

Problem 2

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



In [15]:
num_steps = 3000
furthest_training_example_idx = 1000

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps+1):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (furthest_training_example_idx - 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("Train accuracy: %.1f%%" % accuracy(train_prediction.eval(), train_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))


Initialized
Minibatch loss at step 0: 3521.611328
Minibatch accuracy: 14.1%
Validation accuracy: 31.2%
Minibatch loss at step 500: 21.222721
Minibatch accuracy: 98.4%
Validation accuracy: 79.8%
Minibatch loss at step 1000: 0.610166
Minibatch accuracy: 100.0%
Validation accuracy: 80.7%
Minibatch loss at step 1500: 0.412852
Minibatch accuracy: 100.0%
Validation accuracy: 80.7%
Minibatch loss at step 2000: 0.407822
Minibatch accuracy: 100.0%
Validation accuracy: 80.5%
Minibatch loss at step 2500: 0.576761
Minibatch accuracy: 96.1%
Validation accuracy: 79.8%
Minibatch loss at step 3000: 0.428594
Minibatch accuracy: 99.2%
Validation accuracy: 79.7%
Test accuracy: 86.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?



In [ ]:
batch_size = 128
hidden_layer_length = 1024
regularization_factor1 = 0.01
regularization_factor2 = 0.01
dropout_keep_prob = 0.2

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)
  tf_regularization_factor1 = tf.constant(regularization_factor1)
  tf_regularization_factor2 = tf.constant(regularization_factor2)
  tf_dropout_keep_prob = tf.constant(dropout_keep_prob)
  
  # Variables.
  weights1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, hidden_layer_length]))
  biases1 = tf.Variable(tf.zeros([hidden_layer_length]))
  
  weights2 = tf.Variable(
    tf.truncated_normal([hidden_layer_length, num_labels]))
  biases2 = tf.Variable(tf.zeros([num_labels]))
  
  # Training computation.
  train_logits1 = tf.matmul(tf_train_dataset, weights1) + biases1
  train_activations1 = tf.nn.relu(train_logits1)
  dropped_train_activations1 = tf.nn.dropout(train_activations1, tf_dropout_keep_prob)
  dropped_train_logits2 = tf.matmul(dropped_train_activations1, weights2) + biases2
  
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(dropped_train_logits2, tf_train_labels)) + \
    tf_regularization_factor1*tf.nn.l2_loss(weights1) + \
    tf_regularization_factor2*tf.nn.l2_loss(weights2)
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  undropped_train_logits2 = tf.matmul(train_activations1, weights2) + biases2
  train_prediction = tf.nn.softmax(undropped_train_logits2)
  
  valid_logits1 = tf.matmul(tf_valid_dataset, weights1) + biases1
  valid_activations1 = tf.nn.relu(valid_logits1)
  valid_logits2 = tf.matmul(valid_activations1, weights2) + biases2
  valid_prediction = tf.nn.softmax(valid_logits2)
  
  test_logits1 = tf.matmul(tf_test_dataset, weights1) + biases1
  test_activations1 = tf.nn.relu(test_logits1)
  test_logits2 = tf.matmul(test_activations1, weights2) + biases2
  test_prediction = tf.nn.softmax(test_logits2)

In [ ]:
num_steps = 3000
furthest_training_example_idx = 1000

with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps+1):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (furthest_training_example_idx - 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("Train accuracy: %.1f%%" % accuracy(train_prediction.eval(), train_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

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)



In [ ]: