Deep Learning

Assignment 4

Previously in 2_fullyconnected.ipynb and 3_regularization.ipynb, we trained fully connected networks to classify notMNIST characters.

The goal of this assignment is make the neural network convolutional.


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 time
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range

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 (80000, 28, 28) (80000,)
Validation set (10000, 28, 28) (10000,)
Test set (10000, 28, 28) (10000,)

Reformat into a TensorFlow-friendly shape:

  • convolutions need the image data formatted as a cube (width by height by #channels)
  • labels as float 1-hot encodings.

In [3]:
image_size = 28
num_labels = 10
num_channels = 1 # grayscale

import numpy as np

def reformat(dataset, labels):
  dataset = dataset.reshape(
    (-1, image_size, image_size, num_channels)).astype(np.float32)
  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 (80000, 28, 28, 1) (80000, 10)
Validation set (10000, 28, 28, 1) (10000, 10)
Test set (10000, 28, 28, 1) (10000, 10)

In [4]:
def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.


In [5]:
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  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.
  layer1_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal(
      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
  
  # Model.
  def model(data):
    # cnn-input: 16 x 28 x 28 x 1, num_samples = 16
    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
    # cnn-hidden: 16 x (14 x 14 x 16)
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    # cnn-hidden: 16 x 7 x 7 x 16
    hidden = tf.nn.relu(conv + layer2_biases)
    shape = hidden.get_shape().as_list()
    # num_features = 7 x 7 x 16
    # num_samples = 16
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    # fnn-hidden: matmul(16 x (7 x 7 x 16), (28 // 4 x 28 // 4 x 16, 64))
    # fnn-hidden: num_features = 64
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    # num_labels = 10
    # fnn-output: matmul(16 x 64, 64 x 10) = (16, 10)
    return tf.matmul(hidden, layer4_weights) + layer4_biases
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).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))

In [6]:
num_steps = 1001

with tf.Session(graph=graph) as session:
  tic = time.time()
  try:
    tf.global_variables_initializer().run()
  except AttributeError:
    tf.initialize_all_variables().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    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 % 50 == 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))
  print("Time: %.3f s" % (time.time() - tic))


Initialized
Minibatch loss at step 0: 3.447666
Minibatch accuracy: 6.2%
Validation accuracy: 10.0%
Minibatch loss at step 50: 1.481667
Minibatch accuracy: 37.5%
Validation accuracy: 52.6%
Minibatch loss at step 100: 0.558262
Minibatch accuracy: 87.5%
Validation accuracy: 74.5%
Minibatch loss at step 150: 0.772902
Minibatch accuracy: 75.0%
Validation accuracy: 76.7%
Minibatch loss at step 200: 0.736860
Minibatch accuracy: 93.8%
Validation accuracy: 77.2%
Minibatch loss at step 250: 1.126316
Minibatch accuracy: 68.8%
Validation accuracy: 79.2%
Minibatch loss at step 300: 0.439427
Minibatch accuracy: 81.2%
Validation accuracy: 77.9%
Minibatch loss at step 350: 0.895194
Minibatch accuracy: 75.0%
Validation accuracy: 80.3%
Minibatch loss at step 400: 0.566359
Minibatch accuracy: 87.5%
Validation accuracy: 81.0%
Minibatch loss at step 450: 0.582143
Minibatch accuracy: 81.2%
Validation accuracy: 81.1%
Minibatch loss at step 500: 0.508623
Minibatch accuracy: 81.2%
Validation accuracy: 79.9%
Minibatch loss at step 550: 0.243743
Minibatch accuracy: 93.8%
Validation accuracy: 80.8%
Minibatch loss at step 600: 0.483945
Minibatch accuracy: 75.0%
Validation accuracy: 80.2%
Minibatch loss at step 650: 0.791135
Minibatch accuracy: 81.2%
Validation accuracy: 81.1%
Minibatch loss at step 700: 0.535627
Minibatch accuracy: 81.2%
Validation accuracy: 81.8%
Minibatch loss at step 750: 0.735979
Minibatch accuracy: 81.2%
Validation accuracy: 80.4%
Minibatch loss at step 800: 0.962221
Minibatch accuracy: 68.8%
Validation accuracy: 82.5%
Minibatch loss at step 850: 0.263385
Minibatch accuracy: 93.8%
Validation accuracy: 82.3%
Minibatch loss at step 900: 0.525500
Minibatch accuracy: 87.5%
Validation accuracy: 82.9%
Minibatch loss at step 950: 0.298817
Minibatch accuracy: 87.5%
Validation accuracy: 82.8%
Minibatch loss at step 1000: 1.021847
Minibatch accuracy: 62.5%
Validation accuracy: 82.2%
Test accuracy: 89.8%
Time: 23.785 s

Problem 1

The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (nn.max_pool()) of stride 2 and kernel size 2.



In [11]:
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
num_steps = 1001

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  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.
  layer1_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, num_channels, depth], stddev=0.1))
  layer1_biases = tf.Variable(tf.zeros([depth]))
  layer2_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, depth, depth], stddev=0.1))
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))
  layer3_weights = tf.Variable(tf.truncated_normal(
      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))
  layer4_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
  
  # Model.
  def model(data):
    # cnn-input: max_pooling, kernel_size = 2, strides = 2
    conv = tf.nn.max_pool(data, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    # cnn-hidden: 16 x (14 x 14 x 16)
    # arithmetic: (i - k) / s + 1 = (28 - 2) / 2 + 1 = 14
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    # cnn-hidden: 16 x 7 x 7 x 16
    print(conv.get_shape(), layer2_biases.get_shape())
    hidden = tf.nn.relu(conv + layer2_biases)
    shape = hidden.get_shape().as_list()
    # num_features = 16 x 7 x 7 x 16
    # num_samples = 16
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    # fnn-hidden: matmul(16 x (7 x 7 x 16), (28 // 4 x 28 // 4 x 16, 64))
    # fnn-hidden: num_features = 64
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    # num_labels = 10
    # fnn-output: matmul(16 x 64, 64 x 10) = (16, 10)
    return tf.matmul(hidden, layer4_weights) + layer4_biases
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).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))

with tf.Session(graph=graph) as session:
  tic = time.time()
  try:
    tf.global_variables_initializer().run()
  except AttributeError:
    tf.initialize_all_variables().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    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 % 50 == 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))
  print("Time: %.3f s" % (time.time() - tic))


(16, 7, 7, 16) (16,)
(10000, 7, 7, 16) (16,)
(10000, 7, 7, 16) (16,)
Initialized
Minibatch loss at step 0: 3.299321
Minibatch accuracy: 0.0%
Validation accuracy: 10.0%
Minibatch loss at step 50: 1.067475
Minibatch accuracy: 62.5%
Validation accuracy: 64.2%
Minibatch loss at step 100: 0.684700
Minibatch accuracy: 68.8%
Validation accuracy: 74.2%
Minibatch loss at step 150: 0.971370
Minibatch accuracy: 68.8%
Validation accuracy: 77.0%
Minibatch loss at step 200: 0.647194
Minibatch accuracy: 87.5%
Validation accuracy: 77.4%
Minibatch loss at step 250: 0.852453
Minibatch accuracy: 68.8%
Validation accuracy: 79.1%
Minibatch loss at step 300: 0.179239
Minibatch accuracy: 100.0%
Validation accuracy: 78.5%
Minibatch loss at step 350: 0.856902
Minibatch accuracy: 81.2%
Validation accuracy: 79.6%
Minibatch loss at step 400: 0.358386
Minibatch accuracy: 87.5%
Validation accuracy: 80.7%
Minibatch loss at step 450: 0.582294
Minibatch accuracy: 75.0%
Validation accuracy: 80.6%
Minibatch loss at step 500: 0.612308
Minibatch accuracy: 75.0%
Validation accuracy: 78.8%
Minibatch loss at step 550: 0.211593
Minibatch accuracy: 93.8%
Validation accuracy: 80.9%
Minibatch loss at step 600: 0.363430
Minibatch accuracy: 81.2%
Validation accuracy: 80.1%
Minibatch loss at step 650: 1.094313
Minibatch accuracy: 62.5%
Validation accuracy: 81.0%
Minibatch loss at step 700: 0.366122
Minibatch accuracy: 87.5%
Validation accuracy: 82.0%
Minibatch loss at step 750: 1.074676
Minibatch accuracy: 75.0%
Validation accuracy: 80.5%
Minibatch loss at step 800: 0.980928
Minibatch accuracy: 68.8%
Validation accuracy: 81.3%
Minibatch loss at step 850: 0.259755
Minibatch accuracy: 93.8%
Validation accuracy: 81.6%
Minibatch loss at step 900: 0.469374
Minibatch accuracy: 87.5%
Validation accuracy: 82.5%
Minibatch loss at step 950: 0.506907
Minibatch accuracy: 87.5%
Validation accuracy: 82.3%
Minibatch loss at step 1000: 0.840487
Minibatch accuracy: 62.5%
Validation accuracy: 81.9%
Test accuracy: 88.6%
Time: 20.428 s

Problem 2

Try to get the best performance you can using a convolutional net. Look for example at the classic LeNet5 architecture, adding Dropout, and/or adding learning rate decay.



In [9]:
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
num_steps = 1001

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  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)
  
  layers = {}
  weights = {}
  bias = {}
  scales = {}
  depth = {'C1': 6, 'S2': 6, 'C3': 10, 'S4': 10, 'C5': 16}
  
  weights['C1'] = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth['C1']], stddev=0.1))
  bias['C1'] = tf.Variable(tf.zeros([depth['C1']]))
  bias['S2'] = tf.Variable(tf.zeros([depth['S2']]))
  scales['S2'] = tf.Variable(tf.ones([depth['S2']]))
  weights['C3'] = tr.Variable(tf.truncated_normal([patch_size, patch_size, depth['S2'], depth['C3']], stddev=0.1))
  bias['C3'] = tf.Variable(tf.zeros([depth['C3']]))
  bias['S4'] = tf.Variable(tf.zeros([depth['S4']]))
  scales['S4'] = tf.Variable(tf.ones([depth['S4']]))
  weights['C5'] = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth['S4'], depth['C5']], stddev=0.1))
  bias['C5'] = tf.Variable(tf.zeros([depth['C5']]))
  weights['F6'] = tf.Variable(tf.truncated_normal([batch_size, 84], stddev=0.1))
  bias['F6'] = tf.Variable(tf.zeros([84]))
  weights['F7'] = tf.Variable(tf.truncated_normal([batch_size, 10], stddev=0.1))
  
  def squashing(target, scale):
    return 1.7159 * tf.tanh(scale * target)
  
  def rbf(x, w):
    pass
  
  # Model.
  def lenet5_model(data, for_training=True):
    """ A tensorflow implementation of LeNet5. """
    # C1: Conv2D, 28 x 28 x 6
    layers['C1'] = tf.nn.conv2d(data, weights['C1'], [1, 1, 1, 1], padding='SAME')
    hidden = layers['C1'] + bias['C1']
    # S2: Scaled average pooling with bias, 14 x 14 x 6
    layers['S2'] = tf.nn.avg_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = squashing(layers['S2'] + bias['S2'], scales['S2'])
    # C3: Conv2D, partial connected, 10 x 10 x 16
    layers['C3'] = tf.nn.conv2d(hidden, weights['C3'], [1, 1, 1, 1], padding='SAME')
    hidden = layers['C3'] + bias['C3']
    # S4: Scaled average pooling with bias, 5 x 5 x 16
    layers['S4'] = tf.nn.avg_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = squashing(layers['S4'] + bias['S4'], scales['S4'])
    # C5: Conv2D, 5 x 5 x 16
    layers['C5'] = tf.nn.conv2d(hidden, weights['C5'], [1, 1, 1, 1], padding='SAME')
    hidden = layers['C5'] + bias['C5']
    # F6: FullConnected, 84 nodes
    hidden = tf.reshape(hidden, (-1, 84))
    layers['F6'] = tf.matmul(hidden, weights['F6'])
    hidden = tf.sigmoid(layers['F6'] + bias['F6'])
    # F7: RBF Kernel, 10 nodes
    return rbf(hidden, weights['F7'])
  
  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).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, False))
  test_prediction = tf.nn.softmax(model(tf_test_dataset, False))

with tf.Session(graph=graph) as session:
  tic = time.time()
  try:
    tf.global_variables_initializer().run()
  except AttributeError:
    tf.initialize_all_variables().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    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 % 50 == 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))
  print("Time: %.3f s" % (time.time() - tic))


Initialized
Minibatch loss at step 0: 4.469641
Minibatch accuracy: 12.5%
Validation accuracy: 10.0%
Minibatch loss at step 50: 1.776402
Minibatch accuracy: 31.2%
Validation accuracy: 51.2%
Minibatch loss at step 100: 0.904853
Minibatch accuracy: 68.8%
Validation accuracy: 66.3%
Minibatch loss at step 150: 1.262172
Minibatch accuracy: 62.5%
Validation accuracy: 72.6%
Minibatch loss at step 200: 0.894488
Minibatch accuracy: 75.0%
Validation accuracy: 71.1%
Minibatch loss at step 250: 1.555322
Minibatch accuracy: 43.8%
Validation accuracy: 75.0%
Minibatch loss at step 300: 0.543386
Minibatch accuracy: 87.5%
Validation accuracy: 75.9%
Minibatch loss at step 350: 0.953909
Minibatch accuracy: 68.8%
Validation accuracy: 76.6%
Minibatch loss at step 400: 0.589980
Minibatch accuracy: 87.5%
Validation accuracy: 78.4%
Minibatch loss at step 450: 0.922919
Minibatch accuracy: 62.5%
Validation accuracy: 78.7%
Minibatch loss at step 500: 0.704024
Minibatch accuracy: 75.0%
Validation accuracy: 78.4%
Minibatch loss at step 550: 0.424831
Minibatch accuracy: 87.5%
Validation accuracy: 78.7%
Minibatch loss at step 600: 0.884748
Minibatch accuracy: 75.0%
Validation accuracy: 77.3%
Minibatch loss at step 650: 1.026492
Minibatch accuracy: 68.8%
Validation accuracy: 79.8%
Minibatch loss at step 700: 0.609067
Minibatch accuracy: 87.5%
Validation accuracy: 79.7%
Minibatch loss at step 750: 1.192406
Minibatch accuracy: 68.8%
Validation accuracy: 80.0%
Minibatch loss at step 800: 0.917172
Minibatch accuracy: 68.8%
Validation accuracy: 79.5%
Minibatch loss at step 850: 0.580377
Minibatch accuracy: 81.2%
Validation accuracy: 80.1%
Minibatch loss at step 900: 0.599618
Minibatch accuracy: 87.5%
Validation accuracy: 80.1%
Minibatch loss at step 950: 0.543214
Minibatch accuracy: 81.2%
Validation accuracy: 79.9%
Minibatch loss at step 1000: 1.058471
Minibatch accuracy: 62.5%
Validation accuracy: 80.6%
Test accuracy: 87.9%
Time: 21.930 s