multilayer_perceptron.py 3.1 KB

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