bidirectional_rnn.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """ Bi-directional Recurrent Neural Network.
  2. A Bi-directional Recurrent Neural Network (LSTM) implementation example using
  3. TensorFlow library. This example is using the MNIST database of handwritten
  4. digits (http://yann.lecun.com/exdb/mnist/)
  5. Links:
  6. [Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)
  7. [MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
  8. Author: Aymeric Damien
  9. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  10. """
  11. from __future__ import print_function
  12. import tensorflow as tf
  13. from tensorflow.contrib import rnn
  14. import numpy as np
  15. # Import MNIST data
  16. from tensorflow.examples.tutorials.mnist import input_data
  17. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  18. '''
  19. To classify images using a bidirectional recurrent neural network, we consider
  20. every image row as a sequence of pixels. Because MNIST image shape is 28*28px,
  21. we will then handle 28 sequences of 28 steps for every sample.
  22. '''
  23. # Training Parameters
  24. learning_rate = 0.001
  25. training_steps = 10000
  26. batch_size = 128
  27. display_step = 200
  28. # Network Parameters
  29. num_input = 28 # MNIST data input (img shape: 28*28)
  30. timesteps = 28 # timesteps
  31. num_hidden = 128 # hidden layer num of features
  32. num_classes = 10 # MNIST total classes (0-9 digits)
  33. # tf Graph input
  34. X = tf.placeholder("float", [None, timesteps, num_input])
  35. Y = tf.placeholder("float", [None, num_classes])
  36. # Define weights
  37. weights = {
  38. # Hidden layer weights => 2*n_hidden because of forward + backward cells
  39. 'out': tf.Variable(tf.random_normal([2*num_hidden, num_classes]))
  40. }
  41. biases = {
  42. 'out': tf.Variable(tf.random_normal([num_classes]))
  43. }
  44. def BiRNN(x, weights, biases):
  45. # Prepare data shape to match `rnn` function requirements
  46. # Current data input shape: (batch_size, timesteps, n_input)
  47. # Required shape: 'timesteps' tensors list of shape (batch_size, num_input)
  48. # Unstack to get a list of 'timesteps' tensors of shape (batch_size, num_input)
  49. x = tf.unstack(x, timesteps, 1)
  50. # Define lstm cells with tensorflow
  51. # Forward direction cell
  52. lstm_fw_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
  53. # Backward direction cell
  54. lstm_bw_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
  55. # Get lstm cell output
  56. try:
  57. outputs, _, _ = rnn.static_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.static_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. logits = BiRNN(X, weights, biases)
  65. prediction = tf.nn.softmax(logits)
  66. # Define loss and optimizer
  67. loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
  68. logits=logits, labels=Y))
  69. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  70. train_op = optimizer.minimize(loss_op)
  71. # Evaluate model (with test logits, for dropout to be disabled)
  72. correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
  73. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  74. # Initialize the variables (i.e. assign their default value)
  75. init = tf.global_variables_initializer()
  76. # Start training
  77. with tf.Session() as sess:
  78. # Run the initializer
  79. sess.run(init)
  80. for step in range(1, training_steps+1):
  81. batch_x, batch_y = mnist.train.next_batch(batch_size)
  82. # Reshape data to get 28 seq of 28 elements
  83. batch_x = batch_x.reshape((batch_size, timesteps, num_input))
  84. # Run optimization op (backprop)
  85. sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
  86. if step % display_step == 0 or step == 1:
  87. # Calculate batch loss and accuracy
  88. loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
  89. Y: batch_y})
  90. print("Step " + str(step) + ", Minibatch Loss= " + \
  91. "{:.4f}".format(loss) + ", Training Accuracy= " + \
  92. "{:.3f}".format(acc))
  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, timesteps, num_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}))