classifier.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # From the tutorial on
  2. # https://www.tensorflow.org/get_started/mnist/pros
  3. # Disable linter warnings to maintain consistency with tutorial.
  4. # pylint: disable=invalid-name
  5. # pylint: disable=g-bad-import-order
  6. from __future__ import absolute_import
  7. from __future__ import division
  8. from __future__ import print_function
  9. import argparse
  10. import sys
  11. from tensorflow.examples.tutorials.mnist import input_data
  12. import tensorflow as tf
  13. FLAGS = None
  14. def deepnn(x):
  15. """deepnn builds the graph for a deep net for classifying digits.
  16. Args:
  17. x: an input tensor with the dimensions (N_examples, 784), where 784 is the
  18. number of pixels in a standard MNIST image.
  19. Returns:
  20. A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
  21. equal to the logits of classifying the digit into one of 10 classes (the
  22. digits 0-9). keep_prob is a scalar placeholder for the probability of
  23. dropout.
  24. """
  25. # Reshape to use within a convolutional neural net.
  26. # Last dimension is for "features" - there is only one here, since images are
  27. # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  28. x_image = tf.reshape(x, [-1, 28, 28, 1])
  29. # First convolutional layer - maps one grayscale image to 32 feature maps.
  30. W_conv1 = weight_variable([5, 5, 1, 32])
  31. b_conv1 = bias_variable([32])
  32. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  33. # Pooling layer - downsamples by 2X.
  34. h_pool1 = max_pool_2x2(h_conv1)
  35. # Second convolutional layer -- maps 32 feature maps to 64.
  36. W_conv2 = weight_variable([5, 5, 32, 64])
  37. b_conv2 = bias_variable([64])
  38. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  39. # Second pooling layer.
  40. h_pool2 = max_pool_2x2(h_conv2)
  41. # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  42. # is down to 7x7x64 feature maps -- maps this to 1024 features.
  43. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  44. b_fc1 = bias_variable([1024])
  45. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
  46. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  47. # Dropout - controls the complexity of the model, prevents co-adaptation of
  48. # features.
  49. keep_prob = tf.placeholder(tf.float32)
  50. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  51. # Map the 1024 features to 10 classes, one for each digit
  52. W_fc2 = weight_variable([1024, 10])
  53. b_fc2 = bias_variable([10])
  54. y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  55. return y_conv, keep_prob
  56. def conv2d(x, W):
  57. """conv2d returns a 2d convolution layer with full stride."""
  58. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  59. def max_pool_2x2(x):
  60. """max_pool_2x2 downsamples a feature map by 2X."""
  61. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
  62. strides=[1, 2, 2, 1], padding='SAME')
  63. def weight_variable(shape):
  64. """weight_variable generates a weight variable of a given shape."""
  65. initial = tf.truncated_normal(shape, stddev=0.1)
  66. return tf.Variable(initial)
  67. def bias_variable(shape):
  68. """bias_variable generates a bias variable of a given shape."""
  69. initial = tf.constant(0.1, shape=shape)
  70. return tf.Variable(initial)
  71. def main(_):
  72. # Import data
  73. mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  74. # Create the model
  75. x = tf.placeholder(tf.float32, [None, 784])
  76. # Define loss and optimizer
  77. y_ = tf.placeholder(tf.float32, [None, 10])
  78. # Build the graph for the deep net
  79. y_conv, keep_prob = deepnn(x)
  80. cross_entropy = tf.reduce_mean(
  81. tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
  82. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  83. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
  84. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  85. with tf.Session() as sess:
  86. sess.run(tf.global_variables_initializer())
  87. for i in range(20000):
  88. batch = mnist.train.next_batch(50)
  89. if i % 100 == 0:
  90. train_accuracy = accuracy.eval(feed_dict={
  91. x: batch[0], y_: batch[1], keep_prob: 1.0})
  92. print('step %d, training accuracy %g' % (i, train_accuracy))
  93. train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  94. print('test accuracy %g' % accuracy.eval(feed_dict={
  95. x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
  96. if __name__ == '__main__':
  97. parser = argparse.ArgumentParser()
  98. parser.add_argument('--data_dir', type=str,
  99. default='/tmp/tensorflow/mnist/input_data',
  100. help='Directory for storing input data')
  101. FLAGS, unparsed = parser.parse_known_args()
  102. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)