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


/Users/vikas/workspace/scikit-learn/sklearn/cross_validation.py:42: DeprecationWarning: This module has been deprecated in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
  "This module will be removed in 0.20.", DeprecationWarning)

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 [14]:
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.


L2 for logistic model


In [25]:
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
    beta = 0.001
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) + beta * 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)

Actual training


In [18]:
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: 49.613205
Minibatch accuracy: 10.2%
Validation accuracy: 12.3%
Minibatch loss at step 500: 0.962167
Minibatch accuracy: 78.9%
Validation accuracy: 81.0%
Minibatch loss at step 1000: 0.794880
Minibatch accuracy: 78.9%
Validation accuracy: 81.4%
Minibatch loss at step 1500: 0.586098
Minibatch accuracy: 83.6%
Validation accuracy: 81.5%
Minibatch loss at step 2000: 0.731017
Minibatch accuracy: 81.2%
Validation accuracy: 80.5%
Minibatch loss at step 2500: 0.964740
Minibatch accuracy: 78.1%
Validation accuracy: 82.0%
Minibatch loss at step 3000: 0.782584
Minibatch accuracy: 78.9%
Validation accuracy: 81.3%
Test accuracy: 87.4%

Results

Without L2:

Validation accuracy: 79.2%
Test accuracy: 86.4%

With L2, β=2:

Validation accuracy: 30.4%
Test accuracy: 32.5%

β = 0.01:

Validation accuracy: 81.3%
Test accuracy: 87.4%

L2 for neural network model

Graph:


In [29]:
batch_size = 128
num_hidden_nodes = 1024

g = tf.Graph()
with g.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, input layer
    w1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_hidden_nodes]))
    b1 = tf.Variable(tf.zeros([num_hidden_nodes]))

    # Variables, output layer
    w2 = tf.Variable(tf.truncated_normal([num_hidden_nodes, num_labels]))
    b2 = tf.Variable(tf.zeros([num_labels]))

    # Forward propagation
    # To get the prediction, apply softmax to the output of this
    def forward_prop(dataset, w1, b1, w2, b2):
        o1 = tf.matmul(dataset, w1) + b1
        output_hidden = tf.nn.relu(o1)
        return tf.matmul(output_hidden, w2) + b2

    train_output = forward_prop(tf_train_dataset, w1, b1, w2, b2)

    beta = 0.01
    loss = tf.reduce_mean(
                tf.nn.softmax_cross_entropy_with_logits(train_output, tf_train_labels)) + beta * (tf.nn.l2_loss(w1) + tf.nn.l2_loss(w2))

    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(train_output)
    valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset, w1, b1, w2, b2))
    test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset, w1, b1, w2, b2))

Training the network:


In [33]:
num_steps = 3001

with tf.Session(graph=g) 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) % (small_labels.shape[0] - batch_size)

        # Generate a minibatch.
        batch_data = small_dataset[offset:(offset + batch_size), :]
        batch_labels = small_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: 3451.111328
Minibatch accuracy: 5.5%
Validation accuracy: 30.9%
Minibatch loss at step 500: 20.658495
Minibatch accuracy: 100.0%
Validation accuracy: 74.4%
Minibatch loss at step 1000: 0.148731
Minibatch accuracy: 100.0%
Validation accuracy: 77.3%
Minibatch loss at step 1500: 0.010275
Minibatch accuracy: 100.0%
Validation accuracy: 77.4%
Minibatch loss at step 2000: 0.008375
Minibatch accuracy: 100.0%
Validation accuracy: 77.6%
Minibatch loss at step 2500: 0.007392
Minibatch accuracy: 100.0%
Validation accuracy: 77.7%
Minibatch loss at step 3000: 0.007072
Minibatch accuracy: 100.0%
Validation accuracy: 77.7%
Test accuracy: 84.8%

Problem 2

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



In [32]:
# use only 4 batches
small_dataset = train_dataset[0:128*4, :]
small_labels = train_labels[0:128*4, :]

Answer: The minibatch accuracy is very good but both validation and test accuracy are much lower.

Minibatch accuracy: 89.8%
Validation accuracy: 51.8%
Test accuracy: 58.5%

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 [31]:
# With support for dropout

batch_size = 128
num_hidden_nodes = 1024

g = tf.Graph()
with g.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, input layer
    w1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_hidden_nodes]))
    b1 = tf.Variable(tf.zeros([num_hidden_nodes]))

    # Variables, output layer
    w2 = tf.Variable(tf.truncated_normal([num_hidden_nodes, num_labels]))
    b2 = tf.Variable(tf.zeros([num_labels]))

    # Forward propagation
    # To get the prediction, apply softmax to the output of this
    def forward_prop(dataset, w1, b1, w2, b2, dropout=False):
        o1 = tf.matmul(dataset, w1) + b1
        output_hidden = tf.nn.relu(o1)
        if dropout:
            output_hidden = tf.nn.dropout(output_hidden, 0.5)
        return tf.matmul(output_hidden, w2) + b2

    train_output = forward_prop(tf_train_dataset, w1, b1, w2, b2)

    beta = 0.01
    loss = tf.reduce_mean(
                tf.nn.softmax_cross_entropy_with_logits(train_output, tf_train_labels)) + beta * tf.nn.l2_loss(w1)

    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(train_output)
    valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset, w1, b1, w2, b2))
    test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset, w1, b1, w2, b2))

Accuracy goes up slightly with dropout (and no regularization):

Minibatch accuracy: 93.8%
Validation accuracy: 54.1%
Test accuracy: 61.3%

With both L2 and dropout:

Minibatch accuracy: 96.9%
Validation accuracy: 74.8%
Test accuracy: 82.0%

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)


Final model

First let's setup a multi-layer network.


In [120]:
# With support for dropout

batch_size = 128

num_hidden_nodes_1 = 1024
num_hidden_nodes_2 = 300

g = tf.Graph()
with g.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)

    # transform input layer -> hidden layer 1
    w1 = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_hidden_nodes_1]))
    b1 = tf.Variable(tf.zeros([num_hidden_nodes_1]))

    # transform hidden layer 1 -> hidden layer 2
    w2 = tf.Variable(tf.truncated_normal([num_hidden_nodes_1, num_hidden_nodes_2]))
    b2 = tf.Variable(tf.zeros([num_hidden_nodes_2]))
    
    # transform hidden layer 2 -> output layer
    w3 = tf.Variable(tf.truncated_normal([num_hidden_nodes_2, num_labels]))
    b3 = tf.Variable(tf.zeros([num_labels]))

    # Forward propagation
    # To get the prediction, apply softmax to the output of this
    def forward_prop(dataset, w1, b1, w2, b2, w3, b3, dropout=False):
        o1 = tf.nn.tanh(tf.matmul(dataset, w1) + b1)
        o2 = tf.nn.tanh(tf.matmul(o1, w2) + b2)
        if dropout:
            o1 = tf.nn.dropout(o1, 0.5)
        return tf.matmul(o2, w3) + b3

    train_output = forward_prop(tf_train_dataset, w1, b1, w2, b2, w3, b3)

    beta = 0.005
    loss = tf.reduce_mean(
                tf.nn.softmax_cross_entropy_with_logits(train_output, tf_train_labels)) + beta * (tf.nn.l2_loss(w1) + tf.nn.l2_loss(w2))
    
    p = tf.Print(loss, [loss])
    
    global_step = tf.Variable(0)
    learning_rate = tf.train.exponential_decay(0.1, global_step, 500, 0.96)
    
    # Optimizer.
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(p, global_step=global_step)

    # Predictions for the training, validation, and test data.
    train_prediction = tf.nn.softmax(train_output)
    valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset, w1, b1, w2, b2, w3, b3))
    test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset, w1, b1, w2, b2, w3, b3))

Train the final model


In [121]:
num_steps = 9001

with tf.Session(graph=g) 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: 2169.328125
Minibatch accuracy: 15.6%
Validation accuracy: 14.0%
Minibatch loss at step 500: 1319.655029
Minibatch accuracy: 77.3%
Validation accuracy: 72.1%
Minibatch loss at step 1000: 826.176025
Minibatch accuracy: 71.1%
Validation accuracy: 74.6%
Minibatch loss at step 1500: 525.589844
Minibatch accuracy: 80.5%
Validation accuracy: 76.1%
Minibatch loss at step 2000: 341.485352
Minibatch accuracy: 75.8%
Validation accuracy: 76.4%
Minibatch loss at step 2500: 225.701569
Minibatch accuracy: 80.5%
Validation accuracy: 77.9%
Minibatch loss at step 3000: 151.358444
Minibatch accuracy: 76.6%
Validation accuracy: 79.0%
Minibatch loss at step 3500: 103.515404
Minibatch accuracy: 83.6%
Validation accuracy: 80.1%
Minibatch loss at step 4000: 72.123138
Minibatch accuracy: 78.1%
Validation accuracy: 81.1%
Minibatch loss at step 4500: 50.383839
Minibatch accuracy: 88.3%
Validation accuracy: 81.8%
Minibatch loss at step 5000: 36.327045
Minibatch accuracy: 80.5%
Validation accuracy: 82.8%
Minibatch loss at step 5500: 26.584269
Minibatch accuracy: 80.5%
Validation accuracy: 83.6%
Minibatch loss at step 6000: 19.379429
Minibatch accuracy: 85.9%
Validation accuracy: 84.4%
Minibatch loss at step 6500: 14.606010
Minibatch accuracy: 84.4%
Validation accuracy: 84.5%
Minibatch loss at step 7000: 11.067955
Minibatch accuracy: 85.2%
Validation accuracy: 85.1%
Minibatch loss at step 7500: 8.338758
Minibatch accuracy: 86.7%
Validation accuracy: 85.2%
Minibatch loss at step 8000: 6.547828
Minibatch accuracy: 89.1%
Validation accuracy: 85.1%
Minibatch loss at step 8500: 5.327626
Minibatch accuracy: 88.3%
Validation accuracy: 85.2%
Minibatch loss at step 9000: 4.332844
Minibatch accuracy: 84.4%
Validation accuracy: 85.8%
Test accuracy: 92.2%