multilayer_perceptron.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. """ Multilayer Perceptron.
  2. A Multilayer Perceptron (Neural Network) implementation example using
  3. TensorFlow library. This example is using the MNIST database of handwritten
  4. digits (http://yann.lecun.com/exdb/mnist/).
  5. Links:
  6. [MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
  7. Author: Aymeric Damien
  8. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  9. """
  10. # ------------------------------------------------------------------
  11. #
  12. # THIS EXAMPLE HAS BEEN RENAMED 'neural_network.py', FOR SIMPLICITY.
  13. #
  14. # ------------------------------------------------------------------
  15. from __future__ import print_function
  16. # Import MNIST data
  17. from tensorflow.examples.tutorials.mnist import input_data
  18. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  19. import tensorflow as tf
  20. # Parameters
  21. learning_rate = 0.001
  22. training_epochs = 15
  23. batch_size = 100
  24. display_step = 1
  25. # Network Parameters
  26. n_hidden_1 = 256 # 1st layer number of neurons
  27. n_hidden_2 = 256 # 2nd layer number of neurons
  28. n_input = 784 # MNIST data input (img shape: 28*28)
  29. n_classes = 10 # MNIST total classes (0-9 digits)
  30. # tf Graph input
  31. X = tf.placeholder("float", [None, n_input])
  32. Y = tf.placeholder("float", [None, n_classes])
  33. # Store layers weight & bias
  34. weights = {
  35. 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
  36. 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
  37. 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
  38. }
  39. biases = {
  40. 'b1': tf.Variable(tf.random_normal([n_hidden_1])),
  41. 'b2': tf.Variable(tf.random_normal([n_hidden_2])),
  42. 'out': tf.Variable(tf.random_normal([n_classes]))
  43. }
  44. # Create model
  45. def multilayer_perceptron(x):
  46. # Hidden fully connected layer with 256 neurons
  47. layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
  48. # Hidden fully connected layer with 256 neurons
  49. layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
  50. # Output fully connected layer with a neuron for each class
  51. out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
  52. return out_layer
  53. # Construct model
  54. logits = multilayer_perceptron(X)
  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.AdamOptimizer(learning_rate=learning_rate)
  59. train_op = optimizer.minimize(loss_op)
  60. # Initializing the variables
  61. init = tf.global_variables_initializer()
  62. with tf.Session() as sess:
  63. sess.run(init)
  64. # Training cycle
  65. for epoch in range(training_epochs):
  66. avg_cost = 0.
  67. total_batch = int(mnist.train.num_examples/batch_size)
  68. # Loop over all batches
  69. for i in range(total_batch):
  70. batch_x, batch_y = mnist.train.next_batch(batch_size)
  71. # Run optimization op (backprop) and cost op (to get loss value)
  72. _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
  73. Y: batch_y})
  74. # Compute average loss
  75. avg_cost += c / total_batch
  76. # Display logs per epoch step
  77. if epoch % display_step == 0:
  78. print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
  79. print("Optimization Finished!")
  80. # Test model
  81. pred = tf.nn.softmax(logits) # Apply softmax to logits
  82. correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
  83. # Calculate accuracy
  84. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  85. print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))