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 = '/Users/rringham/Projects/TensorFlow/tensorflow/tensorflow/examples/udacity/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%:

  • h1: 1024 neurons
  • h2: 1024 neurons
  • h3: 305 neurons
  • h4: 75 neurons
  • Each set of weights initialized with stddev=sqrt(2/n), where n = # of neurons in previous layer
  • No dropout



In [7]:
import math as math

batch_size = 128
initial_learning_rate_value = 0.5
beta1 = 0.001
beta2 = 0.001
beta3 = 0.001
beta4 = 0.001
beta5 = 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=math.sqrt(2.0/(image_size*image_size))))
  biases_h1 = tf.Variable(tf.zeros([h1_size]))
  h1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights_h1) + biases_h1)

  # Hidden layer 2
  h2_size = 1024
  weights_h2 = tf.Variable(tf.truncated_normal([h1_size, h2_size], stddev=math.sqrt(2.0/h1_size)))
  biases_h2 = tf.Variable(tf.zeros([h2_size]))
  h2 = tf.nn.relu(tf.matmul(h1, weights_h2) + biases_h2)

  # Hidden layer 3
  h3_size = 305
  weights_h3 = tf.Variable(tf.truncated_normal([h2_size, h3_size], stddev=math.sqrt(2.0/h2_size)))
  biases_h3 = tf.Variable(tf.zeros([h3_size]))
  h3 = tf.nn.relu(tf.matmul(h2, weights_h3) + biases_h3)

  # Hidden layer 4
  h4_size = 75
  weights_h4 = tf.Variable(tf.truncated_normal([h3_size, h4_size], stddev=math.sqrt(2.0/h3_size)))
  biases_h4 = tf.Variable(tf.zeros([h4_size]))
  h4 = tf.nn.relu(tf.matmul(h3, weights_h4) + biases_h4)

  # Output layer
  weights_o = tf.Variable(tf.truncated_normal([h4_size, num_labels], stddev=math.sqrt(2.0/h4_size)))
  biases_o = tf.Variable(tf.zeros([num_labels]))
    
  # Training computation.
  logits = tf.matmul(h4, 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_h3)) + (beta4 * tf.nn.l2_loss(weights_h4)) + (beta5 * 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_h3 = tf.nn.relu(tf.matmul(train_h2, weights_h3) + biases_h3)
  train_h4 = tf.nn.relu(tf.matmul(train_h3, weights_h4) + biases_h4)
  train_logits = tf.matmul(train_h4, 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_h3 = tf.nn.relu(tf.matmul(valid_h2, weights_h3) + biases_h3)
  valid_h4 = tf.nn.relu(tf.matmul(valid_h3, weights_h4) + biases_h4)
  valid_logits = tf.matmul(valid_h4, 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_h3 = tf.nn.relu(tf.matmul(test_h2, weights_h3) + biases_h3)
  test_h4 = tf.nn.relu(tf.matmul(test_h3, weights_h4) + biases_h4)
  test_logits = tf.matmul(test_h4, weights_o) + biases_o
  test_prediction = tf.nn.softmax(test_logits)

In [8]:
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: 4.251674
Learning rate at step 0: 0.499950
Minibatch accuracy: 21.1%
Validation accuracy: 23.0%

Test accuracy: 23.8%

Minibatch loss at step 500: 1.578062
Learning rate at step 500: 0.475562
Minibatch accuracy: 89.1%
Validation accuracy: 86.0%

Minibatch loss at step 1000: 1.281381
Learning rate at step 1000: 0.452364
Minibatch accuracy: 86.7%
Validation accuracy: 86.3%

Minibatch loss at step 1500: 0.831393
Learning rate at step 1500: 0.430297
Minibatch accuracy: 93.0%
Validation accuracy: 87.7%

Minibatch loss at step 2000: 0.679063
Learning rate at step 2000: 0.409307
Minibatch accuracy: 93.8%
Validation accuracy: 87.8%

Test accuracy: 94.1%

Minibatch loss at step 2500: 0.668282
Learning rate at step 2500: 0.389340
Minibatch accuracy: 89.1%
Validation accuracy: 88.1%

Minibatch loss at step 3000: 0.638173
Learning rate at step 3000: 0.370348
Minibatch accuracy: 89.1%
Validation accuracy: 88.4%

Minibatch loss at step 3500: 0.595024
Learning rate at step 3500: 0.352282
Minibatch accuracy: 89.1%
Validation accuracy: 88.4%

Minibatch loss at step 4000: 0.476877
Learning rate at step 4000: 0.335098
Minibatch accuracy: 92.2%
Validation accuracy: 88.7%

Test accuracy: 94.7%

Minibatch loss at step 4500: 0.466525
Learning rate at step 4500: 0.318751
Minibatch accuracy: 90.6%
Validation accuracy: 88.8%

Minibatch loss at step 5000: 0.528854
Learning rate at step 5000: 0.303202
Minibatch accuracy: 89.1%
Validation accuracy: 89.3%

Minibatch loss at step 5500: 0.523381
Learning rate at step 5500: 0.288412
Minibatch accuracy: 87.5%
Validation accuracy: 88.7%

Minibatch loss at step 6000: 0.617525
Learning rate at step 6000: 0.274343
Minibatch accuracy: 87.5%
Validation accuracy: 88.6%

Test accuracy: 94.6%

Minibatch loss at step 6500: 0.385457
Learning rate at step 6500: 0.260960
Minibatch accuracy: 94.5%
Validation accuracy: 89.5%

Minibatch loss at step 7000: 0.548727
Learning rate at step 7000: 0.248230
Minibatch accuracy: 87.5%
Validation accuracy: 89.3%

Minibatch loss at step 7500: 0.513196
Learning rate at step 7500: 0.236121
Minibatch accuracy: 88.3%
Validation accuracy: 89.2%

Minibatch loss at step 8000: 0.578283
Learning rate at step 8000: 0.224603
Minibatch accuracy: 87.5%
Validation accuracy: 89.4%

Test accuracy: 94.9%

Minibatch loss at step 8500: 0.403704
Learning rate at step 8500: 0.213647
Minibatch accuracy: 93.0%
Validation accuracy: 89.9%

Minibatch loss at step 9000: 0.427125
Learning rate at step 9000: 0.203225
Minibatch accuracy: 92.2%
Validation accuracy: 89.2%

Minibatch loss at step 9500: 0.415645
Learning rate at step 9500: 0.193312
Minibatch accuracy: 92.2%
Validation accuracy: 89.9%

Minibatch loss at step 10000: 0.414826
Learning rate at step 10000: 0.183882
Minibatch accuracy: 90.6%
Validation accuracy: 89.8%

Test accuracy: 95.5%

Final test accuracy: 95.5%


In [ ]:


In [ ]: