recurrent_network.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. '''
  2. A Recurrent Neural Network (LSTM) implementation example using TensorFlow library.
  3. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
  4. Long Short Term Memory paper: http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf
  5. Author: Aymeric Damien
  6. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  7. '''
  8. from __future__ import print_function
  9. import tensorflow as tf
  10. from tensorflow.contrib import rnn
  11. # Import MNIST data
  12. from tensorflow.examples.tutorials.mnist import input_data
  13. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  14. '''
  15. To classify images using a recurrent neural network, we consider every image
  16. row as a sequence of pixels. Because MNIST image shape is 28*28px, we will then
  17. handle 28 sequences of 28 steps for every sample.
  18. '''
  19. # Parameters
  20. learning_rate = 0.001
  21. training_iters = 100000
  22. batch_size = 128
  23. display_step = 10
  24. # Network Parameters
  25. n_input = 28 # MNIST data input (img shape: 28*28)
  26. n_steps = 28 # timesteps
  27. n_hidden = 128 # hidden layer num of features
  28. n_classes = 10 # MNIST total classes (0-9 digits)
  29. # tf Graph input
  30. x = tf.placeholder("float", [None, n_steps, n_input])
  31. y = tf.placeholder("float", [None, n_classes])
  32. # Define weights
  33. weights = {
  34. 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
  35. }
  36. biases = {
  37. 'out': tf.Variable(tf.random_normal([n_classes]))
  38. }
  39. def RNN(x, weights, biases):
  40. # Prepare data shape to match `rnn` function requirements
  41. # Current data input shape: (batch_size, n_steps, n_input)
  42. # Required shape: 'n_steps' tensors list of shape (batch_size, n_input)
  43. # Permuting batch_size and n_steps
  44. x = tf.transpose(x, [1, 0, 2])
  45. # Reshaping to (n_steps*batch_size, n_input)
  46. x = tf.reshape(x, [-1, n_input])
  47. # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
  48. x = tf.split(x, n_steps, 0)
  49. # Define a lstm cell with tensorflow
  50. lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
  51. # Get lstm cell output
  52. outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
  53. # Linear activation, using rnn inner loop last output
  54. return tf.matmul(outputs[-1], weights['out']) + biases['out']
  55. pred = RNN(x, weights, biases)
  56. # Define loss and optimizer
  57. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
  58. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  59. # Evaluate model
  60. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  61. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  62. # Initializing the variables
  63. init = tf.global_variables_initializer()
  64. # Launch the graph
  65. with tf.Session() as sess:
  66. sess.run(init)
  67. step = 1
  68. # Keep training until reach max iterations
  69. while step * batch_size < training_iters:
  70. batch_x, batch_y = mnist.train.next_batch(batch_size)
  71. # Reshape data to get 28 seq of 28 elements
  72. batch_x = batch_x.reshape((batch_size, n_steps, n_input))
  73. # Run optimization op (backprop)
  74. sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
  75. if step % display_step == 0:
  76. # Calculate batch accuracy
  77. acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
  78. # Calculate batch loss
  79. loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
  80. print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
  81. "{:.6f}".format(loss) + ", Training Accuracy= " + \
  82. "{:.5f}".format(acc))
  83. step += 1
  84. print("Optimization Finished!")
  85. # Calculate accuracy for 128 mnist test images
  86. test_len = 128
  87. test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
  88. test_label = mnist.test.labels[:test_len]
  89. print("Testing Accuracy:", \
  90. sess.run(accuracy, feed_dict={x: test_data, y: test_label}))