recurrent_network.py 3.9 KB

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