AlexNet in TensorFlow

Credits: Forked from TensorFlow-Examples by Aymeric Damien

Setup

Refer to the setup instructions

In [2]:
# Import MINST data
import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
In [3]:
import tensorflow as tf
In [17]:
# Parameters
learning_rate = 0.001
training_iters = 300000
batch_size = 64
display_step = 100
In [5]:
# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.8 # Dropout, probability to keep units
In [6]:
# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)
In [7]:
# Create AlexNet model
def conv2d(name, l_input, w, b):
    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], 
                                                  padding='SAME'),b), name=name)

def max_pool(name, l_input, k):
    return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], 
                          padding='SAME', name=name)

def norm(name, l_input, lsize=4):
    return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)

def alex_net(_X, _weights, _biases, _dropout):
    # Reshape input picture
    _X = tf.reshape(_X, shape=[-1, 28, 28, 1])

    # Convolution Layer
    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
    # Max Pooling (down-sampling)
    pool1 = max_pool('pool1', conv1, k=2)
    # Apply Normalization
    norm1 = norm('norm1', pool1, lsize=4)
    # Apply Dropout
    norm1 = tf.nn.dropout(norm1, _dropout)

    # Convolution Layer
    conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
    # Max Pooling (down-sampling)
    pool2 = max_pool('pool2', conv2, k=2)
    # Apply Normalization
    norm2 = norm('norm2', pool2, lsize=4)
    # Apply Dropout
    norm2 = tf.nn.dropout(norm2, _dropout)

    # Convolution Layer
    conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])
    # Max Pooling (down-sampling)
    pool3 = max_pool('pool3', conv3, k=2)
    # Apply Normalization
    norm3 = norm('norm3', pool3, lsize=4)
    # Apply Dropout
    norm3 = tf.nn.dropout(norm3, _dropout)

    # Fully connected layer
    # Reshape conv3 output to fit dense layer input
    dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) 
    # Relu activation
    dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1')
    
    # Relu activation
    dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') 

    # Output, class prediction
    out = tf.matmul(dense2, _weights['out']) + _biases['out']
    return out
In [8]:
# Store layers weight & bias
weights = {
    'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
    'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
    'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
    'wd1': tf.Variable(tf.random_normal([4*4*256, 1024])),
    'wd2': tf.Variable(tf.random_normal([1024, 1024])),
    'out': tf.Variable(tf.random_normal([1024, 10]))
}
biases = {
    'bc1': tf.Variable(tf.random_normal([64])),
    'bc2': tf.Variable(tf.random_normal([128])),
    'bc3': tf.Variable(tf.random_normal([256])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'bd2': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
In [9]:
# Construct model
pred = alex_net(x, weights, biases, keep_prob)
In [10]:
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
In [11]:
# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
In [12]:
# Initializing the variables
init = tf.global_variables_initializer()
In [18]:
# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        # Fit training using batch data
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " \
                  + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    # Calculate accuracy for 256 mnist test images
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], 
                                                             y: mnist.test.labels[:256], 
                                                             keep_prob: 1.})
Iter 6400, Minibatch Loss= 29666.185547, Training Accuracy= 0.59375
Iter 12800, Minibatch Loss= 22125.562500, Training Accuracy= 0.60938
Iter 19200, Minibatch Loss= 22631.134766, Training Accuracy= 0.59375
Iter 25600, Minibatch Loss= 18498.414062, Training Accuracy= 0.62500
Iter 32000, Minibatch Loss= 11318.283203, Training Accuracy= 0.70312
Iter 38400, Minibatch Loss= 12076.280273, Training Accuracy= 0.70312
Iter 44800, Minibatch Loss= 8195.520508, Training Accuracy= 0.82812
Iter 51200, Minibatch Loss= 5176.181641, Training Accuracy= 0.84375
Iter 57600, Minibatch Loss= 8951.896484, Training Accuracy= 0.81250
Iter 64000, Minibatch Loss= 10096.946289, Training Accuracy= 0.78125
Iter 70400, Minibatch Loss= 11466.641602, Training Accuracy= 0.68750
Iter 76800, Minibatch Loss= 7469.824219, Training Accuracy= 0.78125
Iter 83200, Minibatch Loss= 4147.449219, Training Accuracy= 0.89062
Iter 89600, Minibatch Loss= 5904.782227, Training Accuracy= 0.82812
Iter 96000, Minibatch Loss= 718.493713, Training Accuracy= 0.93750
Iter 102400, Minibatch Loss= 2184.151367, Training Accuracy= 0.93750
Iter 108800, Minibatch Loss= 2354.463135, Training Accuracy= 0.89062
Iter 115200, Minibatch Loss= 8612.959961, Training Accuracy= 0.81250
Iter 121600, Minibatch Loss= 2225.773926, Training Accuracy= 0.84375
Iter 128000, Minibatch Loss= 160.583618, Training Accuracy= 0.96875
Iter 134400, Minibatch Loss= 1524.846069, Training Accuracy= 0.93750
Iter 140800, Minibatch Loss= 3501.871094, Training Accuracy= 0.89062
Iter 147200, Minibatch Loss= 661.977051, Training Accuracy= 0.96875
Iter 153600, Minibatch Loss= 367.857788, Training Accuracy= 0.98438
Iter 160000, Minibatch Loss= 1735.458740, Training Accuracy= 0.90625
Iter 166400, Minibatch Loss= 209.320374, Training Accuracy= 0.95312
Iter 172800, Minibatch Loss= 1788.553955, Training Accuracy= 0.90625
Iter 179200, Minibatch Loss= 912.995544, Training Accuracy= 0.93750
Iter 185600, Minibatch Loss= 2534.074463, Training Accuracy= 0.87500
Iter 192000, Minibatch Loss= 73.052612, Training Accuracy= 0.96875
Iter 198400, Minibatch Loss= 1609.606323, Training Accuracy= 0.93750
Iter 204800, Minibatch Loss= 1823.219727, Training Accuracy= 0.96875
Iter 211200, Minibatch Loss= 578.051086, Training Accuracy= 0.96875
Iter 217600, Minibatch Loss= 1532.326172, Training Accuracy= 0.89062
Iter 224000, Minibatch Loss= 769.775269, Training Accuracy= 0.95312
Iter 230400, Minibatch Loss= 2614.737793, Training Accuracy= 0.92188
Iter 236800, Minibatch Loss= 938.664368, Training Accuracy= 0.95312
Iter 243200, Minibatch Loss= 1520.495605, Training Accuracy= 0.93750
Iter 249600, Minibatch Loss= 657.419739, Training Accuracy= 0.95312
Iter 256000, Minibatch Loss= 522.802124, Training Accuracy= 0.90625
Iter 262400, Minibatch Loss= 211.188477, Training Accuracy= 0.96875
Iter 268800, Minibatch Loss= 520.451172, Training Accuracy= 0.92188
Iter 275200, Minibatch Loss= 1418.759155, Training Accuracy= 0.89062
Iter 281600, Minibatch Loss= 241.748596, Training Accuracy= 0.96875
Iter 288000, Minibatch Loss= 0.000000, Training Accuracy= 1.00000
Iter 294400, Minibatch Loss= 1535.772827, Training Accuracy= 0.92188
Optimization Finished!
Testing Accuracy: 0.980469