recurrent_network.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. '''
  2. A 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.models.rnn import rnn, rnn_cell
  13. import numpy as np
  14. # Parameters
  15. learning_rate = 0.001
  16. training_iters = 100000
  17. batch_size = 128
  18. display_step = 10
  19. # Network Parameters
  20. n_input = 28 # MNIST data input (img shape: 28*28)
  21. n_steps = 28 # timesteps
  22. n_hidden = 128 # hidden layer num of features
  23. n_classes = 10 # MNIST total classes (0-9 digits)
  24. # tf Graph input
  25. x = tf.placeholder("float", [None, n_steps, n_input])
  26. istate = tf.placeholder("float", [None, 2*n_hidden]) #state & cell => 2x n_hidden
  27. y = tf.placeholder("float", [None, n_classes])
  28. # Define weights
  29. weights = {
  30. 'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights
  31. 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
  32. }
  33. biases = {
  34. 'hidden': tf.Variable(tf.random_normal([n_hidden])),
  35. 'out': tf.Variable(tf.random_normal([n_classes]))
  36. }
  37. def RNN(_X, _istate, _weights, _biases):
  38. # input shape: (batch_size, n_steps, n_input)
  39. _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size
  40. # Reshape to prepare input to hidden activation
  41. _X = tf.reshape(_X, [-1, n_input]) # (n_steps*batch_size, n_input)
  42. # Linear activation
  43. _X = tf.matmul(_X, _weights['hidden']) + _biases['hidden']
  44. # Define a lstm cell with tensorflow
  45. lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)
  46. # Split data because rnn cell needs a list of inputs for the RNN inner loop
  47. _X = tf.split(0, n_steps, _X) # n_steps * (batch_size, n_hidden)
  48. # Get lstm cell output
  49. outputs, states = rnn.rnn(lstm_cell, _X, initial_state=_istate)
  50. # Linear activation
  51. # Get inner loop last output
  52. return tf.matmul(outputs[-1], _weights['out']) + _biases['out']
  53. pred = RNN(x, istate, weights, biases)
  54. # Define loss and optimizer
  55. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax loss
  56. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer
  57. # Evaluate model
  58. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  59. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.types.float32))
  60. # Initializing the variables
  61. init = tf.initialize_all_variables()
  62. # Launch the graph
  63. with tf.Session() as sess:
  64. sess.run(init)
  65. step = 1
  66. # Keep training until reach max iterations
  67. while step * batch_size < training_iters:
  68. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  69. # Reshape data to get 28 seq of 28 elements
  70. batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))
  71. # Fit training using batch data
  72. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys,
  73. istate: np.zeros((batch_size, 2*n_hidden))})
  74. if step % display_step == 0:
  75. # Calculate batch accuracy
  76. acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,
  77. istate: np.zeros((batch_size, 2*n_hidden))})
  78. # Calculate batch loss
  79. loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys,
  80. istate: np.zeros((batch_size, 2*n_hidden))})
  81. print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + \
  82. ", Training Accuracy= " + "{:.5f}".format(acc)
  83. step += 1
  84. print "Optimization Finished!"
  85. # Calculate accuracy for 256 mnist test images
  86. test_len = 256
  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:", sess.run(accuracy, feed_dict={x: test_data, y: test_label,
  90. istate: np.zeros((test_len, 2*n_hidden))})