Convolutional Neural Network 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 [18]:
# Parameters
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 20

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.75 # 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 [8]:
# Create model
def conv2d(img, w, b):
    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(img, w, strides=[1, 1, 1, 1], 
                                                  padding='SAME'),b))

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

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

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

    # Convolution Layer
    conv2 = conv2d(conv1, _weights['wc2'], _biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = max_pool(conv2, k=2)
    # Apply Dropout
    conv2 = tf.nn.dropout(conv2, _dropout)

    # Fully connected layer
    # Reshape conv2 output to fit dense layer input
    dense1 = tf.reshape(conv2, [-1, _weights['wd1'].get_shape().as_list()[0]]) 
    # Relu activation
    dense1 = tf.nn.relu(tf.add(tf.matmul(dense1, _weights['wd1']), _biases['bd1']))
    # Apply Dropout
    dense1 = tf.nn.dropout(dense1, _dropout) # Apply Dropout

    # Output, class prediction
    out = tf.add(tf.matmul(dense1, _weights['out']), _biases['out'])
    return out

In [9]:
# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])), 
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])), 
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])), 
    # 1024 inputs, 10 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_classes])) 
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

In [10]:
# Construct model
pred = conv_net(x, weights, biases, keep_prob)

In [11]:
# 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 [12]:
# 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 [13]:
# Initializing the variables
init = tf.initialize_all_variables()

In [19]:
# 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 2560, Minibatch Loss= 26046.011719, Training Accuracy= 0.21094
Iter 5120, Minibatch Loss= 10456.769531, Training Accuracy= 0.52344
Iter 7680, Minibatch Loss= 6273.207520, Training Accuracy= 0.71875
Iter 10240, Minibatch Loss= 6276.231445, Training Accuracy= 0.64062
Iter 12800, Minibatch Loss= 4188.221680, Training Accuracy= 0.77344
Iter 15360, Minibatch Loss= 2717.077637, Training Accuracy= 0.80469
Iter 17920, Minibatch Loss= 4057.120361, Training Accuracy= 0.81250
Iter 20480, Minibatch Loss= 1696.550415, Training Accuracy= 0.87500
Iter 23040, Minibatch Loss= 2525.317627, Training Accuracy= 0.85938
Iter 25600, Minibatch Loss= 2341.906738, Training Accuracy= 0.87500
Iter 28160, Minibatch Loss= 4200.535156, Training Accuracy= 0.79688
Iter 30720, Minibatch Loss= 1888.964355, Training Accuracy= 0.89062
Iter 33280, Minibatch Loss= 2167.645996, Training Accuracy= 0.84375
Iter 35840, Minibatch Loss= 1932.107544, Training Accuracy= 0.89844
Iter 38400, Minibatch Loss= 1562.430054, Training Accuracy= 0.90625
Iter 40960, Minibatch Loss= 1676.755249, Training Accuracy= 0.84375
Iter 43520, Minibatch Loss= 1003.626099, Training Accuracy= 0.93750
Iter 46080, Minibatch Loss= 1176.615479, Training Accuracy= 0.86719
Iter 48640, Minibatch Loss= 1260.592651, Training Accuracy= 0.88281
Iter 51200, Minibatch Loss= 1399.667969, Training Accuracy= 0.86719
Iter 53760, Minibatch Loss= 1259.961426, Training Accuracy= 0.89844
Iter 56320, Minibatch Loss= 1415.800781, Training Accuracy= 0.89062
Iter 58880, Minibatch Loss= 1835.365967, Training Accuracy= 0.85156
Iter 61440, Minibatch Loss= 1395.168823, Training Accuracy= 0.90625
Iter 64000, Minibatch Loss= 973.283569, Training Accuracy= 0.88281
Iter 66560, Minibatch Loss= 818.093811, Training Accuracy= 0.92969
Iter 69120, Minibatch Loss= 1178.744263, Training Accuracy= 0.92188
Iter 71680, Minibatch Loss= 845.889709, Training Accuracy= 0.89844
Iter 74240, Minibatch Loss= 1259.505615, Training Accuracy= 0.90625
Iter 76800, Minibatch Loss= 738.037109, Training Accuracy= 0.89844
Iter 79360, Minibatch Loss= 862.499146, Training Accuracy= 0.93750
Iter 81920, Minibatch Loss= 739.704041, Training Accuracy= 0.90625
Iter 84480, Minibatch Loss= 652.880310, Training Accuracy= 0.95312
Iter 87040, Minibatch Loss= 635.464600, Training Accuracy= 0.92969
Iter 89600, Minibatch Loss= 933.166626, Training Accuracy= 0.90625
Iter 92160, Minibatch Loss= 213.874893, Training Accuracy= 0.96094
Iter 94720, Minibatch Loss= 609.575684, Training Accuracy= 0.91406
Iter 97280, Minibatch Loss= 560.208008, Training Accuracy= 0.93750
Iter 99840, Minibatch Loss= 963.577148, Training Accuracy= 0.90625
Optimization Finished!
Testing Accuracy: 0.960938