In [1]:
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle

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

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 [4]:
def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])

Notes

With two hidden layers, the best accuracy I've been able to get on the test set below is roughly 90%:

  • 1024 neurons each
  • Each set of weights initialized with stddev=0.5
  • Decreasing dropout on hidden layers - e.g., 0.75 for h1, 0.95 for h2



In [6]:
batch_size = 128
initial_learning_rate_value = 0.0005
beta1 = 0.001
beta2 = 0.001
beta3 = 0.001

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)    
    
  # learning rate decay
  global_step = tf.Variable(0)
  learning_rate = tf.train.exponential_decay(initial_learning_rate_value, global_step, 1, 0.9999)

  # Hidden layer 1
  h1_size = 1024  
  weights_h1 = tf.Variable(tf.truncated_normal([image_size * image_size, h1_size], stddev=0.5))
  biases_h1 = tf.Variable(tf.zeros([h1_size]))
  h1 = tf.nn.dropout(tf.nn.relu(tf.matmul(tf_train_dataset, weights_h1) + biases_h1), 0.75)

  # Hidden layer 2
  h2_size = 1024
  weights_h2 = tf.Variable(tf.truncated_normal([h1_size, h2_size], stddev=0.5))
  biases_h2 = tf.Variable(tf.zeros([h2_size]))
  h2 = tf.nn.dropout(tf.nn.relu(tf.matmul(h1, weights_h2) + biases_h2), 0.95)

  # Output layer
  weights_o = tf.Variable(tf.truncated_normal([h2_size, num_labels], stddev=0.5))
  biases_o = tf.Variable(tf.zeros([num_labels]))
    
  # Training computation.
  logits = tf.matmul(h2, weights_o) + biases_o
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) + ((beta1 * tf.nn.l2_loss(weights_h1)) + (beta2 * tf.nn.l2_loss(weights_h2)) + (beta3 * tf.nn.l2_loss(weights_o)))
  
  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

  # Predictions for the training, validation, and test data.
  train_h1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights_h1) + biases_h1)
  train_h2 = tf.nn.relu(tf.matmul(train_h1, weights_h2) + biases_h2)
  train_logits = tf.matmul(train_h2, weights_o) + biases_o
  train_prediction = tf.nn.softmax(train_logits)
  
  valid_h1 = tf.nn.relu(tf.matmul(tf_valid_dataset, weights_h1) + biases_h1)
  valid_h2 = tf.nn.relu(tf.matmul(valid_h1, weights_h2) + biases_h2)
  valid_logits = tf.matmul(valid_h2, weights_o) + biases_o
  valid_prediction = tf.nn.softmax(valid_logits)
    
  test_h1 = tf.nn.relu(tf.matmul(tf_test_dataset, weights_h1) + biases_h1)
  test_h2 = tf.nn.relu(tf.matmul(test_h1, weights_h2) + biases_h2)
  test_logits = tf.matmul(test_h2, weights_o) + biases_o
  test_prediction = tf.nn.softmax(test_logits)

In [7]:
num_steps = 10001

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("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))
        
    if (step % 2000 == 0):
      print("Test accuracy: %.1f%%\n" % accuracy(test_prediction.eval(), test_labels))
        
  print("Final test accuracy: %.1f%%\n" % accuracy(test_prediction.eval(), test_labels))


Initialized
Minibatch loss at step 0: 1036.835083
Learning rate at step 0: 0.000500
Minibatch accuracy: 13.3%
Validation accuracy: 10.3%

Test accuracy: 9.9%

Minibatch loss at step 500: 315.791382
Learning rate at step 500: 0.000476
Minibatch accuracy: 72.7%
Validation accuracy: 76.8%

Minibatch loss at step 1000: 337.020386
Learning rate at step 1000: 0.000452
Minibatch accuracy: 72.7%
Validation accuracy: 78.7%

Minibatch loss at step 1500: 254.118164
Learning rate at step 1500: 0.000430
Minibatch accuracy: 85.2%
Validation accuracy: 79.6%

Minibatch loss at step 2000: 269.242065
Learning rate at step 2000: 0.000409
Minibatch accuracy: 86.7%
Validation accuracy: 80.2%

Test accuracy: 88.2%

Minibatch loss at step 2500: 276.467407
Learning rate at step 2500: 0.000389
Minibatch accuracy: 80.5%
Validation accuracy: 80.8%

Minibatch loss at step 3000: 288.928223
Learning rate at step 3000: 0.000370
Minibatch accuracy: 82.0%
Validation accuracy: 81.1%

Minibatch loss at step 3500: 264.130859
Learning rate at step 3500: 0.000352
Minibatch accuracy: 82.8%
Validation accuracy: 81.3%

Minibatch loss at step 4000: 248.249985
Learning rate at step 4000: 0.000335
Minibatch accuracy: 87.5%
Validation accuracy: 81.5%

Test accuracy: 89.2%

Minibatch loss at step 4500: 237.254715
Learning rate at step 4500: 0.000319
Minibatch accuracy: 83.6%
Validation accuracy: 81.7%

Minibatch loss at step 5000: 243.480972
Learning rate at step 5000: 0.000303
Minibatch accuracy: 85.2%
Validation accuracy: 81.9%

Minibatch loss at step 5500: 244.452789
Learning rate at step 5500: 0.000288
Minibatch accuracy: 82.8%
Validation accuracy: 81.7%

Minibatch loss at step 6000: 256.484711
Learning rate at step 6000: 0.000274
Minibatch accuracy: 81.2%
Validation accuracy: 81.9%

Test accuracy: 89.5%

Minibatch loss at step 6500: 222.449997
Learning rate at step 6500: 0.000261
Minibatch accuracy: 82.8%
Validation accuracy: 82.0%

Minibatch loss at step 7000: 240.335724
Learning rate at step 7000: 0.000248
Minibatch accuracy: 82.8%
Validation accuracy: 82.0%

Minibatch loss at step 7500: 261.476776
Learning rate at step 7500: 0.000236
Minibatch accuracy: 78.9%
Validation accuracy: 82.1%

Minibatch loss at step 8000: 272.132538
Learning rate at step 8000: 0.000225
Minibatch accuracy: 75.0%
Validation accuracy: 82.2%

Test accuracy: 89.9%

Minibatch loss at step 8500: 227.130325
Learning rate at step 8500: 0.000214
Minibatch accuracy: 87.5%
Validation accuracy: 82.4%

Minibatch loss at step 9000: 239.626389
Learning rate at step 9000: 0.000203
Minibatch accuracy: 82.0%
Validation accuracy: 82.2%

Minibatch loss at step 9500: 232.183685
Learning rate at step 9500: 0.000193
Minibatch accuracy: 82.8%
Validation accuracy: 82.4%

Minibatch loss at step 10000: 230.191010
Learning rate at step 10000: 0.000184
Minibatch accuracy: 81.2%
Validation accuracy: 82.5%

Test accuracy: 90.1%

Final test accuracy: 90.1%


In [ ]:


In [ ]: