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 matplotlib.pyplot as plt

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,)

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)
  # Map 1 to [0.0, 1.0, 0.0 ...], 2 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, 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 [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):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    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 w/ learning rate decay.
  global_step = tf.Variable(0)
  learning_rate = tf.train.exponential_decay(0.05, global_step, 1000, 0.9)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).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:
  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 % 100 == 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))


WARNING:tensorflow:From <ipython-input-6-b0900ef7635b>:4 in <module>.: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Initialized
Minibatch loss at step 0: 2.918096
Minibatch accuracy: 6.2%
Validation accuracy: 10.0%
Minibatch loss at step 100: 1.564008
Minibatch accuracy: 43.8%
Validation accuracy: 65.2%
Minibatch loss at step 200: 1.081790
Minibatch accuracy: 81.2%
Validation accuracy: 77.2%
Minibatch loss at step 300: 1.328269
Minibatch accuracy: 56.2%
Validation accuracy: 79.2%
Minibatch loss at step 400: 1.192118
Minibatch accuracy: 62.5%
Validation accuracy: 80.3%
Minibatch loss at step 500: 0.639404
Minibatch accuracy: 81.2%
Validation accuracy: 81.1%
Minibatch loss at step 600: 1.100861
Minibatch accuracy: 62.5%
Validation accuracy: 81.1%
Minibatch loss at step 700: 0.561790
Minibatch accuracy: 75.0%
Validation accuracy: 82.1%
Minibatch loss at step 800: 0.458544
Minibatch accuracy: 87.5%
Validation accuracy: 82.2%
Minibatch loss at step 900: 0.713941
Minibatch accuracy: 81.2%
Validation accuracy: 82.0%
Minibatch loss at step 1000: 0.347145
Minibatch accuracy: 87.5%
Validation accuracy: 82.7%
Test accuracy: 89.2%

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 [7]:
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')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer1_biases)
            
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer2_biases)
    
    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 w/ learning rate decay.
  global_step = tf.Variable(0)
  learning_rate = tf.train.exponential_decay(0.05, global_step, 1000, 0.9)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).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 [20]:
num_steps = 1001

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().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 % 100 == 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: 3.483711
Minibatch accuracy: 12.5%
Validation accuracy: 10.0%
Minibatch loss at step 100: 1.628864
Minibatch accuracy: 43.8%
Validation accuracy: 63.4%
Minibatch loss at step 200: 1.175636
Minibatch accuracy: 75.0%
Validation accuracy: 77.5%
Minibatch loss at step 300: 1.144591
Minibatch accuracy: 56.2%
Validation accuracy: 74.9%
Minibatch loss at step 400: 1.112732
Minibatch accuracy: 68.8%
Validation accuracy: 77.7%
Minibatch loss at step 500: 0.624896
Minibatch accuracy: 75.0%
Validation accuracy: 81.8%
Minibatch loss at step 600: 1.439164
Minibatch accuracy: 62.5%
Validation accuracy: 82.0%
Minibatch loss at step 700: 0.465617
Minibatch accuracy: 81.2%
Validation accuracy: 82.9%
Minibatch loss at step 800: 0.456498
Minibatch accuracy: 93.8%
Validation accuracy: 83.0%
Minibatch loss at step 900: 0.654596
Minibatch accuracy: 81.2%
Validation accuracy: 82.6%
Minibatch loss at step 1000: 0.312720
Minibatch accuracy: 93.8%
Validation accuracy: 84.3%
Test accuracy: 90.6%

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 [49]:
batch_size = 32#16#94.8%
patch_size = 5
depth = 16
num_hidden = 128#64
beta = 0.005

graph = tf.Graph()

with graph.as_default():

  # Placeholder to control dropout probability.
  keep_prob = tf.placeholder(tf.float32)
  keep_prob_conv = tf.placeholder(tf.float32)
    
  # 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]))
  layer2a_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))
  layer2a_biases = tf.Variable(tf.constant(1.0, shape=[depth]))

  layer3_weights = tf.Variable(tf.truncated_normal([4 * 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')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer1_biases)

    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer2_biases)

    conv = tf.nn.conv2d(hidden, layer2a_weights, [1, 1, 1, 1], padding='SAME')
    pool = tf.nn.max_pool(conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(pool + layer2a_biases)
    
    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)
    drop = tf.nn.dropout(hidden, keep_prob)
    
    return tf.matmul(drop, 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))

  # Add the regularization term to the loss.
  loss += beta * (tf.nn.l2_loss(layer3_weights) + tf.nn.l2_loss(layer4_weights))

  # Optimizer w/ learning rate decay.
  global_step = tf.Variable(0)
  learning_rate = tf.train.exponential_decay(0.1, global_step, 3000, 0.01)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).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 [112]:
num_steps = 3001
steps = np.array([])
loss_batch = np.array([])
acc_valid = np.array([])

with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().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, keep_prob:1.0, keep_prob_conv:1.0}
    feed_dict_w_dropout = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob:0.5, keep_prob_conv:1.0}
    _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict_w_dropout)
    if (step % 100 == 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(feed_dict=feed_dict), valid_labels))
    
      steps = np.append(steps, step)
      loss_batch = np.append(loss_batch, l)
      acc_valid = np.append(acc_valid, [accuracy(valid_prediction.eval(feed_dict=feed_dict), valid_labels)])
    
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict=feed_dict), test_labels))


Initialized
Minibatch loss at step 0: 6.712016
Minibatch accuracy: 18.8%
Validation accuracy: 10.0%
Minibatch loss at step 100: 2.595669
Minibatch accuracy: 31.2%
Validation accuracy: 27.5%
Minibatch loss at step 200: 1.446040
Minibatch accuracy: 75.0%
Validation accuracy: 70.8%
Minibatch loss at step 300: 1.594900
Minibatch accuracy: 65.6%
Validation accuracy: 77.1%
Minibatch loss at step 400: 1.465292
Minibatch accuracy: 68.8%
Validation accuracy: 79.8%
Minibatch loss at step 500: 0.907639
Minibatch accuracy: 84.4%
Validation accuracy: 82.4%
Minibatch loss at step 600: 0.851826
Minibatch accuracy: 87.5%
Validation accuracy: 83.0%
Minibatch loss at step 700: 0.757362
Minibatch accuracy: 87.5%
Validation accuracy: 83.3%
Minibatch loss at step 800: 0.874789
Minibatch accuracy: 84.4%
Validation accuracy: 82.7%
Minibatch loss at step 900: 1.230573
Minibatch accuracy: 75.0%
Validation accuracy: 83.9%
Minibatch loss at step 1000: 0.825831
Minibatch accuracy: 84.4%
Validation accuracy: 84.9%
Minibatch loss at step 1100: 0.834065
Minibatch accuracy: 84.4%
Validation accuracy: 85.3%
Minibatch loss at step 1200: 0.748064
Minibatch accuracy: 87.5%
Validation accuracy: 85.8%
Minibatch loss at step 1300: 0.977312
Minibatch accuracy: 75.0%
Validation accuracy: 86.3%
Minibatch loss at step 1400: 0.699148
Minibatch accuracy: 84.4%
Validation accuracy: 86.0%
Minibatch loss at step 1500: 0.670250
Minibatch accuracy: 87.5%
Validation accuracy: 86.2%
Minibatch loss at step 1600: 0.924020
Minibatch accuracy: 75.0%
Validation accuracy: 86.8%
Minibatch loss at step 1700: 0.411786
Minibatch accuracy: 93.8%
Validation accuracy: 86.9%
Minibatch loss at step 1800: 0.549918
Minibatch accuracy: 87.5%
Validation accuracy: 87.2%
Minibatch loss at step 1900: 0.831919
Minibatch accuracy: 78.1%
Validation accuracy: 87.0%
Minibatch loss at step 2000: 0.786327
Minibatch accuracy: 81.2%
Validation accuracy: 86.5%
Minibatch loss at step 2100: 0.754802
Minibatch accuracy: 81.2%
Validation accuracy: 87.0%
Minibatch loss at step 2200: 0.721017
Minibatch accuracy: 75.0%
Validation accuracy: 86.3%
Minibatch loss at step 2300: 0.774539
Minibatch accuracy: 81.2%
Validation accuracy: 87.0%
Minibatch loss at step 2400: 0.595340
Minibatch accuracy: 87.5%
Validation accuracy: 87.3%
Minibatch loss at step 2500: 0.506562
Minibatch accuracy: 90.6%
Validation accuracy: 87.0%
Minibatch loss at step 2600: 0.693725
Minibatch accuracy: 81.2%
Validation accuracy: 87.3%
Minibatch loss at step 2700: 0.267519
Minibatch accuracy: 96.9%
Validation accuracy: 88.0%
Minibatch loss at step 2800: 0.271084
Minibatch accuracy: 93.8%
Validation accuracy: 87.7%
Minibatch loss at step 2900: 0.489859
Minibatch accuracy: 93.8%
Validation accuracy: 87.9%
Minibatch loss at step 3000: 0.264786
Minibatch accuracy: 93.8%
Validation accuracy: 88.3%
Test accuracy: 93.8%

In [113]:
print('Loss evolution')
s1, = plt.plot(steps, loss_batch)
s2, = plt.plot(steps, acc_valid/100)
plt.legend([s1, s2], ['loss_batch','accuracy_valid'])
plt.show()


Loss evolution

In [ ]: