neural_network.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """ Neural Network.
  2. A 2-Hidden Layers Fully Connected Neural Network (a.k.a Multilayer Perceptron)
  3. implementation with TensorFlow. 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 MNIST data
  14. from tensorflow.examples.tutorials.mnist import input_data
  15. mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
  16. import tensorflow as tf
  17. # Parameters
  18. learning_rate = 0.1
  19. num_steps = 1000
  20. batch_size = 128
  21. display_step = 100
  22. # Network Parameters
  23. n_hidden_1 = 256 # 1st layer number of neurons
  24. n_hidden_2 = 256 # 2nd layer number of neurons
  25. num_input = 784 # MNIST data input (img shape: 28*28)
  26. num_classes = 10 # MNIST total classes (0-9 digits)
  27. # Define the neural network
  28. def neural_net(x_dict):
  29. # TF Estimator input is a dict, in case of multiple inputs
  30. x = x_dict['images']
  31. # Hidden fully connected layer with 256 neurons
  32. layer_1 = tf.layers.dense(x, n_hidden_1)
  33. # Hidden fully connected layer with 256 neurons
  34. layer_2 = tf.layers.dense(layer_1, n_hidden_2)
  35. # Output fully connected layer with a neuron for each class
  36. out_layer = tf.layers.dense(layer_2, num_classes)
  37. return out_layer
  38. # Define the model function (following TF Estimator Template)
  39. def model_fn(features, labels, mode):
  40. # Build the neural network
  41. logits = neural_net(features)
  42. # Predictions
  43. pred_classes = tf.argmax(logits, axis=1)
  44. pred_probas = tf.nn.softmax(logits)
  45. # If prediction mode, early return
  46. if mode == tf.estimator.ModeKeys.PREDICT:
  47. return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)
  48. # Define loss and optimizer
  49. loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
  50. logits=logits, labels=tf.cast(labels, dtype=tf.int32)))
  51. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  52. train_op = optimizer.minimize(loss_op,
  53. global_step=tf.train.get_global_step())
  54. # Evaluate the accuracy of the model
  55. acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
  56. # TF Estimators requires to return a EstimatorSpec, that specify
  57. # the different ops for training, evaluating, ...
  58. estim_specs = tf.estimator.EstimatorSpec(
  59. mode=mode,
  60. predictions=pred_classes,
  61. loss=loss_op,
  62. train_op=train_op,
  63. eval_metric_ops={'accuracy': acc_op})
  64. return estim_specs
  65. # Build the Estimator
  66. model = tf.estimator.Estimator(model_fn)
  67. # Define the input function for training
  68. input_fn = tf.estimator.inputs.numpy_input_fn(
  69. x={'images': mnist.train.images}, y=mnist.train.labels,
  70. batch_size=batch_size, num_epochs=None, shuffle=True)
  71. # Train the Model
  72. model.train(input_fn, steps=num_steps)
  73. # Evaluate the Model
  74. # Define the input function for evaluating
  75. input_fn = tf.estimator.inputs.numpy_input_fn(
  76. x={'images': mnist.test.images}, y=mnist.test.labels,
  77. batch_size=batch_size, shuffle=False)
  78. # Use the Estimator 'evaluate' method
  79. e = model.evaluate(input_fn)
  80. print("Testing Accuracy:", e['accuracy'])