neural_network_eager_api.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """ Neural Network with Eager API.
  2. A 2-Hidden Layers Fully Connected Neural Network (a.k.a Multilayer Perceptron)
  3. implementation with TensorFlow's Eager API. This example is using the MNIST database
  4. of handwritten digits (http://yann.lecun.com/exdb/mnist/).
  5. This example is using TensorFlow layers, see 'neural_network_raw' example for
  6. a raw implementation with variables.
  7. Links:
  8. [MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
  9. Author: Aymeric Damien
  10. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  11. """
  12. from __future__ import print_function
  13. import tensorflow as tf
  14. import tensorflow.contrib.eager as tfe
  15. # Set Eager API
  16. tfe.enable_eager_execution()
  17. # Import MNIST data
  18. from tensorflow.examples.tutorials.mnist import input_data
  19. mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
  20. # Parameters
  21. learning_rate = 0.001
  22. num_steps = 1000
  23. batch_size = 128
  24. display_step = 100
  25. # Network Parameters
  26. n_hidden_1 = 256 # 1st layer number of neurons
  27. n_hidden_2 = 256 # 2nd layer number of neurons
  28. num_input = 784 # MNIST data input (img shape: 28*28)
  29. num_classes = 10 # MNIST total classes (0-9 digits)
  30. # Using TF Dataset to split data into batches
  31. dataset = tf.data.Dataset.from_tensor_slices(
  32. (mnist.train.images, mnist.train.labels)).batch(batch_size)
  33. dataset_iter = tfe.Iterator(dataset)
  34. # Define the neural network. To use eager API and tf.layers API together,
  35. # we must instantiate a tfe.Network class as follow:
  36. class NeuralNet(tfe.Network):
  37. def __init__(self):
  38. # Define each layer
  39. super(NeuralNet, self).__init__()
  40. # Hidden fully connected layer with 256 neurons
  41. self.layer1 = self.track_layer(
  42. tf.layers.Dense(n_hidden_1, activation=tf.nn.relu))
  43. # Hidden fully connected layer with 256 neurons
  44. self.layer2 = self.track_layer(
  45. tf.layers.Dense(n_hidden_2, activation=tf.nn.relu))
  46. # Output fully connected layer with a neuron for each class
  47. self.out_layer = self.track_layer(tf.layers.Dense(num_classes))
  48. def call(self, x):
  49. x = self.layer1(x)
  50. x = self.layer2(x)
  51. return self.out_layer(x)
  52. neural_net = NeuralNet()
  53. # Cross-Entropy loss function
  54. def loss_fn(inference_fn, inputs, labels):
  55. # Using sparse_softmax cross entropy
  56. return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
  57. logits=inference_fn(inputs), labels=labels))
  58. # Calculate accuracy
  59. def accuracy_fn(inference_fn, inputs, labels):
  60. prediction = tf.nn.softmax(inference_fn(inputs))
  61. correct_pred = tf.equal(tf.argmax(prediction, 1), labels)
  62. return tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  63. # SGD Optimizer
  64. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
  65. # Compute gradients
  66. grad = tfe.implicit_gradients(loss_fn)
  67. # Training
  68. average_loss = 0.
  69. average_acc = 0.
  70. for step in range(num_steps):
  71. # Iterate through the dataset
  72. try:
  73. d = dataset_iter.next()
  74. except StopIteration:
  75. # Refill queue
  76. dataset_iter = tfe.Iterator(dataset)
  77. d = dataset_iter.next()
  78. # Images
  79. x_batch = d[0]
  80. # Labels
  81. y_batch = tf.cast(d[1], dtype=tf.int64)
  82. # Compute the batch loss
  83. batch_loss = loss_fn(neural_net, x_batch, y_batch)
  84. average_loss += batch_loss
  85. # Compute the batch accuracy
  86. batch_accuracy = accuracy_fn(neural_net, x_batch, y_batch)
  87. average_acc += batch_accuracy
  88. if step == 0:
  89. # Display the initial cost, before optimizing
  90. print("Initial loss= {:.9f}".format(average_loss))
  91. # Update the variables following gradients info
  92. optimizer.apply_gradients(grad(neural_net, x_batch, y_batch))
  93. # Display info
  94. if (step + 1) % display_step == 0 or step == 0:
  95. if step > 0:
  96. average_loss /= display_step
  97. average_acc /= display_step
  98. print("Step:", '%04d' % (step + 1), " loss=",
  99. "{:.9f}".format(average_loss), " accuracy=",
  100. "{:.4f}".format(average_acc))
  101. average_loss = 0.
  102. average_acc = 0.
  103. # Evaluate model on the test image set
  104. testX = mnist.test.images
  105. testY = mnist.test.labels
  106. test_acc = accuracy_fn(neural_net, testX, testY)
  107. print("Testset Accuracy: {:.4f}".format(test_acc))