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 [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 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 [4]:
def acc(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.


Logistic Regression


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)
  
  # 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
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss + 5e-4 * tf.nn.l2_loss(weights))
  
  # 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 = 10001

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 % 1000 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % acc(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % acc(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % acc(test_prediction.eval(), test_labels))


Initialized
Minibatch loss at step 0: 15.700172
Minibatch accuracy: 13.3%
Validation accuracy: 17.7%
Minibatch loss at step 1000: 1.047611
Minibatch accuracy: 80.5%
Validation accuracy: 77.4%
Minibatch loss at step 2000: 0.953297
Minibatch accuracy: 78.9%
Validation accuracy: 79.1%
Minibatch loss at step 3000: 0.735120
Minibatch accuracy: 79.7%
Validation accuracy: 80.9%
Minibatch loss at step 4000: 0.429398
Minibatch accuracy: 88.3%
Validation accuracy: 81.8%
Minibatch loss at step 5000: 0.827257
Minibatch accuracy: 80.5%
Validation accuracy: 81.6%
Minibatch loss at step 6000: 0.562103
Minibatch accuracy: 82.0%
Validation accuracy: 81.3%
Minibatch loss at step 7000: 0.628133
Minibatch accuracy: 80.5%
Validation accuracy: 82.2%
Minibatch loss at step 8000: 0.783334
Minibatch accuracy: 81.2%
Validation accuracy: 80.9%
Minibatch loss at step 9000: 0.566038
Minibatch accuracy: 81.2%
Validation accuracy: 82.2%
Minibatch loss at step 10000: 0.706487
Minibatch accuracy: 84.4%
Validation accuracy: 82.0%
Test accuracy: 88.5%

Neural Network (1 hidden layer)


In [7]:
batch_size = 128
num_hidden = 2048

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.
  x = tf.placeholder(tf.float32, shape=(None, image_size * image_size))
  y_ = tf.placeholder(tf.float32, shape=(None, num_labels))
  keep_prob = tf.placeholder('float')
    
  # Variables. (Input -> Hidden)
  w_1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_hidden]))
  b_1 = tf.Variable(tf.zeros([num_hidden]))

  # Training computation. (Input -> Hidden)
  h_1 = tf.nn.dropout(tf.nn.relu(tf.matmul(x, w_1) + b_1), 0.5)
  
  # Variables. (Hidden -> Output)
  w_2 = tf.Variable(
    tf.truncated_normal([num_hidden, num_labels]))
  b_2 = tf.Variable(tf.zeros([num_labels]))
    
  # Training computation. (Hidden -> Output)
  h_2 = tf.matmul(h_1, w_2) + b_2
  
  # Loss
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(h_2, y_))
  
  # Optimizer.
  optimizer = tf.train.AdagradOptimizer(1e-3).minimize(loss + 5e-4 * (tf.nn.l2_loss(w_1) + tf.nn.l2_loss(w_2)))
  
  # Predictions for the training, validation, and test data.
  prediction = tf.nn.softmax(h_2)

  correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))

In [8]:
num_steps = 30001

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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
    _, l = session.run(
      [optimizer, loss], feed_dict=feed_dict)
    if (step % 2000 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
  print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))


Initialized
Minibatch loss at step 0: 666.305664
Validation accuracy: 10.9%
Minibatch loss at step 2000: 219.845444
Validation accuracy: 60.7%
Minibatch loss at step 4000: 111.434731
Validation accuracy: 65.0%
Minibatch loss at step 6000: 134.186325
Validation accuracy: 67.8%
Minibatch loss at step 8000: 167.049652
Validation accuracy: 69.3%
Minibatch loss at step 10000: 148.302643
Validation accuracy: 70.1%
Minibatch loss at step 12000: 128.502075
Validation accuracy: 70.4%
Minibatch loss at step 14000: 114.258560
Validation accuracy: 70.9%
Minibatch loss at step 16000: 139.722672
Validation accuracy: 71.4%
Minibatch loss at step 18000: 97.424637
Validation accuracy: 71.7%
Minibatch loss at step 20000: 71.895927
Validation accuracy: 72.2%
Minibatch loss at step 22000: 111.910652
Validation accuracy: 72.5%
Minibatch loss at step 24000: 105.544632
Validation accuracy: 72.7%
Minibatch loss at step 26000: 87.480385
Validation accuracy: 73.4%
Minibatch loss at step 28000: 95.903397
Validation accuracy: 73.4%
Minibatch loss at step 30000: 109.879532
Validation accuracy: 73.7%
Test accuracy: 80.8%

Problem 2

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


Oviously, the model is overfitted


In [9]:
num_steps = 30001
train_data_size = 1000

part_train_dataset = train_dataset[:train_data_size, :]
part_train_labels = train_labels[:train_data_size]

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) % (part_train_labels.shape[0] - batch_size)
    # Generate a minibatch.
    batch_data = part_train_dataset[offset:(offset + batch_size), :]
    batch_labels = part_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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
    _, l = session.run(
      [optimizer, loss], feed_dict=feed_dict)
    if (step % 2000 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
  print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))


Initialized
Minibatch loss at step 0: 667.905762
Validation accuracy: 8.1%
Minibatch loss at step 2000: 128.714310
Validation accuracy: 58.2%
Minibatch loss at step 4000: 72.877907
Validation accuracy: 63.0%
Minibatch loss at step 6000: 77.184540
Validation accuracy: 64.5%
Minibatch loss at step 8000: 63.037251
Validation accuracy: 66.1%
Minibatch loss at step 10000: 33.229725
Validation accuracy: 67.7%
Minibatch loss at step 12000: 40.965000
Validation accuracy: 68.1%
Minibatch loss at step 14000: 52.464226
Validation accuracy: 67.9%
Minibatch loss at step 16000: 35.694748
Validation accuracy: 69.2%
Minibatch loss at step 18000: 21.793943
Validation accuracy: 69.4%
Minibatch loss at step 20000: 24.060169
Validation accuracy: 69.3%
Minibatch loss at step 22000: 11.778533
Validation accuracy: 69.6%
Minibatch loss at step 24000: 35.231609
Validation accuracy: 69.7%
Minibatch loss at step 26000: 30.743317
Validation accuracy: 69.9%
Minibatch loss at step 28000: 19.866440
Validation accuracy: 70.2%
Minibatch loss at step 30000: 15.725492
Validation accuracy: 70.5%
Test accuracy: 77.3%

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?



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)


  • 2 hidden layers (2048, 1024)
  • dropout on both hidden layers
  • L2 regularization

In [10]:
batch_size = 128
num_hidden_1 = 2048
num_hidden_2 = 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.
  x = tf.placeholder(tf.float32, shape=(None, image_size * image_size))
  y_ = tf.placeholder(tf.float32, shape=(None, num_labels))
  keep_prob = tf.placeholder('float')
    
  # Input -> Hidden1
  w_1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_hidden_1]))
  b_1 = tf.Variable(tf.zeros([num_hidden_1]))
  h_1 = tf.nn.dropout(tf.nn.relu(tf.matmul(x, w_1) + b_1), keep_prob)
    
  # Hidden1 -> Hidden2
  w_2 = tf.Variable(
    tf.truncated_normal([num_hidden_1, num_hidden_2]))
  b_2 = tf.Variable(tf.zeros([num_hidden_2]))
  h_2 = tf.nn.dropout(tf.nn.relu(tf.matmul(h_1, w_2) + b_2), keep_prob)
  
  # Hidden2 -> Output
  w_3 = tf.Variable(
    tf.truncated_normal([num_hidden_2, num_labels]))
  b_3 = tf.Variable(tf.zeros([num_labels]))
  h_3 = tf.matmul(h_2, w_3) + b_3
  
  # Loss
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(h_3, y_))
  
  # Optimizer.
  optimizer = tf.train.AdagradOptimizer(1e-3).minimize(loss + 1e-5 * (tf.nn.l2_loss(w_1) + tf.nn.l2_loss(w_2) + tf.nn.l2_loss(w_3)))
  
  # Predictions for the training, validation, and test data.
  prediction = tf.nn.softmax(h_3)

  correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))

In [11]:
num_steps = 30001

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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
    _, l = session.run(
      [optimizer, loss], feed_dict=feed_dict)
    if (step % 2000 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
  print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))


Initialized
Minibatch loss at step 0: 16843.279297
Validation accuracy: 13.5%
Minibatch loss at step 2000: 5620.586426
Validation accuracy: 76.4%
Minibatch loss at step 4000: 3942.778076
Validation accuracy: 78.2%
Minibatch loss at step 6000: 3085.673096
Validation accuracy: 79.2%
Minibatch loss at step 8000: 4248.289062
Validation accuracy: 79.6%
Minibatch loss at step 10000: 3506.438477
Validation accuracy: 79.9%
Minibatch loss at step 12000: 3245.044922
Validation accuracy: 80.2%
Minibatch loss at step 14000: 4125.744141
Validation accuracy: 80.4%
Minibatch loss at step 16000: 3333.512207
Validation accuracy: 80.6%
Minibatch loss at step 18000: 2453.872070
Validation accuracy: 80.8%
Minibatch loss at step 20000: 2277.604492
Validation accuracy: 81.0%
Minibatch loss at step 22000: 3556.410156
Validation accuracy: 81.2%
Minibatch loss at step 24000: 2105.003174
Validation accuracy: 81.2%
Minibatch loss at step 26000: 2753.843506
Validation accuracy: 81.3%
Minibatch loss at step 28000: 1755.736938
Validation accuracy: 81.4%
Minibatch loss at step 30000: 3162.377441
Validation accuracy: 81.4%
Test accuracy: 88.1%