convolutional_network.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. '''
  2. A Convolutional Network 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 tensorflow as tf
  10. # Import MINST data
  11. from tensorflow.examples.tutorials.mnist import input_data
  12. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  13. # Parameters
  14. learning_rate = 0.001
  15. training_iters = 200000
  16. batch_size = 128
  17. display_step = 10
  18. # Network Parameters
  19. n_input = 784 # MNIST data input (img shape: 28*28)
  20. n_classes = 10 # MNIST total classes (0-9 digits)
  21. dropout = 0.75 # Dropout, probability to keep units
  22. # tf Graph input
  23. x = tf.placeholder(tf.float32, [None, n_input])
  24. y = tf.placeholder(tf.float32, [None, n_classes])
  25. keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)
  26. # Create some wrappers for simplicity
  27. def conv2d(x, W, b, strides=1):
  28. # Conv2D wrapper, with bias and relu activation
  29. x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
  30. x = tf.nn.bias_add(x, b)
  31. return tf.nn.relu(x)
  32. def maxpool2d(x, k=2):
  33. # MaxPool2D wrapper
  34. return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
  35. padding='SAME')
  36. # Create model
  37. def conv_net(x, weights, biases, dropout):
  38. # Reshape input picture
  39. x = tf.reshape(x, shape=[-1, 28, 28, 1])
  40. # Convolution Layer
  41. conv1 = conv2d(x, weights['wc1'], biases['bc1'])
  42. # Max Pooling (down-sampling)
  43. conv1 = maxpool2d(conv1, k=2)
  44. # Convolution Layer
  45. conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
  46. # Max Pooling (down-sampling)
  47. conv2 = maxpool2d(conv2, k=2)
  48. # Fully connected layer
  49. # Reshape conv2 output to fit fully connected layer input
  50. fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
  51. fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
  52. fc1 = tf.nn.relu(fc1)
  53. # Apply Dropout
  54. fc1 = tf.nn.dropout(fc1, dropout)
  55. # Output, class prediction
  56. out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
  57. return out
  58. # Store layers weight & bias
  59. weights = {
  60. # 5x5 conv, 1 input, 32 outputs
  61. 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
  62. # 5x5 conv, 32 inputs, 64 outputs
  63. 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
  64. # fully connected, 7*7*64 inputs, 1024 outputs
  65. 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
  66. # 1024 inputs, 10 outputs (class prediction)
  67. 'out': tf.Variable(tf.random_normal([1024, n_classes]))
  68. }
  69. biases = {
  70. 'bc1': tf.Variable(tf.random_normal([32])),
  71. 'bc2': tf.Variable(tf.random_normal([64])),
  72. 'bd1': tf.Variable(tf.random_normal([1024])),
  73. 'out': tf.Variable(tf.random_normal([n_classes]))
  74. }
  75. # Construct model
  76. pred = conv_net(x, weights, biases, keep_prob)
  77. # Define loss and optimizer
  78. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  79. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  80. # Evaluate model
  81. correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
  82. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  83. # Initializing the variables
  84. init = tf.initialize_all_variables()
  85. # Launch the graph
  86. with tf.Session() as sess:
  87. sess.run(init)
  88. step = 1
  89. # Keep training until reach max iterations
  90. while step * batch_size < training_iters:
  91. batch_x, batch_y = mnist.train.next_batch(batch_size)
  92. # Run optimization op (backprop)
  93. sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
  94. keep_prob: dropout})
  95. if step % display_step == 0:
  96. # Calculate batch loss and accuracy
  97. loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
  98. y: batch_y,
  99. keep_prob: 1.})
  100. print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
  101. "{:.6f}".format(loss) + ", Training Accuracy= " + \
  102. "{:.5f}".format(acc))
  103. step += 1
  104. print("Optimization Finished!")
  105. # Calculate accuracy for 256 mnist test images
  106. print("Testing Accuracy:", \
  107. sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
  108. y: mnist.test.labels[:256],
  109. keep_prob: 1.}))