Previously in 2_fullyconnected.ipynb
and 3_regularization.ipynb
, we trained fully connected networks to classify notMNIST characters.
The goal of this assignment is make the neural network convolutional.
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 time
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
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 TensorFlow-friendly shape:
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)
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])
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):
# cnn-input: 16 x 28 x 28 x 1, num_samples = 16
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
# cnn-hidden: 16 x (14 x 14 x 16)
hidden = tf.nn.relu(conv + layer1_biases)
conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
# cnn-hidden: 16 x 7 x 7 x 16
hidden = tf.nn.relu(conv + layer2_biases)
shape = hidden.get_shape().as_list()
# num_features = 7 x 7 x 16
# num_samples = 16
reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
# fnn-hidden: matmul(16 x (7 x 7 x 16), (28 // 4 x 28 // 4 x 16, 64))
# fnn-hidden: num_features = 64
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# num_labels = 10
# fnn-output: matmul(16 x 64, 64 x 10) = (16, 10)
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.
optimizer = tf.train.GradientDescentOptimizer(0.05).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:
tic = time.time()
try:
tf.global_variables_initializer().run()
except AttributeError:
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 % 50 == 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))
print("Time: %.3f s" % (time.time() - tic))
In [11]:
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
num_steps = 1001
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):
# cnn-input: max_pooling, kernel_size = 2, strides = 2
conv = tf.nn.max_pool(data, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
# cnn-hidden: 16 x (14 x 14 x 16)
# arithmetic: (i - k) / s + 1 = (28 - 2) / 2 + 1 = 14
hidden = tf.nn.relu(conv + layer1_biases)
conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
# cnn-hidden: 16 x 7 x 7 x 16
print(conv.get_shape(), layer2_biases.get_shape())
hidden = tf.nn.relu(conv + layer2_biases)
shape = hidden.get_shape().as_list()
# num_features = 16 x 7 x 7 x 16
# num_samples = 16
reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
# fnn-hidden: matmul(16 x (7 x 7 x 16), (28 // 4 x 28 // 4 x 16, 64))
# fnn-hidden: num_features = 64
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# num_labels = 10
# fnn-output: matmul(16 x 64, 64 x 10) = (16, 10)
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.
optimizer = tf.train.GradientDescentOptimizer(0.05).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))
with tf.Session(graph=graph) as session:
tic = time.time()
try:
tf.global_variables_initializer().run()
except AttributeError:
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 % 50 == 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))
print("Time: %.3f s" % (time.time() - tic))
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 [9]:
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
num_steps = 1001
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)
layers = {}
weights = {}
bias = {}
scales = {}
depth = {'C1': 6, 'S2': 6, 'C3': 10, 'S4': 10, 'C5': 16}
weights['C1'] = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth['C1']], stddev=0.1))
bias['C1'] = tf.Variable(tf.zeros([depth['C1']]))
bias['S2'] = tf.Variable(tf.zeros([depth['S2']]))
scales['S2'] = tf.Variable(tf.ones([depth['S2']]))
weights['C3'] = tr.Variable(tf.truncated_normal([patch_size, patch_size, depth['S2'], depth['C3']], stddev=0.1))
bias['C3'] = tf.Variable(tf.zeros([depth['C3']]))
bias['S4'] = tf.Variable(tf.zeros([depth['S4']]))
scales['S4'] = tf.Variable(tf.ones([depth['S4']]))
weights['C5'] = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth['S4'], depth['C5']], stddev=0.1))
bias['C5'] = tf.Variable(tf.zeros([depth['C5']]))
weights['F6'] = tf.Variable(tf.truncated_normal([batch_size, 84], stddev=0.1))
bias['F6'] = tf.Variable(tf.zeros([84]))
weights['F7'] = tf.Variable(tf.truncated_normal([batch_size, 10], stddev=0.1))
def squashing(target, scale):
return 1.7159 * tf.tanh(scale * target)
def rbf(x, w):
pass
# Model.
def lenet5_model(data, for_training=True):
""" A tensorflow implementation of LeNet5. """
# C1: Conv2D, 28 x 28 x 6
layers['C1'] = tf.nn.conv2d(data, weights['C1'], [1, 1, 1, 1], padding='SAME')
hidden = layers['C1'] + bias['C1']
# S2: Scaled average pooling with bias, 14 x 14 x 6
layers['S2'] = tf.nn.avg_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
hidden = squashing(layers['S2'] + bias['S2'], scales['S2'])
# C3: Conv2D, partial connected, 10 x 10 x 16
layers['C3'] = tf.nn.conv2d(hidden, weights['C3'], [1, 1, 1, 1], padding='SAME')
hidden = layers['C3'] + bias['C3']
# S4: Scaled average pooling with bias, 5 x 5 x 16
layers['S4'] = tf.nn.avg_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
hidden = squashing(layers['S4'] + bias['S4'], scales['S4'])
# C5: Conv2D, 5 x 5 x 16
layers['C5'] = tf.nn.conv2d(hidden, weights['C5'], [1, 1, 1, 1], padding='SAME')
hidden = layers['C5'] + bias['C5']
# F6: FullConnected, 84 nodes
hidden = tf.reshape(hidden, (-1, 84))
layers['F6'] = tf.matmul(hidden, weights['F6'])
hidden = tf.sigmoid(layers['F6'] + bias['F6'])
# F7: RBF Kernel, 10 nodes
return rbf(hidden, weights['F7'])
# Training computation.
logits = model(tf_train_dataset)
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
# Optimizer.
optimizer = tf.train.GradientDescentOptimizer(0.05).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, False))
test_prediction = tf.nn.softmax(model(tf_test_dataset, False))
with tf.Session(graph=graph) as session:
tic = time.time()
try:
tf.global_variables_initializer().run()
except AttributeError:
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 % 50 == 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))
print("Time: %.3f s" % (time.time() - tic))