{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Recurrent Neural Network in TensorFlow\n",
"\n",
"Credits: Forked from [TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples) by Aymeric Damien\n",
"\n",
"## Setup\n",
"\n",
"Refer to the [setup instructions](http://nbviewer.ipython.org/github/donnemartin/data-science-ipython-notebooks/blob/master/deep-learning/tensor-flow-examples/Setup_TensorFlow.md)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
"Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
"Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
"Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n"
]
}
],
"source": [
"# Import MINST data\n",
"import input_data\n",
"mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n",
"\n",
"import tensorflow as tf\n",
"from tensorflow.models.rnn import rnn, rnn_cell\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"'''\n",
"To classify images using a reccurent neural network, we consider every image row as a sequence of pixels.\n",
"Because MNIST image shape is 28*28px, we will then handle 28 sequences of 28 steps for every sample.\n",
"'''\n",
"\n",
"# Parameters\n",
"learning_rate = 0.001\n",
"training_iters = 100000\n",
"batch_size = 128\n",
"display_step = 10\n",
"\n",
"# Network Parameters\n",
"n_input = 28 # MNIST data input (img shape: 28*28)\n",
"n_steps = 28 # timesteps\n",
"n_hidden = 128 # hidden layer num of features\n",
"n_classes = 10 # MNIST total classes (0-9 digits)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# tf Graph input\n",
"x = tf.placeholder(\"float\", [None, n_steps, n_input])\n",
"istate = tf.placeholder(\"float\", [None, 2*n_hidden]) #state & cell => 2x n_hidden\n",
"y = tf.placeholder(\"float\", [None, n_classes])\n",
"\n",
"# Define weights\n",
"weights = {\n",
" 'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights\n",
" 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))\n",
"}\n",
"biases = {\n",
" 'hidden': tf.Variable(tf.random_normal([n_hidden])),\n",
" 'out': tf.Variable(tf.random_normal([n_classes]))\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def RNN(_X, _istate, _weights, _biases):\n",
"\n",
" # input shape: (batch_size, n_steps, n_input)\n",
" _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size\n",
" # Reshape to prepare input to hidden activation\n",
" _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)\n",
" # Linear activation\n",
" _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']\n",
"\n",
" # Define a lstm cell with tensorflow\n",
" lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)\n",
" # Split data because rnn cell needs a list of inputs for the RNN inner loop\n",
" _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)\n",
"\n",
" # Get lstm cell output\n",
" outputs, states = rnn.rnn(lstm_cell, _X, initial_state=_istate)\n",
"\n",
" # Linear activation\n",
" # Get inner loop last output\n",
" return tf.matmul(outputs[-1], _weights['out']) + _biases['out']"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"pred = RNN(x, istate, weights, biases)\n",
"\n",
"# Define loss and optimizer\n",
"cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss\n",
"optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer\n",
"\n",
"# Evaluate model\n",
"correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))\n",
"accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Iter 1280, Minibatch Loss= 1.888242, Training Accuracy= 0.39844\n",
"Iter 2560, Minibatch Loss= 1.519879, Training Accuracy= 0.47656\n",
"Iter 3840, Minibatch Loss= 1.238005, Training Accuracy= 0.63281\n",
"Iter 5120, Minibatch Loss= 0.933760, Training Accuracy= 0.71875\n",
"Iter 6400, Minibatch Loss= 0.832130, Training Accuracy= 0.73438\n",
"Iter 7680, Minibatch Loss= 0.979760, Training Accuracy= 0.70312\n",
"Iter 8960, Minibatch Loss= 0.821921, Training Accuracy= 0.71875\n",
"Iter 10240, Minibatch Loss= 0.710566, Training Accuracy= 0.79688\n",
"Iter 11520, Minibatch Loss= 0.578501, Training Accuracy= 0.82812\n",
"Iter 12800, Minibatch Loss= 0.765049, Training Accuracy= 0.75000\n",
"Iter 14080, Minibatch Loss= 0.582995, Training Accuracy= 0.78125\n",
"Iter 15360, Minibatch Loss= 0.575092, Training Accuracy= 0.79688\n",
"Iter 16640, Minibatch Loss= 0.701214, Training Accuracy= 0.75781\n",
"Iter 17920, Minibatch Loss= 0.561972, Training Accuracy= 0.78125\n",
"Iter 19200, Minibatch Loss= 0.394480, Training Accuracy= 0.85938\n",
"Iter 20480, Minibatch Loss= 0.356244, Training Accuracy= 0.91406\n",
"Iter 21760, Minibatch Loss= 0.632163, Training Accuracy= 0.78125\n",
"Iter 23040, Minibatch Loss= 0.269334, Training Accuracy= 0.90625\n",
"Iter 24320, Minibatch Loss= 0.485007, Training Accuracy= 0.86719\n",
"Iter 25600, Minibatch Loss= 0.569704, Training Accuracy= 0.78906\n",
"Iter 26880, Minibatch Loss= 0.267697, Training Accuracy= 0.92188\n",
"Iter 28160, Minibatch Loss= 0.381177, Training Accuracy= 0.90625\n",
"Iter 29440, Minibatch Loss= 0.350800, Training Accuracy= 0.87500\n",
"Iter 30720, Minibatch Loss= 0.356782, Training Accuracy= 0.90625\n",
"Iter 32000, Minibatch Loss= 0.322511, Training Accuracy= 0.89062\n",
"Iter 33280, Minibatch Loss= 0.309195, Training Accuracy= 0.90625\n",
"Iter 34560, Minibatch Loss= 0.535408, Training Accuracy= 0.83594\n",
"Iter 35840, Minibatch Loss= 0.281643, Training Accuracy= 0.92969\n",
"Iter 37120, Minibatch Loss= 0.290962, Training Accuracy= 0.89844\n",
"Iter 38400, Minibatch Loss= 0.204718, Training Accuracy= 0.93750\n",
"Iter 39680, Minibatch Loss= 0.205882, Training Accuracy= 0.92969\n",
"Iter 40960, Minibatch Loss= 0.481441, Training Accuracy= 0.84375\n",
"Iter 42240, Minibatch Loss= 0.348245, Training Accuracy= 0.89844\n",
"Iter 43520, Minibatch Loss= 0.274692, Training Accuracy= 0.90625\n",
"Iter 44800, Minibatch Loss= 0.171815, Training Accuracy= 0.94531\n",
"Iter 46080, Minibatch Loss= 0.171035, Training Accuracy= 0.93750\n",
"Iter 47360, Minibatch Loss= 0.235800, Training Accuracy= 0.89844\n",
"Iter 48640, Minibatch Loss= 0.235974, Training Accuracy= 0.93750\n",
"Iter 49920, Minibatch Loss= 0.207323, Training Accuracy= 0.92188\n",
"Iter 51200, Minibatch Loss= 0.212989, Training Accuracy= 0.91406\n",
"Iter 52480, Minibatch Loss= 0.151774, Training Accuracy= 0.95312\n",
"Iter 53760, Minibatch Loss= 0.090070, Training Accuracy= 0.96875\n",
"Iter 55040, Minibatch Loss= 0.264714, Training Accuracy= 0.92969\n",
"Iter 56320, Minibatch Loss= 0.235086, Training Accuracy= 0.92969\n",
"Iter 57600, Minibatch Loss= 0.160302, Training Accuracy= 0.95312\n",
"Iter 58880, Minibatch Loss= 0.106515, Training Accuracy= 0.96875\n",
"Iter 60160, Minibatch Loss= 0.236039, Training Accuracy= 0.94531\n",
"Iter 61440, Minibatch Loss= 0.279540, Training Accuracy= 0.90625\n",
"Iter 62720, Minibatch Loss= 0.173585, Training Accuracy= 0.93750\n",
"Iter 64000, Minibatch Loss= 0.191009, Training Accuracy= 0.92188\n",
"Iter 65280, Minibatch Loss= 0.210331, Training Accuracy= 0.89844\n",
"Iter 66560, Minibatch Loss= 0.223444, Training Accuracy= 0.94531\n",
"Iter 67840, Minibatch Loss= 0.278210, Training Accuracy= 0.91406\n",
"Iter 69120, Minibatch Loss= 0.174290, Training Accuracy= 0.95312\n",
"Iter 70400, Minibatch Loss= 0.188701, Training Accuracy= 0.94531\n",
"Iter 71680, Minibatch Loss= 0.210277, Training Accuracy= 0.94531\n",
"Iter 72960, Minibatch Loss= 0.249951, Training Accuracy= 0.95312\n",
"Iter 74240, Minibatch Loss= 0.209853, Training Accuracy= 0.92188\n",
"Iter 75520, Minibatch Loss= 0.049742, Training Accuracy= 0.99219\n",
"Iter 76800, Minibatch Loss= 0.250095, Training Accuracy= 0.92969\n",
"Iter 78080, Minibatch Loss= 0.133853, Training Accuracy= 0.95312\n",
"Iter 79360, Minibatch Loss= 0.110206, Training Accuracy= 0.97656\n",
"Iter 80640, Minibatch Loss= 0.141906, Training Accuracy= 0.93750\n",
"Iter 81920, Minibatch Loss= 0.126872, Training Accuracy= 0.94531\n",
"Iter 83200, Minibatch Loss= 0.138925, Training Accuracy= 0.95312\n",
"Iter 84480, Minibatch Loss= 0.128652, Training Accuracy= 0.96094\n",
"Iter 85760, Minibatch Loss= 0.099837, Training Accuracy= 0.96094\n",
"Iter 87040, Minibatch Loss= 0.119000, Training Accuracy= 0.95312\n",
"Iter 88320, Minibatch Loss= 0.179807, Training Accuracy= 0.95312\n",
"Iter 89600, Minibatch Loss= 0.141792, Training Accuracy= 0.96094\n",
"Iter 90880, Minibatch Loss= 0.142424, Training Accuracy= 0.96094\n",
"Iter 92160, Minibatch Loss= 0.159564, Training Accuracy= 0.96094\n",
"Iter 93440, Minibatch Loss= 0.111984, Training Accuracy= 0.95312\n",
"Iter 94720, Minibatch Loss= 0.238978, Training Accuracy= 0.92969\n",
"Iter 96000, Minibatch Loss= 0.068002, Training Accuracy= 0.97656\n",
"Iter 97280, Minibatch Loss= 0.191819, Training Accuracy= 0.94531\n",
"Iter 98560, Minibatch Loss= 0.081197, Training Accuracy= 0.99219\n",
"Iter 99840, Minibatch Loss= 0.206797, Training Accuracy= 0.95312\n",
"Optimization Finished!\n",
"Testing Accuracy: 0.941406\n"
]
}
],
"source": [
"# Initializing the variables\n",
"init = tf.global_variables_initializer()\n",
"\n",
"# Launch the graph\n",
"with tf.Session() as sess:\n",
" sess.run(init)\n",
" step = 1\n",
" # Keep training until reach max iterations\n",
" while step * batch_size < training_iters:\n",
" batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
" # Reshape data to get 28 seq of 28 elements\n",
" batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))\n",
" # Fit training using batch data\n",
" sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys,\n",
" istate: np.zeros((batch_size, 2*n_hidden))})\n",
" if step % display_step == 0:\n",
" # Calculate batch accuracy\n",
" acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,\n",
" istate: np.zeros((batch_size, 2*n_hidden))})\n",
" # Calculate batch loss\n",
" loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,\n",
" istate: np.zeros((batch_size, 2*n_hidden))})\n",
" print \"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \"{:.6f}\".format(loss) + \\\n",
" \", Training Accuracy= \" + \"{:.5f}\".format(acc)\n",
" step += 1\n",
" print \"Optimization Finished!\"\n",
" # Calculate accuracy for 256 mnist test images\n",
" test_len = 256\n",
" test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))\n",
" test_label = mnist.test.labels[:test_len]\n",
" print \"Testing Accuracy:\", sess.run(accuracy, feed_dict={x: test_data, y: test_label,\n",
" istate: np.zeros((test_len, 2*n_hidden))})"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}