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