bidirectional_rnn.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. '''
  2. A Bidirectional Reccurent 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. import tensorflow as tf
  9. from tensorflow.models.rnn import rnn, rnn_cell
  10. import numpy as np
  11. # Import MINST 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 bidirectional reccurent neural network, we consider
  16. every image row as a sequence of pixels. Because MNIST image shape is 28*28px,
  17. we will then 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. # Hidden layer weights => 2*n_hidden because of foward + backward cells
  35. 'out': tf.Variable(tf.random_normal([2*n_hidden, n_classes]))
  36. }
  37. biases = {
  38. 'out': tf.Variable(tf.random_normal([n_classes]))
  39. }
  40. def BiRNN(x, weights, biases):
  41. # Prepare data shape to match `bidirectional_rnn` function requirements
  42. # Current data input shape: (batch_size, n_steps, n_input)
  43. # Required shape: 'n_steps' tensors list of shape (batch_size, n_input)
  44. # Permuting batch_size and n_steps
  45. x = tf.transpose(x, [1, 0, 2])
  46. # Reshape to (n_steps*batch_size, n_input)
  47. x = tf.reshape(x, [-1, n_input])
  48. # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
  49. x = tf.split(0, n_steps, x)
  50. # Define lstm cells with tensorflow
  51. # Forward direction cell
  52. lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  53. # Backward direction cell
  54. lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  55. # Get lstm cell output
  56. try:
  57. outputs, _, _ = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x,
  58. dtype=tf.float32)
  59. except Exception: # Old TensorFlow version only returns outputs not states
  60. outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x,
  61. dtype=tf.float32)
  62. # Linear activation, using rnn inner loop last output
  63. return tf.matmul(outputs[-1], weights['out']) + biases['out']
  64. pred = BiRNN(x, weights, biases)
  65. # Define loss and optimizer
  66. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  67. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  68. # Evaluate model
  69. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  70. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  71. # Initializing the variables
  72. init = tf.initialize_all_variables()
  73. # Launch the graph
  74. with tf.Session() as sess:
  75. sess.run(init)
  76. step = 1
  77. # Keep training until reach max iterations
  78. while step * batch_size < training_iters:
  79. batch_x, batch_y = mnist.train.next_batch(batch_size)
  80. # Reshape data to get 28 seq of 28 elements
  81. batch_x = batch_x.reshape((batch_size, n_steps, n_input))
  82. # Run optimization op (backprop)
  83. sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
  84. if step % display_step == 0:
  85. # Calculate batch accuracy
  86. acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
  87. # Calculate batch loss
  88. loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
  89. print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
  90. "{:.6f}".format(loss) + ", Training Accuracy= " + \
  91. "{:.5f}".format(acc)
  92. step += 1
  93. print "Optimization Finished!"
  94. # Calculate accuracy for 128 mnist test images
  95. test_len = 128
  96. test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
  97. test_label = mnist.test.labels[:test_len]
  98. print "Testing Accuracy:", \
  99. sess.run(accuracy, feed_dict={x: test_data, y: test_label})