Recurrent 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)

import tensorflow as tf
from tensorflow.models.rnn import rnn, rnn_cell
import numpy as np
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]:
'''
To classify images using a reccurent neural network, we consider every image row as a sequence of pixels.
Because MNIST image shape is 28*28px, we will then handle 28 sequences of 28 steps for every sample.
'''

# Parameters
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Network Parameters
n_input = 28 # MNIST data input (img shape: 28*28)
n_steps = 28 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 10 # MNIST total classes (0-9 digits)
In [4]:
# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
istate = tf.placeholder("float", [None, 2*n_hidden]) #state & cell => 2x n_hidden
y = tf.placeholder("float", [None, n_classes])

# Define weights
weights = {
    'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights
    'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
    'hidden': tf.Variable(tf.random_normal([n_hidden])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
In [5]:
def RNN(_X, _istate, _weights, _biases):

    # input shape: (batch_size, n_steps, n_input)
    _X = tf.transpose(_X, [1, 0, 2])  # permute n_steps and batch_size
    # Reshape to prepare input to hidden activation
    _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)
    # Linear activation
    _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']

    # Define a lstm cell with tensorflow
    lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
    # Split data because rnn cell needs a list of inputs for the RNN inner loop
    _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)

    # Get lstm cell output
    outputs, states = rnn.rnn(lstm_cell, _X, initial_state=_istate)

    # Linear activation
    # Get inner loop last output
    return tf.matmul(outputs[-1], _weights['out']) + _biases['out']
In [6]:
pred = RNN(x, istate, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer

# 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 [7]:
# Initializing the variables
init = tf.global_variables_initializer()

# 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)
        # Reshape data to get 28 seq of 28 elements
        batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))
        # Fit training using batch data
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys,
                                       istate: np.zeros((batch_size, 2*n_hidden))})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,
                                                istate: np.zeros((batch_size, 2*n_hidden))})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,
                                             istate: np.zeros((batch_size, 2*n_hidden))})
            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
    test_len = 256
    test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
    test_label = mnist.test.labels[:test_len]
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label,
                                                             istate: np.zeros((test_len, 2*n_hidden))})
Iter 1280, Minibatch Loss= 1.888242, Training Accuracy= 0.39844
Iter 2560, Minibatch Loss= 1.519879, Training Accuracy= 0.47656
Iter 3840, Minibatch Loss= 1.238005, Training Accuracy= 0.63281
Iter 5120, Minibatch Loss= 0.933760, Training Accuracy= 0.71875
Iter 6400, Minibatch Loss= 0.832130, Training Accuracy= 0.73438
Iter 7680, Minibatch Loss= 0.979760, Training Accuracy= 0.70312
Iter 8960, Minibatch Loss= 0.821921, Training Accuracy= 0.71875
Iter 10240, Minibatch Loss= 0.710566, Training Accuracy= 0.79688
Iter 11520, Minibatch Loss= 0.578501, Training Accuracy= 0.82812
Iter 12800, Minibatch Loss= 0.765049, Training Accuracy= 0.75000
Iter 14080, Minibatch Loss= 0.582995, Training Accuracy= 0.78125
Iter 15360, Minibatch Loss= 0.575092, Training Accuracy= 0.79688
Iter 16640, Minibatch Loss= 0.701214, Training Accuracy= 0.75781
Iter 17920, Minibatch Loss= 0.561972, Training Accuracy= 0.78125
Iter 19200, Minibatch Loss= 0.394480, Training Accuracy= 0.85938
Iter 20480, Minibatch Loss= 0.356244, Training Accuracy= 0.91406
Iter 21760, Minibatch Loss= 0.632163, Training Accuracy= 0.78125
Iter 23040, Minibatch Loss= 0.269334, Training Accuracy= 0.90625
Iter 24320, Minibatch Loss= 0.485007, Training Accuracy= 0.86719
Iter 25600, Minibatch Loss= 0.569704, Training Accuracy= 0.78906
Iter 26880, Minibatch Loss= 0.267697, Training Accuracy= 0.92188
Iter 28160, Minibatch Loss= 0.381177, Training Accuracy= 0.90625
Iter 29440, Minibatch Loss= 0.350800, Training Accuracy= 0.87500
Iter 30720, Minibatch Loss= 0.356782, Training Accuracy= 0.90625
Iter 32000, Minibatch Loss= 0.322511, Training Accuracy= 0.89062
Iter 33280, Minibatch Loss= 0.309195, Training Accuracy= 0.90625
Iter 34560, Minibatch Loss= 0.535408, Training Accuracy= 0.83594
Iter 35840, Minibatch Loss= 0.281643, Training Accuracy= 0.92969
Iter 37120, Minibatch Loss= 0.290962, Training Accuracy= 0.89844
Iter 38400, Minibatch Loss= 0.204718, Training Accuracy= 0.93750
Iter 39680, Minibatch Loss= 0.205882, Training Accuracy= 0.92969
Iter 40960, Minibatch Loss= 0.481441, Training Accuracy= 0.84375
Iter 42240, Minibatch Loss= 0.348245, Training Accuracy= 0.89844
Iter 43520, Minibatch Loss= 0.274692, Training Accuracy= 0.90625
Iter 44800, Minibatch Loss= 0.171815, Training Accuracy= 0.94531
Iter 46080, Minibatch Loss= 0.171035, Training Accuracy= 0.93750
Iter 47360, Minibatch Loss= 0.235800, Training Accuracy= 0.89844
Iter 48640, Minibatch Loss= 0.235974, Training Accuracy= 0.93750
Iter 49920, Minibatch Loss= 0.207323, Training Accuracy= 0.92188
Iter 51200, Minibatch Loss= 0.212989, Training Accuracy= 0.91406
Iter 52480, Minibatch Loss= 0.151774, Training Accuracy= 0.95312
Iter 53760, Minibatch Loss= 0.090070, Training Accuracy= 0.96875
Iter 55040, Minibatch Loss= 0.264714, Training Accuracy= 0.92969
Iter 56320, Minibatch Loss= 0.235086, Training Accuracy= 0.92969
Iter 57600, Minibatch Loss= 0.160302, Training Accuracy= 0.95312
Iter 58880, Minibatch Loss= 0.106515, Training Accuracy= 0.96875
Iter 60160, Minibatch Loss= 0.236039, Training Accuracy= 0.94531
Iter 61440, Minibatch Loss= 0.279540, Training Accuracy= 0.90625
Iter 62720, Minibatch Loss= 0.173585, Training Accuracy= 0.93750
Iter 64000, Minibatch Loss= 0.191009, Training Accuracy= 0.92188
Iter 65280, Minibatch Loss= 0.210331, Training Accuracy= 0.89844
Iter 66560, Minibatch Loss= 0.223444, Training Accuracy= 0.94531
Iter 67840, Minibatch Loss= 0.278210, Training Accuracy= 0.91406
Iter 69120, Minibatch Loss= 0.174290, Training Accuracy= 0.95312
Iter 70400, Minibatch Loss= 0.188701, Training Accuracy= 0.94531
Iter 71680, Minibatch Loss= 0.210277, Training Accuracy= 0.94531
Iter 72960, Minibatch Loss= 0.249951, Training Accuracy= 0.95312
Iter 74240, Minibatch Loss= 0.209853, Training Accuracy= 0.92188
Iter 75520, Minibatch Loss= 0.049742, Training Accuracy= 0.99219
Iter 76800, Minibatch Loss= 0.250095, Training Accuracy= 0.92969
Iter 78080, Minibatch Loss= 0.133853, Training Accuracy= 0.95312
Iter 79360, Minibatch Loss= 0.110206, Training Accuracy= 0.97656
Iter 80640, Minibatch Loss= 0.141906, Training Accuracy= 0.93750
Iter 81920, Minibatch Loss= 0.126872, Training Accuracy= 0.94531
Iter 83200, Minibatch Loss= 0.138925, Training Accuracy= 0.95312
Iter 84480, Minibatch Loss= 0.128652, Training Accuracy= 0.96094
Iter 85760, Minibatch Loss= 0.099837, Training Accuracy= 0.96094
Iter 87040, Minibatch Loss= 0.119000, Training Accuracy= 0.95312
Iter 88320, Minibatch Loss= 0.179807, Training Accuracy= 0.95312
Iter 89600, Minibatch Loss= 0.141792, Training Accuracy= 0.96094
Iter 90880, Minibatch Loss= 0.142424, Training Accuracy= 0.96094
Iter 92160, Minibatch Loss= 0.159564, Training Accuracy= 0.96094
Iter 93440, Minibatch Loss= 0.111984, Training Accuracy= 0.95312
Iter 94720, Minibatch Loss= 0.238978, Training Accuracy= 0.92969
Iter 96000, Minibatch Loss= 0.068002, Training Accuracy= 0.97656
Iter 97280, Minibatch Loss= 0.191819, Training Accuracy= 0.94531
Iter 98560, Minibatch Loss= 0.081197, Training Accuracy= 0.99219
Iter 99840, Minibatch Loss= 0.206797, Training Accuracy= 0.95312
Optimization Finished!
Testing Accuracy: 0.941406