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 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 (200000, 28, 28) (200000,)
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 (200000, 28, 28, 1) (200000, 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 [20]:
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):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)
    hidden = tf.nn.max_pool(hidden, [1,2,2,1], [1,2,2,1], padding='SAME')
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    hidden = tf.nn.max_pool(hidden, [1,2,2,1], [1,2,2,1], padding='SAME')
    shape = hidden.get_shape().as_list()
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    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 [21]:
num_steps = 2001

with tf.Session(graph=graph) as session:
  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))


Initialized
Minibatch loss at step 0: 2.887852
Minibatch accuracy: 6.2%
Validation accuracy: 10.0%
Minibatch loss at step 50: 2.051110
Minibatch accuracy: 12.5%
Validation accuracy: 29.9%
Minibatch loss at step 100: 1.185204
Minibatch accuracy: 62.5%
Validation accuracy: 51.3%
Minibatch loss at step 150: 0.624291
Minibatch accuracy: 81.2%
Validation accuracy: 71.7%
Minibatch loss at step 200: 0.955439
Minibatch accuracy: 75.0%
Validation accuracy: 74.3%
Minibatch loss at step 250: 1.174336
Minibatch accuracy: 68.8%
Validation accuracy: 76.7%
Minibatch loss at step 300: 0.375701
Minibatch accuracy: 87.5%
Validation accuracy: 80.0%
Minibatch loss at step 350: 0.705345
Minibatch accuracy: 93.8%
Validation accuracy: 76.4%
Minibatch loss at step 400: 0.281616
Minibatch accuracy: 100.0%
Validation accuracy: 80.5%
Minibatch loss at step 450: 1.062438
Minibatch accuracy: 75.0%
Validation accuracy: 79.2%
Minibatch loss at step 500: 0.610115
Minibatch accuracy: 87.5%
Validation accuracy: 81.4%
Minibatch loss at step 550: 0.876767
Minibatch accuracy: 75.0%
Validation accuracy: 81.6%
Minibatch loss at step 600: 0.271369
Minibatch accuracy: 87.5%
Validation accuracy: 81.8%
Minibatch loss at step 650: 0.766848
Minibatch accuracy: 75.0%
Validation accuracy: 81.8%
Minibatch loss at step 700: 0.815853
Minibatch accuracy: 81.2%
Validation accuracy: 82.6%
Minibatch loss at step 750: 0.094008
Minibatch accuracy: 100.0%
Validation accuracy: 83.7%
Minibatch loss at step 800: 0.632895
Minibatch accuracy: 81.2%
Validation accuracy: 83.1%
Minibatch loss at step 850: 0.845280
Minibatch accuracy: 75.0%
Validation accuracy: 83.7%
Minibatch loss at step 900: 0.678683
Minibatch accuracy: 87.5%
Validation accuracy: 82.9%
Minibatch loss at step 950: 0.518502
Minibatch accuracy: 87.5%
Validation accuracy: 84.3%
Minibatch loss at step 1000: 0.376357
Minibatch accuracy: 87.5%
Validation accuracy: 84.2%
Minibatch loss at step 1050: 0.493665
Minibatch accuracy: 81.2%
Validation accuracy: 83.4%
Minibatch loss at step 1100: 0.616195
Minibatch accuracy: 81.2%
Validation accuracy: 84.2%
Minibatch loss at step 1150: 0.454042
Minibatch accuracy: 81.2%
Validation accuracy: 84.7%
Minibatch loss at step 1200: 0.823288
Minibatch accuracy: 81.2%
Validation accuracy: 85.0%
Minibatch loss at step 1250: 0.589719
Minibatch accuracy: 81.2%
Validation accuracy: 84.6%
Minibatch loss at step 1300: 0.276481
Minibatch accuracy: 93.8%
Validation accuracy: 84.1%
Minibatch loss at step 1350: 0.729200
Minibatch accuracy: 75.0%
Validation accuracy: 85.3%
Minibatch loss at step 1400: 0.252959
Minibatch accuracy: 93.8%
Validation accuracy: 85.3%
Minibatch loss at step 1450: 0.213688
Minibatch accuracy: 100.0%
Validation accuracy: 85.3%
Minibatch loss at step 1500: 0.729057
Minibatch accuracy: 75.0%
Validation accuracy: 85.2%
Minibatch loss at step 1550: 0.555658
Minibatch accuracy: 93.8%
Validation accuracy: 85.1%
Minibatch loss at step 1600: 1.003705
Minibatch accuracy: 68.8%
Validation accuracy: 85.1%
Minibatch loss at step 1650: 0.614646
Minibatch accuracy: 81.2%
Validation accuracy: 85.3%
Minibatch loss at step 1700: 0.526734
Minibatch accuracy: 87.5%
Validation accuracy: 85.2%
Minibatch loss at step 1750: 0.517184
Minibatch accuracy: 81.2%
Validation accuracy: 86.0%
Minibatch loss at step 1800: 0.242730
Minibatch accuracy: 93.8%
Validation accuracy: 86.1%
Minibatch loss at step 1850: 0.540403
Minibatch accuracy: 81.2%
Validation accuracy: 85.9%
Minibatch loss at step 1900: 0.385952
Minibatch accuracy: 81.2%
Validation accuracy: 85.2%
Minibatch loss at step 1950: 0.452086
Minibatch accuracy: 87.5%
Validation accuracy: 86.3%
Minibatch loss at step 2000: 0.094848
Minibatch accuracy: 100.0%
Validation accuracy: 86.2%
Test accuracy: 92.6%

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.



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 [101]:
initial_learning_rate_value = 0.05
batch_size = 16
patch_size = 5
depth = 16
depth2 = 32
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)

  # learning rate decay
  global_step = tf.Variable(0)
  learning_rate = tf.train.exponential_decay(initial_learning_rate_value, global_step, 1, 0.9999)
  
  # 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(
      [patch_size, patch_size, depth, depth2], stddev=0.1))
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[depth2]))

  layer4_weights = tf.Variable(tf.truncated_normal(
      [image_size // 7 * image_size // 7 * depth2, num_hidden], stddev=0.1))
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))

  layer5_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1))
  layer5_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
  
  # Model.
  def model(data):
    # data ---> conv2d | layer1 ---> relu --> max_pool
    #
    # data input tensor:      [16, 28, 28, 1]     4D tensor: (batch, h, w, ch)
    # layer1 filter tensor:   [5, 5, 1, 16]
    # conv2d output tensor:   [16, 28, 28, 16]
    # relu output tensor:     [16, 28, 28, 16]
    # max_pool output tensor: [16, 14, 14 16]
    
    conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')    
    hidden = tf.nn.relu(conv + layer1_biases)
    hidden = tf.nn.max_pool(hidden, [1,2,2,1], [1,2,2,1], padding='SAME')
        
    # hidden ---> conv2d | layer2 ---> relu --> max_pool
    #
    # hidden input tensor:    [16, 14, 14, 16]
    # layer2 filter tensor:   [5, 5, 16, 16]
    # conv2d output tensor:   [16, 14, 14, 16]
    # relu output tensor:     [16, 14, 14, 16]
    # max_pool output tensor: [16, 7, 7, 16]
    
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    hidden = tf.nn.max_pool(hidden, [1,2,2,1], [1,2,2,1], padding='SAME')
        
    # hidden ---> conv2d | layer3 ---> relu --> max_pool
    #
    # hidden input tensor:    [16, 7, 7, 16]
    # layer3 filter tensor:   [5, 5, 16, 32]
    # conv2d output tensor:   [16, 7, 7, 32]
    # relu output tensor:     [16, 7, 7, 32]
    # max_pool output tensor: [16, 4, 4, 32]
    
    conv = tf.nn.conv2d(hidden, layer3_weights, [1, 1, 1, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer3_biases)
    hidden = tf.nn.max_pool(hidden, [1,2,2,1], [1,2,2,1], padding='SAME')
    
    # hidden ---> relu --> dropout
    #
    # hidden input tensor:    [16, 4, 4, 32]
    # reshape tensor:         [16, 512]
    # layer4 tensor:          [512, 64] (512 = 4*4*32)
    # relu tensor:            [16, 64]
    
    shape = hidden.get_shape().as_list()    
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer4_weights) + layer4_biases)
    hidden = tf.nn.dropout(hidden, 0.75)
    
    # hidden ---> layer5
    #
    # hidden input tensor:    [16, 64]
    # layer5 tensor:          [64, 10]
    # ouput tensor:           [16 x 10]
    output = tf.matmul(hidden, layer5_weights) + layer5_biases
    return output
  
  # 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(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))

In [102]:
num_steps = 2001

with tf.Session(graph=graph) as session:
  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("Learning rate at step %d: %f" % (step, learning_rate.eval()))
      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
      print('Validation accuracy: %.1f%%\n' % accuracy(
        valid_prediction.eval(), valid_labels))
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))


Initialized
Minibatch loss at step 0: 5.236138
Learning rate at step 0: 0.049995
Minibatch accuracy: 12.5%
Validation accuracy: 9.9%

Minibatch loss at step 50: 2.147182
Learning rate at step 50: 0.049746
Minibatch accuracy: 6.2%
Validation accuracy: 21.2%

Minibatch loss at step 100: 1.249267
Learning rate at step 100: 0.049497
Minibatch accuracy: 62.5%
Validation accuracy: 49.4%

Minibatch loss at step 150: 0.540573
Learning rate at step 150: 0.049251
Minibatch accuracy: 87.5%
Validation accuracy: 65.2%

Minibatch loss at step 200: 0.937742
Learning rate at step 200: 0.049005
Minibatch accuracy: 62.5%
Validation accuracy: 70.7%

Minibatch loss at step 250: 1.064317
Learning rate at step 250: 0.048760
Minibatch accuracy: 68.8%
Validation accuracy: 74.1%

Minibatch loss at step 300: 0.627920
Learning rate at step 300: 0.048517
Minibatch accuracy: 81.2%
Validation accuracy: 76.8%

Minibatch loss at step 350: 0.415646
Learning rate at step 350: 0.048275
Minibatch accuracy: 81.2%
Validation accuracy: 75.8%

Minibatch loss at step 400: 0.240822
Learning rate at step 400: 0.048034
Minibatch accuracy: 87.5%
Validation accuracy: 77.6%

Minibatch loss at step 450: 0.937572
Learning rate at step 450: 0.047795
Minibatch accuracy: 75.0%
Validation accuracy: 78.7%

Minibatch loss at step 500: 0.680249
Learning rate at step 500: 0.047556
Minibatch accuracy: 81.2%
Validation accuracy: 80.2%

Minibatch loss at step 550: 1.324346
Learning rate at step 550: 0.047319
Minibatch accuracy: 75.0%
Validation accuracy: 79.2%

Minibatch loss at step 600: 0.295159
Learning rate at step 600: 0.047083
Minibatch accuracy: 87.5%
Validation accuracy: 80.6%

Minibatch loss at step 650: 1.080894
Learning rate at step 650: 0.046848
Minibatch accuracy: 75.0%
Validation accuracy: 80.8%

Minibatch loss at step 700: 1.045246
Learning rate at step 700: 0.046614
Minibatch accuracy: 62.5%
Validation accuracy: 80.7%

Minibatch loss at step 750: 0.046020
Learning rate at step 750: 0.046382
Minibatch accuracy: 100.0%
Validation accuracy: 81.9%

Minibatch loss at step 800: 0.465275
Learning rate at step 800: 0.046150
Minibatch accuracy: 81.2%
Validation accuracy: 81.3%

Minibatch loss at step 850: 0.930939
Learning rate at step 850: 0.045920
Minibatch accuracy: 68.8%
Validation accuracy: 82.2%

Minibatch loss at step 900: 0.631694
Learning rate at step 900: 0.045691
Minibatch accuracy: 81.2%
Validation accuracy: 83.0%

Minibatch loss at step 950: 0.647490
Learning rate at step 950: 0.045463
Minibatch accuracy: 81.2%
Validation accuracy: 82.1%

Minibatch loss at step 1000: 0.653211
Learning rate at step 1000: 0.045236
Minibatch accuracy: 81.2%
Validation accuracy: 82.2%

Minibatch loss at step 1050: 0.587030
Learning rate at step 1050: 0.045011
Minibatch accuracy: 87.5%
Validation accuracy: 81.6%

Minibatch loss at step 1100: 0.564651
Learning rate at step 1100: 0.044786
Minibatch accuracy: 75.0%
Validation accuracy: 83.2%

Minibatch loss at step 1150: 0.468530
Learning rate at step 1150: 0.044563
Minibatch accuracy: 81.2%
Validation accuracy: 82.9%

Minibatch loss at step 1200: 0.933110
Learning rate at step 1200: 0.044340
Minibatch accuracy: 68.8%
Validation accuracy: 83.6%

Minibatch loss at step 1250: 0.926923
Learning rate at step 1250: 0.044119
Minibatch accuracy: 75.0%
Validation accuracy: 83.2%

Minibatch loss at step 1300: 0.381629
Learning rate at step 1300: 0.043899
Minibatch accuracy: 93.8%
Validation accuracy: 82.2%

Minibatch loss at step 1350: 0.864118
Learning rate at step 1350: 0.043680
Minibatch accuracy: 68.8%
Validation accuracy: 82.9%

Minibatch loss at step 1400: 0.351495
Learning rate at step 1400: 0.043462
Minibatch accuracy: 93.8%
Validation accuracy: 84.2%

Minibatch loss at step 1450: 0.113925
Learning rate at step 1450: 0.043245
Minibatch accuracy: 100.0%
Validation accuracy: 84.2%

Minibatch loss at step 1500: 0.531653
Learning rate at step 1500: 0.043030
Minibatch accuracy: 75.0%
Validation accuracy: 84.2%

Minibatch loss at step 1550: 0.796815
Learning rate at step 1550: 0.042815
Minibatch accuracy: 68.8%
Validation accuracy: 83.7%

Minibatch loss at step 1600: 0.930998
Learning rate at step 1600: 0.042601
Minibatch accuracy: 75.0%
Validation accuracy: 84.0%

Minibatch loss at step 1650: 0.791512
Learning rate at step 1650: 0.042389
Minibatch accuracy: 81.2%
Validation accuracy: 83.5%

Minibatch loss at step 1700: 0.803234
Learning rate at step 1700: 0.042177
Minibatch accuracy: 81.2%
Validation accuracy: 84.1%

Minibatch loss at step 1750: 0.481777
Learning rate at step 1750: 0.041967
Minibatch accuracy: 81.2%
Validation accuracy: 84.1%

Minibatch loss at step 1800: 0.334682
Learning rate at step 1800: 0.041758
Minibatch accuracy: 93.8%
Validation accuracy: 84.5%

Minibatch loss at step 1850: 0.801326
Learning rate at step 1850: 0.041549
Minibatch accuracy: 75.0%
Validation accuracy: 84.9%

Minibatch loss at step 1900: 0.306579
Learning rate at step 1900: 0.041342
Minibatch accuracy: 93.8%
Validation accuracy: 83.9%

Minibatch loss at step 1950: 0.563700
Learning rate at step 1950: 0.041136
Minibatch accuracy: 75.0%
Validation accuracy: 84.9%

Minibatch loss at step 2000: 0.068546
Learning rate at step 2000: 0.040931
Minibatch accuracy: 100.0%
Validation accuracy: 84.7%

Test accuracy: 90.9%

In [ ]: