Deep Learning

Assignment 2

Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset.

The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow. We will do this in the three following steps:

  • We will start with implementing simple linear regression in tensorflow.
  • We will implement stochastic gradient decent to calculate the coefficients of the linear regression classifier.
  • We will train a neural network classifier with one fully connected hidden layer.

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
from six.moves import range
import os

First reload the data we generated in 1_notmnist.ipynb.


In [3]:
# Create data directory path
dpath = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
dpath = os.path.join(dpath, 'data')
# create pickle data file path
pickle_file = os.path.join(dpath,'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 (500000, 28, 28) (500000,)
Validation set (29000, 28, 28) (29000,)
Test set (18000, 28, 28) (18000,)

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 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.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 (500000, 784) (500000, 10)
Validation set (29000, 784) (29000, 10)
Test set (18000, 784) (18000, 10)

In [5]:
# Testing data transformations!
test1 = train_labels[1:6]
print(test1.shape)
t2 = (np.arange(num_labels) == test1[:,None]).astype(np.float32)
print(t2.shape)


(5, 10)
(5, 1, 10)

We're first going to train a multinomial logistic regression using simple gradient descent.

TensorFlow works like this:

  • First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description is all contained within the block below:

    with graph.as_default():
        ...
  • Then you can run the operations on this graph as many times as you want by calling session.run(), providing it outputs to fetch from the graph that get returned. This runtime operation is all contained in the block below:

    with tf.Session(graph=graph) as session:
        ...

Let's load all the data into TensorFlow and build the computation graph corresponding to our training:


In [6]:
# With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
train_subset = 10000

graph = tf.Graph()
with graph.as_default():

    # Input data.
    # Load the training, validation and test data into constants that are
    # attached to the graph.
    tf_train_dataset = tf.constant(train_dataset[:train_subset, :])
    tf_train_labels = tf.constant(train_labels[:train_subset])
    tf_valid_dataset = tf.constant(valid_dataset)
    tf_test_dataset = tf.constant(test_dataset)
  
    # Variables.
    # These are the parameters that we are going to be training. The weight
    # matrix will be initialized using random values following a (truncated)
    # normal distribution. The biases get initialized to zero.
    weights = tf.Variable(
        tf.truncated_normal([image_size * image_size, num_labels]))
    biases = tf.Variable(tf.zeros([num_labels]))
  
    # Training computation.
    # We multiply the inputs with the weight matrix, and add biases. We compute
    # the softmax and cross-entropy (it's one operation in TensorFlow, because
    # it's very common, and it can be optimized). We take the average of this
    # cross-entropy across all training examples: that's our loss.
    logits = tf.matmul(tf_train_dataset, weights) + biases
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(
            labels = tf_train_labels,
            logits = logits))
  
    # Optimizer.
    # We are going to find the minimum of this loss using gradient descent.
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    # Predictions for the training, validation, and test data.
    # These are not part of training, but merely here so that we can report
    # accuracy figures as we train.
    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)

Let's run this computation and iterate:


In [7]:
num_steps = 801

def accuracy(predictions, labels):
    # Sums num of correct predictions per total data_points.
    return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

with tf.Session(graph=graph) as session:
    # This is a one-time operation which ensures the parameters get initialized as
    # we described in the graph: random weights for the matrix, zeros for the
    # biases. 
    tf.global_variables_initializer().run()
    print('Initialized')
    for step in range(num_steps):
        # Run the computations. We tell .run() that we want to run the optimizer,
        # and get the loss value and the training predictions returned as numpy
        # arrays.
        _, l, predictions = session.run([optimizer, loss, train_prediction])
        if (step % 100 == 0):
            print('Loss at step %d: %f' % (step, l))
            print('Training accuracy: %.1f%%' % accuracy(
            predictions, train_labels[:train_subset, :]))
            # Calling .eval() on valid_prediction is basically like calling run(), but
            # just to get that one numpy array. Note that it recomputes all its graph
            # dependencies.
            print('Validation accuracy: %.1f%%' % accuracy(
                valid_prediction.eval(), valid_labels))
    print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))


Initialized
Loss at step 0: 16.202929
Training accuracy: 12.9%
Validation accuracy: 16.4%
Loss at step 100: 2.362511
Training accuracy: 71.2%
Validation accuracy: 70.7%
Loss at step 200: 1.899688
Training accuracy: 74.3%
Validation accuracy: 73.1%
Loss at step 300: 1.651105
Training accuracy: 75.6%
Validation accuracy: 73.9%
Loss at step 400: 1.485163
Training accuracy: 76.3%
Validation accuracy: 74.3%
Loss at step 500: 1.362860
Training accuracy: 77.1%
Validation accuracy: 74.5%
Loss at step 600: 1.267497
Training accuracy: 77.6%
Validation accuracy: 74.6%
Loss at step 700: 1.190369
Training accuracy: 78.1%
Validation accuracy: 74.7%
Loss at step 800: 1.126213
Training accuracy: 78.6%
Validation accuracy: 74.9%
Test accuracy: 82.7%

Let's now switch to stochastic gradient descent training instead, which is much faster.

The graph will be similar, except that instead of holding all the training data into a constant node, we create a Placeholder node which will be fed actual data at every call of session.run().


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.
    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(labels=tf_train_labels, logits=logits))
  
    # 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)

Let's run it:


In [9]:
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.529678
Minibatch accuracy: 7.8%
Validation accuracy: 10.5%
Minibatch loss at step 500: 1.588616
Minibatch accuracy: 79.7%
Validation accuracy: 75.8%
Minibatch loss at step 1000: 1.328140
Minibatch accuracy: 75.0%
Validation accuracy: 75.9%
Minibatch loss at step 1500: 0.980198
Minibatch accuracy: 78.9%
Validation accuracy: 76.9%
Minibatch loss at step 2000: 1.039457
Minibatch accuracy: 77.3%
Validation accuracy: 77.9%
Minibatch loss at step 2500: 1.052840
Minibatch accuracy: 80.5%
Validation accuracy: 78.4%
Minibatch loss at step 3000: 1.028807
Minibatch accuracy: 82.8%
Validation accuracy: 79.0%
Test accuracy: 86.3%

Question: What exactly did we do differently between the two implemenations?

On the first implementation we started with a subset of the training set that entered the graph as constant. On the second implementation the tf.placeholder type is used that uses only the batch size as "width". The smaller width allows for easier/faster matrix multiplication.

The key difference here is the use of the placeholder type minimising the dimension of matrices to be multiplied (and derivatives to be calculated).


Problem

Turn the logistic regression example with SGD into a 1-hidden layer neural network with rectified linear units nn.relu() and 1024 hidden nodes. This model should improve your validation / test accuracy.


Notes:

  • We want a 1-hidden layer network.
  • The input layer is usually not counted against the number of layers

In [10]:
batch_size = 128
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 - Network Construction!
    # Matrix Dimensions:
    # 1st argument has dimensions coming from previous layer
    # 2nd argument has dimensions going to the next layer == dim(bias)
    # We construct the variables representing the hidden layer:
    weights1 = tf.Variable(
        tf.truncated_normal([image_size * image_size, hidden_nodes]))
    biases1 = tf.Variable(tf.zeros([hidden_nodes]))
    # We construct the variables representing the output layer:
    weights2 = tf.Variable(
        tf.truncated_normal([hidden_nodes, num_labels]))
    biases2 = tf.Variable(tf.zeros([num_labels]))

    # Training computation.
    hidden_layer = tf.matmul(tf_train_dataset, weights1) + biases1
    logits = tf.matmul(hidden_layer, weights2) + biases2
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(
            labels=tf_train_labels, logits=logits))

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

    # Predictions for the training, validation, and test data.
    # Predict for training:
    train_prediction = tf.nn.softmax(logits)
    
    # Create Validation graph
    hidden_layer_val = tf.matmul(tf_valid_dataset, weights1) + biases1
    logits_val = tf.matmul(hidden_layer_val, weights2) + biases2
    # Predict for validation
    valid_prediction = tf.nn.softmax(logits_val)
    
    # Create Test graph
    hidden_layer_test = tf.matmul(tf_test_dataset, weights1) + biases1
    logits_test = tf.matmul(hidden_layer_test, weights2) + biases2
    # Predict for test
    test_prediction = tf.nn.softmax(logits_test)

In [11]:
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: 481.056335
Minibatch accuracy: 17.2%
Validation accuracy: 36.0%
Minibatch loss at step 500: 44.361320
Minibatch accuracy: 70.3%
Validation accuracy: 72.2%
Minibatch loss at step 1000: 38.004921
Minibatch accuracy: 70.3%
Validation accuracy: 73.2%
Minibatch loss at step 1500: 29.165146
Minibatch accuracy: 74.2%
Validation accuracy: 71.1%
Minibatch loss at step 2000: 42.998734
Minibatch accuracy: 62.5%
Validation accuracy: 69.6%
Minibatch loss at step 2500: 25.268459
Minibatch accuracy: 71.1%
Validation accuracy: 71.5%
Minibatch loss at step 3000: 29.094276
Minibatch accuracy: 69.5%
Validation accuracy: 74.0%
Test accuracy: 81.5%