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 tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
import os
In [2]:
# Create data directory path
dpath = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
dpath = os.path.join(dpath, 'data')
# create pickle data file path
pickle_file = os.path.join(dpath,'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
# Note: wouldn't getting out of with remove save object?
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.
Note: Initial configuration was slightly changed while experimenting.
In [5]:
batch_size = 64
# patch_size is the size of the square of the 2d convolution (~)
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.
# layerX_weights are the kernels of the convolution
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):
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer1_biases)
conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer2_biases)
shape = hidden.get_shape().as_list()
# debug:
# print(shape)
# exit()
# shape[0] is batch size !
# we reshape to feed the output of the convolution layer to the fully connected hidden layer.
reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
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(labels=tf_train_labels, logits=logits))
# 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 = 5001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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 % 500 == 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))
In [7]:
batch_size = 64
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.
# layerX_weights are the kernels of the convolution
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]))
# we need to change layer 3 size because of the addition of max_pool
# 28//16 = 1 but we need 2 - hard code it for now!
layer3_weights = tf.Variable(tf.truncated_normal(
[(image_size // 16 +1) * (image_size // 16 +1) * 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):
# print(data.get_shape().as_list())
# [64, 28, 28, 1]
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer1_biases)
# print(hidden.get_shape().as_list())
# [64, 14, 14, 16]
mpool = tf.nn.max_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
# print(mpool.get_shape().as_list())
# [64, 7, 7, 16]
conv = tf.nn.conv2d(mpool, layer2_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer2_biases)
# print(hidden.get_shape().as_list())
# [64, 4, 4, 16]
mpool = tf.nn.max_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
shape = mpool.get_shape().as_list()
# print(shape)
# [64, 2, 2, 16]
reshape = tf.reshape(mpool, [shape[0], shape[1] * shape[2] * shape[3]])
# print(reshape.get_shape().as_list())
# [64, 64]
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
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(labels=tf_train_labels, logits=logits))
# 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 [8]:
num_steps = 5001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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 % 500 == 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))
We got almost the same accuracy as with the previous effort. We likely didn't make efficient use of max pooling. Let's try again:
In [9]:
batch_size = 64
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.
# layerX_weights are the kernels of the convolution
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]))
# we need to change layer 3 size because of the addition of max_pool
# 28//16 = 1 but we need 2 - hard code it for now!
layer3_weights = tf.Variable(tf.truncated_normal(
[round(image_size / 8) * round(image_size / 8) * 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):
# print(data.get_shape().as_list())
# [64, 28, 28, 1]
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer1_biases)
# print(hidden.get_shape().as_list())
# [64, 14, 14, 16]
mpool = tf.nn.max_pool(hidden, [1, 2, 2, 1], [1, 1, 2, 1], padding='SAME')
# print(mpool.get_shape().as_list())
# [64, 7, 7, 16]
conv = tf.nn.conv2d(mpool, layer2_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer2_biases)
# print(hidden.get_shape().as_list())
# [64, 4, 4, 16]
mpool = tf.nn.max_pool(hidden, [1, 2, 2, 1], [1, 2, 1, 1], padding='SAME')
shape = mpool.get_shape().as_list()
# print(shape)
# [64, 2, 2, 16]
reshape = tf.reshape(mpool, [shape[0], shape[1] * shape[2] * shape[3]])
# print(reshape.get_shape().as_list())
# [64, 64]
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
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(labels=tf_train_labels, logits=logits))
# 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 [10]:
num_steps = 5001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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 % 500 == 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))
We got slightly better results. Seems like two max pools after each convolution on such a small image size was excessive.
In [11]:
batch_size = 64
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.
# layerX_weights are the kernels of the convolution
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]))
# we need to change layer 3 size because of the addition of max_pool
# 28//16 = 1 but we need 2 - hard code it for now!
layer3_weights = tf.Variable(tf.truncated_normal(
[round(image_size / 8) * round(image_size / 8) * 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):
# print(data.get_shape().as_list())
# [64, 28, 28, 1]
conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer1_biases)
# print(hidden.get_shape().as_list())
# [64, 14, 14, 16]
mpool = tf.nn.max_pool(hidden, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
# print(mpool.get_shape().as_list())
# [64, 7, 7, 16]
conv = tf.nn.conv2d(mpool, layer2_weights, [1, 2, 2, 1], padding='SAME')
hidden = tf.nn.relu(conv + layer2_biases)
shape = hidden.get_shape().as_list()
# print(shape)
# [64, 4, 4, 16]
reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
# print(reshape.get_shape().as_list())
# [64, 256]
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
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(labels=tf_train_labels, logits=logits))
# 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 [12]:
num_steps = 5001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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 % 500 == 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))
Looks like putting the max_pooling operations together offers almost, but not exactly the same, performance as doing them separately.
Try to get the best performance you can use a convolutional net. Look for example at the classic LeNet5 architecture, adding Dropout, and/or adding learning rate decay.
We use figure 2 from Gradient-Based Learning Applied to Document Recognition as a guide in creating the model infrastructure.
In [13]:
batch_size = 64
patch_size = 5
depth1 = 6
depth2 = 16
num_hidden1 = 120
num_hidden2 = 84
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.
# C1 layer:
layer1_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, num_channels, depth1], stddev=0.1))
layer1_biases = tf.Variable(tf.zeros([depth1]))
# S2 avg_pool - no need to specify weights
# C3 layer:
layer2_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, depth1, depth2], stddev=0.1))
layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth2]))
# S4 avg_pool - no need to specify weights
# C5 hidden1
size = ((image_size - patch_size + 1) // 2 - patch_size + 1) // 2
layer3_weights = tf.Variable(tf.truncated_normal(
[size * size * depth2, num_hidden1], stddev=np.sqrt(2.0 / num_hidden1)))
layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden1]))
# F6 hidden2
layer4_weights = tf.Variable(tf.truncated_normal(
[num_hidden1, num_hidden2], stddev=np.sqrt(2.0 / num_hidden2)))
layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden2]))
# Output
layer5_weights = tf.Variable(tf.truncated_normal(
[num_hidden2, num_labels], stddev=0.1))
layer5_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
# Model.
def model(data):
# C1 input 28 x 28
conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer1_biases)
# S2 input 24 x 24
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C3 input 12 x 12
conv = tf.nn.conv2d(pool, layer2_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer2_biases)
# S4 input 8 x 8
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C5 input 4 x 4
shape = pool.get_shape().as_list()
reshape = tf.reshape(pool, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# F6
hidden = tf.nn.relu(tf.matmul(hidden, layer4_weights) + layer4_biases)
# return output logits
return (tf.matmul(hidden, layer5_weights) + layer5_biases)
# Training computation.
logits = model(tf_train_dataset)
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=tf_train_labels))
# Optimizer - with variable learning rate.
gstep = tf.Variable(0) # steps taken
ilrate = tf.placeholder(tf.float32)
flrate = tf.train.exponential_decay(ilrate, gstep, 4000, 0.6)
optimizer = tf.train.MomentumOptimizer(flrate, momentum=0.9, use_nesterov=True).minimize(
loss, global_step=gstep)
# # Optimizer.
# optimizer = tf.train.GradientDescentOptimizer(0.005).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 [14]:
num_steps = 20001
# learning rate (initial)
learning_rate_i = 0.01
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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,
ilrate : learning_rate_i}
_, 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%%' % accuracy(predictions, batch_labels))
print('Validation accuracy: %.1f%%' % accuracy(
valid_prediction.eval(), valid_labels))
print("Current learning rate: {}".format(flrate.eval(feed_dict=feed_dict)))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
Even though this is not as accurate as we have gotten with 4 fully connected layers (97.4%) it is close (and we have not fully optimised it).
Let's try tweaking the LeNet-5 architecture:
In [15]:
batch_size = 128
patch_size = 5
depth1 = 10
depth2 = 30
num_hidden1 = 240
num_hidden2 = 160
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.
# C1 layer:
layer1_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, num_channels, depth1], stddev=0.1))
layer1_biases = tf.Variable(tf.zeros([depth1]))
# S2 avg_pool - no need to specify weights
# C3 layer:
layer2_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, depth1, depth2], stddev=0.1))
layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth2]))
# S4 avg_pool - no need to specify weights
# C5 hidden1
size = ((image_size - patch_size + 1) // 2 - patch_size + 1) // 2
layer3_weights = tf.Variable(tf.truncated_normal(
[size * size * depth2, num_hidden1], stddev=np.sqrt(0.025 / num_hidden1)))
layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden1]))
# F6 hidden2
layer4_weights = tf.Variable(tf.truncated_normal(
[num_hidden1, num_hidden2], stddev=np.sqrt(0.025 / num_hidden2)))
layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden2]))
# Output
layer5_weights = tf.Variable(tf.truncated_normal(
[num_hidden2, num_labels], stddev=np.sqrt(0.025 / num_labels)))
layer5_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))
# Model.
def model(data):
# C1 input 28 x 28
conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer1_biases)
# S2 input 24 x 24
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C3 input 12 x 12
conv = tf.nn.conv2d(pool, layer2_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer2_biases)
# S4 input 8 x 8
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C5 input 4 x 4
shape = pool.get_shape().as_list()
reshape = tf.reshape(pool, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# F6
hidden = tf.nn.relu(tf.matmul(hidden, layer4_weights) + layer4_biases)
# return output logits
return (tf.matmul(hidden, layer5_weights) + layer5_biases)
# Training computation.
logits = model(tf_train_dataset)
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=tf_train_labels))
# Optimizer - with variable learning rate.
gstep = tf.Variable(0) # steps taken
ilrate = tf.placeholder(tf.float32)
flrate = tf.train.exponential_decay(ilrate, gstep, 8000, 0.5)
optimizer = tf.train.MomentumOptimizer(flrate, momentum=0.9, use_nesterov=True).minimize(
loss, global_step=gstep)
# # Optimizer.
# optimizer = tf.train.GradientDescentOptimizer(0.005).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 [16]:
num_steps = 20001
# learning rate (initial)
learning_rate_i = 0.01
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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,
ilrate : learning_rate_i}
_, 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%%' % accuracy(predictions, batch_labels))
print('Validation accuracy: %.1f%%' % accuracy(
valid_prediction.eval(), valid_labels))
print("Current learning rate: {}".format(flrate.eval(feed_dict=feed_dict)))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
In [17]:
batch_size = 128
patch_size = 5
depth1 = 10
depth2 = 30
num_hidden1 = 240
num_hidden2 = 160
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.
# C1 layer:
layer1_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, num_channels, depth1], stddev=0.1))
layer1_biases = tf.Variable(tf.zeros([depth1]))
# S2 avg_pool - no need to specify weights
# C3 layer:
layer2_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, depth1, depth2], stddev=0.1))
layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth2]))
# S4 avg_pool - no need to specify weights
# C5 hidden1
size = ((image_size - patch_size + 1) // 2 - patch_size + 1) // 2
layer3_weights = tf.Variable(tf.truncated_normal(
[size * size * depth2, num_hidden1], stddev=np.sqrt(1 / num_hidden1)))
layer3_biases = tf.Variable(tf.constant(0.01, shape=[num_hidden1]))
# F6 hidden2
layer4_weights = tf.Variable(tf.truncated_normal(
[num_hidden1, num_hidden2], stddev=np.sqrt(1 / num_hidden2)))
layer4_biases = tf.Variable(tf.constant(0.01, shape=[num_hidden2]))
# Output
layer5_weights = tf.Variable(tf.truncated_normal(
[num_hidden2, num_labels], stddev=np.sqrt(1 / num_labels)))
layer5_biases = tf.Variable(tf.constant(0.01, shape=[num_labels]))
# Model.
def model(data):
# C1 input 28 x 28
conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer1_biases)
# S2 input 24 x 24
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C3 input 12 x 12
conv = tf.nn.conv2d(pool, layer2_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer2_biases)
# S4 input 8 x 8
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C5 input 4 x 4
shape = pool.get_shape().as_list()
reshape = tf.reshape(pool, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
# F6
hidden = tf.nn.relu(tf.matmul(hidden, layer4_weights) + layer4_biases)
# return output logits
return (tf.matmul(hidden, layer5_weights) + layer5_biases)
# Training computation.
logits = model(tf_train_dataset)
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=tf_train_labels))
# add regularisation for all weights.
regconst = tf.placeholder(tf.float32)
loss = loss + regconst * (
tf.nn.l2_loss(layer3_weights) + tf.nn.l2_loss(layer4_weights) + tf.nn.l2_loss(layer5_weights))
# Optimizer - with variable learning rate.
gstep = tf.Variable(0) # steps taken
ilrate = tf.placeholder(tf.float32)
flrate = tf.train.exponential_decay(ilrate, gstep, 8000, 0.75)
optimizer = tf.train.MomentumOptimizer(flrate, momentum=0.9, use_nesterov=True).minimize(
loss, global_step=gstep)
# # Optimizer.
# optimizer = tf.train.GradientDescentOptimizer(0.005).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 [18]:
num_steps = 20001
# learning rate (initial)
learning_rate_i = 0.01
# regularisation constant
gamma = 0.00001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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,
regconst : gamma,
ilrate : learning_rate_i}
_, l, predictions = session.run(
[optimizer, loss, train_prediction], feed_dict=feed_dict)
if (step % 2000 == 0 or step in ([250, 500, 750, 1000])):
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("Current learning rate: {}".format(flrate.eval(feed_dict=feed_dict)))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
Regularisation didn't significantly improve permormance. Let's try dropout.
In [19]:
batch_size = 128
patch_size = 5
depth1 = 10
depth2 = 30
num_hidden1 = 240
num_hidden2 = 160
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.
# C1 layer:
layer1_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, num_channels, depth1], stddev=0.1))
layer1_biases = tf.Variable(tf.zeros([depth1]))
# S2 avg_pool - no need to specify weights
# C3 layer:
layer2_weights = tf.Variable(tf.truncated_normal(
[patch_size, patch_size, depth1, depth2], stddev=0.1))
layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth2]))
# S4 avg_pool - no need to specify weights
# C5 hidden1
size = ((image_size - patch_size + 1) // 2 - patch_size + 1) // 2
layer3_weights = tf.Variable(tf.truncated_normal(
[size * size * depth2, num_hidden1], stddev=np.sqrt(1 / num_hidden1)))
layer3_biases = tf.Variable(tf.constant(0.01, shape=[num_hidden1]))
# F6 hidden2
layer4_weights = tf.Variable(tf.truncated_normal(
[num_hidden1, num_hidden2], stddev=np.sqrt(1 / num_hidden2)))
layer4_biases = tf.Variable(tf.constant(0.01, shape=[num_hidden2]))
# Output
layer5_weights = tf.Variable(tf.truncated_normal(
[num_hidden2, num_labels], stddev=np.sqrt(1 / num_labels)))
layer5_biases = tf.Variable(tf.constant(0.01, shape=[num_labels]))
# introduce dropout
keep_prob = tf.placeholder(tf.float32)
# Model.
def model(data):
# C1 input 28 x 28
conv = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer1_biases)
# S2 input 24 x 24
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C3 input 12 x 12
conv = tf.nn.conv2d(pool, layer2_weights, [1, 1, 1, 1], padding='VALID')
layer = tf.nn.relu(conv + layer2_biases)
# S4 input 8 x 8
pool = tf.nn.max_pool(layer, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
# C5 input 4 x 4
shape = pool.get_shape().as_list()
reshape = tf.reshape(pool, [shape[0], shape[1] * shape[2] * shape[3]])
hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
hidden_d = tf.nn.dropout(hidden, keep_prob)
# F6
hidden = tf.nn.relu(tf.matmul(hidden, layer4_weights) + layer4_biases)
hidden2 = tf.nn.relu(tf.matmul(hidden_d, layer4_weights) + layer4_biases)
hidden_d = tf.nn.dropout(hidden2, keep_prob)
# return output logits
output = (tf.matmul(hidden, layer5_weights) + layer5_biases)
output_d = (tf.matmul(hidden_d, layer5_weights) + layer5_biases)
# dropput passes through both fully connected layers.
return ([output_d, output])
# Training computation.
logits = model(tf_train_dataset)[0]
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=logits,
labels=tf_train_labels))
# add regularisation for all weights.
regconst = tf.placeholder(tf.float32)
loss = loss + regconst * (
tf.nn.l2_loss(layer3_weights) + tf.nn.l2_loss(layer4_weights) +
tf.nn.l2_loss(layer5_weights))
# Optimizer - with variable learning rate.
gstep = tf.Variable(0) # steps taken
ilrate = tf.placeholder(tf.float32)
flrate = tf.train.exponential_decay(ilrate, gstep, 8000, 0.75)
optimizer = tf.train.MomentumOptimizer(flrate, momentum=0.9, use_nesterov=True).minimize(
loss, global_step=gstep)
# # Optimizer.
# optimizer = tf.train.GradientDescentOptimizer(0.005).minimize(loss)
# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(model(tf_train_dataset)[1])
valid_prediction = tf.nn.softmax(model(tf_valid_dataset)[1])
test_prediction = tf.nn.softmax(model(tf_test_dataset)[1])
In [20]:
num_steps = 20001
# learning rate (initial)
learning_rate_i = 0.01
# regularisation constant
gamma = 1e-5
# dropout layer keep probability
keep_probl = 0.8 # cannot have the same name as graph variable!
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().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,
regconst : gamma,
keep_prob : keep_probl,
ilrate : learning_rate_i}
_, l, predictions = session.run(
[optimizer, loss, train_prediction], feed_dict=feed_dict)
if (step % 2000 == 0 or step in ([250, 500, 750, 1000])):
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("Current learning rate: {}".format(flrate.eval(feed_dict=feed_dict)))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))