• Source
    1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
    2. #
    3. # Licensed under the Apache License, Version 2.0 (the "License");
    4. # you may not use this file except in compliance with the License.
    5. # You may obtain a copy of the License at
    6. #
    7. # http://www.apache.org/licenses/LICENSE-2.0
    8. #
    9. # Unless required by applicable law or agreed to in writing, software
    10. # distributed under the License is distributed on an "AS IS" BASIS,
    11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12. # See the License for the specific language governing permissions and
    13. # limitations under the License.
    14. # ==============================================================================
    15.  
    16. """A deep MNIST classifier using convolutional layers.
    17.  
    18. See extensive documentation at
    19. https://www.tensorflow.org/get_started/mnist/pros
    20. """
    21. # Disable linter warnings to maintain consistency with tutorial.
    22. # pylint: disable=invalid-name
    23. # pylint: disable=g-bad-import-order
    24.  
    25. from __future__ import absolute_import
    26. from __future__ import division
    27. from __future__ import print_function
    28.  
    29. import argparse
    30. import sys
    31. import tempfile
    32.  
    33. from tensorflow.examples.tutorials.mnist import input_data
    34.  
    35. import tensorflow as tf
    36.  
    37. FLAGS = None
    38.  
    39. def deepnn(x):
    40. """deepnn builds the graph for a deep net for classifying digits.
    41.  
    42. Args:
    43. x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    44. number of pixels in a standard MNIST image.
    45.  
    46. Returns:
    47. A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    48. equal to the logits of classifying the digit into one of 10 classes (the
    49. digits 0-9). keep_prob is a scalar placeholder for the probability of
    50. dropout.
    51. """
    52. # Reshape to use within a convolutional neural net.
    53. # Last dimension is for "features" - there is only one here, since images are
    54. # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
    55. with tf.name_scope('reshape'):
    56. x_image = tf.reshape(x, [-1, 28, 28, 1])
    57.  
    58. # First convolutional layer - maps one grayscale image to 32 feature maps.
    59. with tf.name_scope('conv1'):
    60. W_conv1 = weight_variable([5, 5, 1, 32])
    61. b_conv1 = bias_variable([32])
    62. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    63.  
    64. # Pooling layer - downsamples by 2X.
    65. with tf.name_scope('pool1'):
    66. h_pool1 = max_pool_2x2(h_conv1)
    67.  
    68. # Second convolutional layer -- maps 32 feature maps to 64.
    69. with tf.name_scope('conv2'):
    70. W_conv2 = weight_variable([5, 5, 32, 64])
    71. b_conv2 = bias_variable([64])
    72. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    73.  
    74. # Second pooling layer.
    75. with tf.name_scope('pool2'):
    76. h_pool2 = max_pool_2x2(h_conv2)
    77.  
    78. # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
    79. # is down to 7x7x64 feature maps -- maps this to 1024 features.
    80. with tf.name_scope('fc1'):
    81. W_fc1 = weight_variable([7 * 7 * 64, 1024])
    82. b_fc1 = bias_variable([1024])
    83.  
    84. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    85. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    86.  
    87. # Dropout - controls the complexity of the model, prevents co-adaptation of
    88. # features.
    89. with tf.name_scope('dropout'):
    90. keep_prob = tf.placeholder(tf.float32)
    91. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    92.  
    93. # Map the 1024 features to 10 classes, one for each digit
    94. with tf.name_scope('fc2'):
    95. W_fc2 = weight_variable([1024, 10])
    96. b_fc2 = bias_variable([10])
    97.  
    98. y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
    99. return y_conv, keep_prob
    100.  
    101.  
    102. def conv2d(x, W):
    103. """conv2d returns a 2d convolution layer with full stride."""
    104. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
    105.  
    106.  
    107. def max_pool_2x2(x):
    108. """max_pool_2x2 downsamples a feature map by 2X."""
    109. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
    110. strides=[1, 2, 2, 1], padding='SAME')
    111.  
    112.  
    113. def weight_variable(shape):
    114. """weight_variable generates a weight variable of a given shape."""
    115. initial = tf.truncated_normal(shape, stddev=0.1)
    116. return tf.Variable(initial)
    117.  
    118.  
    119. def bias_variable(shape):
    120. """bias_variable generates a bias variable of a given shape."""
    121. initial = tf.constant(0.1, shape=shape)
    122. return tf.Variable(initial)
    123.  
    124.  
    125. def main(_):
    126. # Import data
    127. mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
    128.  
    129. # Create the model
    130. x = tf.placeholder(tf.float32, [None, 784])
    131.  
    132. # Define loss and optimizer
    133. y_ = tf.placeholder(tf.float32, [None, 10])
    134.  
    135. # Build the graph for the deep net
    136. y_conv, keep_prob = deepnn(x)
    137.  
    138. with tf.name_scope('loss'):
    139. cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
    140. logits=y_conv)
    141. cross_entropy = tf.reduce_mean(cross_entropy)
    142.  
    143. with tf.name_scope('adam_optimizer'):
    144. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    145.  
    146. with tf.name_scope('accuracy'):
    147. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    148. correct_prediction = tf.cast(correct_prediction, tf.float32)
    149. accuracy = tf.reduce_mean(correct_prediction)
    150.  
    151. graph_location = tempfile.mkdtemp()
    152. print('Saving graph to: %s' % graph_location)
    153. train_writer = tf.summary.FileWriter(graph_location)
    154. train_writer.add_graph(tf.get_default_graph())
    155.  
    156. with tf.Session() as sess:
    157. sess.run(tf.global_variables_initializer())
    158. for i in range(20000):
    159. batch = mnist.train.next_batch(50)
    160. if i % 100 == 0:
    161. train_accuracy = accuracy.eval(feed_dict={
    162. x: batch[0], y_: batch[1], keep_prob: 1.0})
    163. print('step %d, training accuracy %g' % (i, train_accuracy))
    164. train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    165.  
    166. #print('test accuracy %g' % accuracy.eval(feed_dict={
    167. # x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
    168. batch_size = 50
    169. batch_num = int(mnist.test.num_examples / batch_size)
    170. test_accuracy = 0
    171.  
    172. for i in range(batch_num):
    173. batch = mnist.test.next_batch(batch_size)
    174. test_accuracy += accuracy.eval(feed_dict={x: batch[0],
    175. y_: batch[1],
    176. keep_prob: 1.0})
    177.  
    178. test_accuracy /= batch_num
    179. print("test accuracy %g"%test_accuracy)
    180.  
    181. if __name__ == '__main__':
    182. parser = argparse.ArgumentParser()
    183. parser.add_argument('--data_dir', type=str,
    184. default='/tmp/tensorflow/mnist/input_data',
    185. help='Directory for storing input data')
    186. FLAGS, unparsed = parser.parse_known_args()
    187. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
    188.