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
First reload the data we generated in notmist.ipynb.
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)
Reformat into a shape that's more adapted to the models we're going to train:
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 acc(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
Introduce and tune L2 regularization for both logistic and neural network models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor t
using nn.l2_loss(t)
. The right amount of regularization should improve your validation / test accuracy.
In [5]:
batch_size = 128
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)
# Variables.
weights = tf.Variable(
tf.truncated_normal([image_size * image_size, num_labels]))
biases = tf.Variable(tf.zeros([num_labels]))
# Training computation.
logits = tf.matmul(tf_train_dataset, weights) + biases
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
# Optimizer.
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss + 5e-4 * tf.nn.l2_loss(weights))
# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(logits)
valid_prediction = tf.nn.softmax(
tf.matmul(tf_valid_dataset, weights) + biases)
test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)
In [6]:
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 % 1000 == 0):
print("Minibatch loss at step %d: %f" % (step, l))
print("Minibatch accuracy: %.1f%%" % acc(predictions, batch_labels))
print("Validation accuracy: %.1f%%" % acc(
valid_prediction.eval(), valid_labels))
print("Test accuracy: %.1f%%" % acc(test_prediction.eval(), test_labels))
In [7]:
batch_size = 128
num_hidden = 2048
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.
x = tf.placeholder(tf.float32, shape=(None, image_size * image_size))
y_ = tf.placeholder(tf.float32, shape=(None, num_labels))
keep_prob = tf.placeholder('float')
# Variables. (Input -> Hidden)
w_1 = tf.Variable(
tf.truncated_normal([image_size * image_size, num_hidden]))
b_1 = tf.Variable(tf.zeros([num_hidden]))
# Training computation. (Input -> Hidden)
h_1 = tf.nn.dropout(tf.nn.relu(tf.matmul(x, w_1) + b_1), 0.5)
# Variables. (Hidden -> Output)
w_2 = tf.Variable(
tf.truncated_normal([num_hidden, num_labels]))
b_2 = tf.Variable(tf.zeros([num_labels]))
# Training computation. (Hidden -> Output)
h_2 = tf.matmul(h_1, w_2) + b_2
# Loss
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(h_2, y_))
# Optimizer.
optimizer = tf.train.AdagradOptimizer(1e-3).minimize(loss + 5e-4 * (tf.nn.l2_loss(w_1) + tf.nn.l2_loss(w_2)))
# Predictions for the training, validation, and test data.
prediction = tf.nn.softmax(h_2)
correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
In [8]:
num_steps = 30001
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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
_, l = session.run(
[optimizer, loss], feed_dict=feed_dict)
if (step % 2000 == 0):
print("Minibatch loss at step %d: %f" % (step, l))
print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))
In [9]:
num_steps = 30001
train_data_size = 1000
part_train_dataset = train_dataset[:train_data_size, :]
part_train_labels = train_labels[:train_data_size]
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) % (part_train_labels.shape[0] - batch_size)
# Generate a minibatch.
batch_data = part_train_dataset[offset:(offset + batch_size), :]
batch_labels = part_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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
_, l = session.run(
[optimizer, loss], feed_dict=feed_dict)
if (step % 2000 == 0):
print("Minibatch loss at step %d: %f" % (step, l))
print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))
Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides nn.dropout()
for that, but you have to make sure it's only inserted during training.
What happens to our extreme overfitting case?
Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is 97.1%.
One avenue you can explore is to add multiple layers.
Another one is to use learning rate decay:
global_step = tf.Variable(0) # count the number of steps taken.
learning_rate = tf.train.exponential_decay(0.5, global_step, ...)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
In [10]:
batch_size = 128
num_hidden_1 = 2048
num_hidden_2 = 1024
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.
x = tf.placeholder(tf.float32, shape=(None, image_size * image_size))
y_ = tf.placeholder(tf.float32, shape=(None, num_labels))
keep_prob = tf.placeholder('float')
# Input -> Hidden1
w_1 = tf.Variable(
tf.truncated_normal([image_size * image_size, num_hidden_1]))
b_1 = tf.Variable(tf.zeros([num_hidden_1]))
h_1 = tf.nn.dropout(tf.nn.relu(tf.matmul(x, w_1) + b_1), keep_prob)
# Hidden1 -> Hidden2
w_2 = tf.Variable(
tf.truncated_normal([num_hidden_1, num_hidden_2]))
b_2 = tf.Variable(tf.zeros([num_hidden_2]))
h_2 = tf.nn.dropout(tf.nn.relu(tf.matmul(h_1, w_2) + b_2), keep_prob)
# Hidden2 -> Output
w_3 = tf.Variable(
tf.truncated_normal([num_hidden_2, num_labels]))
b_3 = tf.Variable(tf.zeros([num_labels]))
h_3 = tf.matmul(h_2, w_3) + b_3
# Loss
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(h_3, y_))
# Optimizer.
optimizer = tf.train.AdagradOptimizer(1e-3).minimize(loss + 1e-5 * (tf.nn.l2_loss(w_1) + tf.nn.l2_loss(w_2) + tf.nn.l2_loss(w_3)))
# Predictions for the training, validation, and test data.
prediction = tf.nn.softmax(h_3)
correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
In [11]:
num_steps = 30001
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 = {x: batch_data, y_: batch_labels, keep_prob: 0.5}
_, l = session.run(
[optimizer, loss], feed_dict=feed_dict)
if (step % 2000 == 0):
print("Minibatch loss at step %d: %f" % (step, l))
print("Validation accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: valid_dataset, y_: valid_labels, keep_prob: 1.0}) * 100))
print("Test accuracy: %.1f%%" % (accuracy.eval(feed_dict={x: test_dataset, y_: test_labels, keep_prob: 1.0}) * 100))