You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

minst_rnn.py 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import tensorflow as tf
  2. # hyperparameters
  3. n_neurons = 128
  4. learning_rate = 0.001
  5. batch_size = 128
  6. n_epochs = 10
  7. # parameters
  8. n_steps = 28 # 28 rows
  9. n_inputs = 28 # 28 cols
  10. n_outputs = 10 # 10 classes
  11. # build a rnn model
  12. X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
  13. y = tf.placeholder(tf.int32, [None])
  14. cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons)
  15. output, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
  16. logits = tf.layers.dense(state, n_outputs)
  17. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)
  18. loss = tf.reduce_mean(cross_entropy)
  19. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
  20. prediction = tf.nn.in_top_k(logits, y, 1)
  21. accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))
  22. # input data
  23. from tensorflow.examples.tutorials.mnist import input_data
  24. mnist = input_data.read_data_sets("MNIST_data/")
  25. X_test = mnist.test.images # X_test shape: [num_test, 28*28]
  26. X_test = X_test.reshape([-1, n_steps, n_inputs])
  27. y_test = mnist.test.labels
  28. # initialize the variables
  29. init = tf.global_variables_initializer()
  30. # train the model
  31. with tf.Session() as sess:
  32. sess.run(init)
  33. n_batches = mnist.train.num_examples // batch_size
  34. for epoch in range(n_epochs):
  35. for batch in range(n_batches):
  36. X_train, y_train = mnist.train.next_batch(batch_size)
  37. X_train = X_train.reshape([-1, n_steps, n_inputs])
  38. sess.run(optimizer, feed_dict={X: X_train, y: y_train})
  39. loss_train, acc_train = sess.run(
  40. [loss, accuracy], feed_dict={X: X_train, y: y_train})
  41. print('Epoch: {}, Train Loss: {:.3f}, Train Acc: {:.3f}'.format(
  42. epoch + 1, loss_train, acc_train))
  43. loss_test, acc_test = sess.run(
  44. [loss, accuracy], feed_dict={X: X_test, y: y_test})
  45. print('Test Loss: {:.3f}, Test Acc: {:.3f}'.format(loss_test, acc_test))