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 [3]:
# 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 [4]:
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 [5]:
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 [6]:
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 [8]:
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)
  
  # Variables.
  weights1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, 1024]))
  biases1 = tf.Variable(tf.zeros([1024]))

  hidden1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights1) + biases1)

  weights2 = tf.Variable(
    tf.truncated_normal([1024, num_labels]))
  biases2 = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  logits = tf.matmul(hidden1, weights2) + biases2
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1) +
                  tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2))
  loss += 5e-4 * regularizers
  
  # 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.nn.relu(tf.matmul(tf_valid_dataset, weights1) + biases1),
                                   weights2) + biases2)
  test_prediction = tf.nn.softmax(tf.matmul(tf.nn.relu(tf.matmul(tf_test_dataset, weights1) + biases1),
                                   weights2) + biases2)

num_steps = 3001

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


Initialized
Minibatch loss at step 0: 536.109680
Minibatch accuracy: 6.2%
Validation accuracy: 30.0%
Minibatch loss at step 500: 131.098511
Minibatch accuracy: 84.4%
Validation accuracy: 80.9%
Minibatch loss at step 1000: 101.360031
Minibatch accuracy: 75.8%
Validation accuracy: 81.3%
Minibatch loss at step 1500: 75.253151
Minibatch accuracy: 89.8%
Validation accuracy: 81.8%
Minibatch loss at step 2000: 56.973488
Minibatch accuracy: 87.5%
Validation accuracy: 82.8%
Minibatch loss at step 2500: 44.524899
Minibatch accuracy: 85.2%
Validation accuracy: 83.5%
Minibatch loss at step 3000: 34.320892
Minibatch accuracy: 82.0%
Validation accuracy: 84.2%
Test accuracy: 91.0%

Problem 2

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



In [8]:
batch_size = 12
SEED = 66478


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, 1024]))
  biases1 = tf.Variable(tf.zeros([1024]))
  weights2 = tf.Variable(tf.truncated_normal([1024, num_labels]))
  biases2 = tf.Variable(tf.zeros([num_labels]))

  def model(data, train=False):
    hidden1 = tf.nn.relu(tf.matmul(data, weights1) + biases1)
    return tf.matmul(hidden1, weights2) + biases2



  # Training computation.
  logits = model(tf_train_dataset, True)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1) +
                  tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2))
  loss += 5e-4 * regularizers
  
  # 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(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))


num_steps = 3001

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


Initialized
Minibatch loss at step 0: 479.049835
Minibatch accuracy: 0.0%
Validation accuracy: 20.1%
Minibatch loss at step 500: 499.082642
Minibatch accuracy: 58.3%
Validation accuracy: 53.7%
Minibatch loss at step 1000: 390.921783
Minibatch accuracy: 66.7%
Validation accuracy: 57.1%
Minibatch loss at step 1500: 908.511719
Minibatch accuracy: 66.7%
Validation accuracy: 58.9%
Minibatch loss at step 2000: 787.659668
Minibatch accuracy: 58.3%
Validation accuracy: 49.0%
Minibatch loss at step 2500: 320.798096
Minibatch accuracy: 33.3%
Validation accuracy: 51.1%
Minibatch loss at step 3000: 297.437286
Minibatch accuracy: 75.0%
Validation accuracy: 56.0%
Test accuracy: 61.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 [18]:
batch_size = 12
SEED = 66478


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, 1024]))
  biases1 = tf.Variable(tf.zeros([1024]))
  weights2 = tf.Variable(tf.truncated_normal([1024, num_labels]))
  biases2 = tf.Variable(tf.zeros([num_labels]))

  def model(data, train=False):
    hidden1 = tf.nn.relu(tf.matmul(data, weights1) + biases1)
    if train:
      hidden1 = tf.nn.dropout(hidden1, 0.5, seed=SEED)
    return tf.matmul(hidden1, weights2) + biases2


  # Training computation.
  logits = model(tf_train_dataset, True)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1) +
                  tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2))
  loss += 5e-4 * regularizers
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  
  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))


num_steps = 3001

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


Initialized
Minibatch loss at step 0: 868.424683
Minibatch accuracy: 0.0%
Validation accuracy: 17.8%
Minibatch loss at step 500: 320.267517
Minibatch accuracy: 66.7%
Validation accuracy: 74.5%
Minibatch loss at step 1000: 212.855942
Minibatch accuracy: 83.3%
Validation accuracy: 74.8%
Minibatch loss at step 1500: 147.227631
Minibatch accuracy: 100.0%
Validation accuracy: 76.8%
Minibatch loss at step 2000: 353.915588
Minibatch accuracy: 66.7%
Validation accuracy: 77.4%
Minibatch loss at step 2500: 186.228287
Minibatch accuracy: 66.7%
Validation accuracy: 77.7%
Minibatch loss at step 3000: 261.168182
Minibatch accuracy: 66.7%
Validation accuracy: 76.7%
Test accuracy: 83.3%

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, step, ...)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)



In [35]:
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)  

  # Variables.
  weights1 = tf.Variable(tf.truncated_normal([image_size * image_size, 1024]))
  biases1 = tf.Variable(tf.zeros([1024]))
  weights2 = tf.Variable(tf.truncated_normal([1024, 1024]))
  biases2 = tf.Variable(tf.zeros([1024]))
  weights3 = tf.Variable(tf.truncated_normal([1024, num_labels]))
  biases3 = tf.Variable(tf.zeros([num_labels]))

  def model(data, train=False):
    hidden1 = tf.nn.relu(tf.matmul(data, weights1) + biases1)
    if train:
      hidden1 = tf.nn.dropout(hidden1, 0.7, seed=SEED)
    hidden2 = tf.matmul(hidden1, weights2) + biases2
    if train:
      hidden2 = tf.nn.dropout(hidden2, 0.7, seed=SEED)
    return tf.matmul(hidden2, weights3) + biases3

  # Training computation.
  logits = model(tf_train_dataset, True)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
  # L2 regularization for the fully connected parameters.
  regularizers = (tf.nn.l2_loss(weights1) + tf.nn.l2_loss(biases1)
                  + tf.nn.l2_loss(weights2) + tf.nn.l2_loss(biases2)
                  + tf.nn.l2_loss(weights3) + tf.nn.l2_loss(biases3))
  loss += 5e-4 * regularizers
  
  # Optimizer.
  global_step = tf.Variable(0)  # count the number of steps taken.
  learning_rate = tf.train.exponential_decay(0.01, step, 3000, 0.5, 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)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))


num_steps = 3001

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


Initialized
Minibatch loss at step 0: 13673.852539
Minibatch accuracy: 12.5%
Validation accuracy: 25.5%
Minibatch loss at step 500: 867.041565
Minibatch accuracy: 78.9%
Validation accuracy: 81.0%
Minibatch loss at step 1000: 702.076416
Minibatch accuracy: 72.7%
Validation accuracy: 80.6%
Minibatch loss at step 1500: 743.617981
Minibatch accuracy: 75.0%
Validation accuracy: 80.0%
Minibatch loss at step 2000: 576.072144
Minibatch accuracy: 80.5%
Validation accuracy: 80.5%
Minibatch loss at step 2500: 504.398926
Minibatch accuracy: 75.8%
Validation accuracy: 80.1%
Minibatch loss at step 3000: 464.087555
Minibatch accuracy: 69.5%
Validation accuracy: 79.8%
Test accuracy: 87.7%

In [ ]: