multilayer_perceptron.py 2.9 KB

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