bidirectional_rnn.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 MINST data
  9. import input_data
  10. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  11. import tensorflow as tf
  12. from tensorflow.python.ops.constant_op import constant
  13. from tensorflow.models.rnn import rnn, rnn_cell
  14. import numpy as np
  15. '''
  16. To classify images using a bidirectional reccurent neural network, we consider every image row as a sequence of pixels.
  17. Because MNIST image shape is 28*28px, 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. # Tensorflow LSTM cell requires 2x n_hidden length (state & cell)
  32. istate_fw = tf.placeholder("float", [None, 2*n_hidden])
  33. istate_bw = tf.placeholder("float", [None, 2*n_hidden])
  34. y = tf.placeholder("float", [None, n_classes])
  35. # Define weights
  36. weights = {
  37. # Hidden layer weights => 2*n_hidden because of foward + backward cells
  38. 'hidden': tf.Variable(tf.random_normal([n_input, 2*n_hidden])),
  39. 'out': tf.Variable(tf.random_normal([2*n_hidden, n_classes]))
  40. }
  41. biases = {
  42. 'hidden': tf.Variable(tf.random_normal([2*n_hidden])),
  43. 'out': tf.Variable(tf.random_normal([n_classes]))
  44. }
  45. def BiRNN(_X, _istate_fw, _istate_bw, _weights, _biases, _batch_size, _seq_len):
  46. # BiRNN requires to supply sequence_length as [batch_size, int64]
  47. # Note: Tensorflow 0.6.0 requires BiRNN sequence_length parameter to be set
  48. # For a better implementation with latest version of tensorflow, check below
  49. _seq_len = tf.fill([_batch_size], constant(_seq_len, dtype=tf.int64))
  50. # input shape: (batch_size, n_steps, n_input)
  51. _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size
  52. # Reshape to prepare input to hidden activation
  53. _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)
  54. # Linear activation
  55. _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']
  56. # Define lstm cells with tensorflow
  57. # Forward direction cell
  58. lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  59. # Backward direction cell
  60. lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  61. # Split data because rnn cell needs a list of inputs for the RNN inner loop
  62. _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)
  63. # Get lstm cell output
  64. outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, _X,
  65. initial_state_fw=_istate_fw,
  66. initial_state_bw=_istate_bw,
  67. sequence_length=_seq_len)
  68. # Linear activation
  69. # Get inner loop last output
  70. return tf.matmul(outputs[-1], _weights['out']) + _biases['out']
  71. pred = BiRNN(x, istate_fw, istate_bw, weights, biases, batch_size, n_steps)
  72. # NOTE: The following code is working with current master version of tensorflow
  73. # BiRNN sequence_length parameter isn't required, so we don't define it
  74. #
  75. # def BiRNN(_X, _istate_fw, _istate_bw, _weights, _biases):
  76. #
  77. # # input shape: (batch_size, n_steps, n_input)
  78. # _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size
  79. # # Reshape to prepare input to hidden activation
  80. # _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)
  81. # # Linear activation
  82. # _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']
  83. #
  84. # # Define lstm cells with tensorflow
  85. # # Forward direction cell
  86. # lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  87. # # Backward direction cell
  88. # lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  89. # # Split data because rnn cell needs a list of inputs for the RNN inner loop
  90. # _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)
  91. #
  92. # # Get lstm cell output
  93. # outputs = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, _X,
  94. # initial_state_fw=_istate_fw,
  95. # initial_state_bw=_istate_bw)
  96. #
  97. # # Linear activation
  98. # # Get inner loop last output
  99. # return tf.matmul(outputs[-1], _weights['out']) + _biases['out']
  100. #
  101. # pred = BiRNN(x, istate_fw, istate_bw, weights, biases)
  102. # Define loss and optimizer
  103. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss
  104. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer
  105. # Evaluate model
  106. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  107. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  108. # Initializing the variables
  109. init = tf.initialize_all_variables()
  110. # Launch the graph
  111. with tf.Session() as sess:
  112. sess.run(init)
  113. step = 1
  114. # Keep training until reach max iterations
  115. while step * batch_size < training_iters:
  116. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  117. # Reshape data to get 28 seq of 28 elements
  118. batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))
  119. # Fit training using batch data
  120. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys,
  121. istate_fw: np.zeros((batch_size, 2*n_hidden)),
  122. istate_bw: np.zeros((batch_size, 2*n_hidden))})
  123. if step % display_step == 0:
  124. # Calculate batch accuracy
  125. acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,
  126. istate_fw: np.zeros((batch_size, 2*n_hidden)),
  127. istate_bw: np.zeros((batch_size, 2*n_hidden))})
  128. # Calculate batch loss
  129. loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,
  130. istate_fw: np.zeros((batch_size, 2*n_hidden)),
  131. istate_bw: np.zeros((batch_size, 2*n_hidden))})
  132. print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + \
  133. ", Training Accuracy= " + "{:.5f}".format(acc)
  134. step += 1
  135. print "Optimization Finished!"
  136. # Calculate accuracy for 128 mnist test images
  137. test_len = 128
  138. test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
  139. test_label = mnist.test.labels[:test_len]
  140. print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label,
  141. istate_fw: np.zeros((test_len, 2*n_hidden)),
  142. istate_bw: np.zeros((test_len, 2*n_hidden))})