multilayer_perceptron.py 3.1 KB

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