|
| 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 add(x, y): |
| 40 | + return tf.nn.bias_add(x, y, data_format="NCHW") |
| 41 | + |
| 42 | +def deepnn(x): |
| 43 | + """deepnn builds the graph for a deep net for classifying digits. |
| 44 | +
|
| 45 | + Args: |
| 46 | + x: an input tensor with the dimensions (N_examples, 784), where 784 is the |
| 47 | + number of pixels in a standard MNIST image. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values |
| 51 | + equal to the logits of classifying the digit into one of 10 classes (the |
| 52 | + digits 0-9). keep_prob is a scalar placeholder for the probability of |
| 53 | + dropout. |
| 54 | + """ |
| 55 | + # Reshape to use within a convolutional neural net. |
| 56 | + # Last dimension is for "features" - there is only one here, since images are |
| 57 | + # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. |
| 58 | + with tf.name_scope('reshape'): |
| 59 | + x_image = tf.reshape(x, [-1, 1, 28, 28]) |
| 60 | + |
| 61 | + # First convolutional layer - maps one grayscale image to 32 feature maps. |
| 62 | + with tf.name_scope('conv1'): |
| 63 | + W_conv1 = weight_variable([5, 5, 1, 32]) |
| 64 | + b_conv1 = bias_variable([32]) |
| 65 | + h_conv1 = tf.nn.relu(add(conv2d(x_image, W_conv1), b_conv1)) |
| 66 | + |
| 67 | + # Pooling layer - downsamples by 2X. |
| 68 | + with tf.name_scope('pool1'): |
| 69 | + h_pool1 = max_pool_2x2(h_conv1) |
| 70 | + |
| 71 | + # Second convolutional layer -- maps 32 feature maps to 64. |
| 72 | + with tf.name_scope('conv2'): |
| 73 | + W_conv2 = weight_variable([5, 5, 32, 64]) |
| 74 | + b_conv2 = bias_variable([64]) |
| 75 | + h_conv2 = tf.nn.relu(add(conv2d(h_pool1, W_conv2), b_conv2)) |
| 76 | + |
| 77 | + # Second pooling layer. |
| 78 | + with tf.name_scope('pool2'): |
| 79 | + h_pool2 = max_pool_2x2(h_conv2) |
| 80 | + |
| 81 | + # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image |
| 82 | + # is down to 7x7x64 feature maps -- maps this to 1024 features. |
| 83 | + with tf.name_scope('fc1'): |
| 84 | + W_fc1 = weight_variable([7 * 7 * 64, 1024]) |
| 85 | + b_fc1 = bias_variable([1024]) |
| 86 | + |
| 87 | + h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) |
| 88 | + h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) |
| 89 | + |
| 90 | + # Map the 1024 features to 10 classes, one for each digit |
| 91 | + with tf.name_scope('fc2'): |
| 92 | + W_fc2 = weight_variable([1024, 10]) |
| 93 | + b_fc2 = bias_variable([10]) |
| 94 | + |
| 95 | + y_conv = tf.matmul(h_fc1, W_fc2) + b_fc2 |
| 96 | + |
| 97 | + return y_conv |
| 98 | + |
| 99 | + |
| 100 | +def conv2d(x, W): |
| 101 | + """conv2d returns a 2d convolution layer with full stride.""" |
| 102 | + return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME', data_format="NCHW") |
| 103 | + |
| 104 | + |
| 105 | +def max_pool_2x2(x): |
| 106 | + """max_pool_2x2 downsamples a feature map by 2X.""" |
| 107 | + return tf.nn.max_pool(x, ksize=[1, 1, 2, 2], |
| 108 | + strides=[1, 1, 2, 2], padding='SAME', data_format="NCHW") |
| 109 | + |
| 110 | + |
| 111 | +def weight_variable(shape): |
| 112 | + """weight_variable generates a weight variable of a given shape.""" |
| 113 | + initial = tf.truncated_normal(shape, stddev=0.1) |
| 114 | + return tf.Variable(initial) |
| 115 | + |
| 116 | + |
| 117 | +def bias_variable(shape): |
| 118 | + """bias_variable generates a bias variable of a given shape.""" |
| 119 | + initial = tf.constant(0.1, shape=shape) |
| 120 | + return tf.Variable(initial) |
| 121 | + |
| 122 | + |
| 123 | +def main(_): |
| 124 | + # Import data |
| 125 | + mnist = input_data.read_data_sets(FLAGS.data_dir) |
| 126 | + |
| 127 | + # Create the model |
| 128 | + x = tf.placeholder(tf.float32, [None, 784]) |
| 129 | + |
| 130 | + # Build the graph for the deep net |
| 131 | + y_conv = deepnn(x) |
| 132 | + |
| 133 | + with open("graph.proto", "wb") as file: |
| 134 | + graph = tf.get_default_graph().as_graph_def(add_shapes=True) |
| 135 | + file.write(graph.SerializeToString()) |
| 136 | + |
| 137 | + # Define loss and optimizer |
| 138 | + y_ = tf.placeholder(tf.int64, [None]) |
| 139 | + |
| 140 | + with tf.name_scope('loss'): |
| 141 | + cross_entropy = tf.losses.sparse_softmax_cross_entropy( |
| 142 | + labels=y_, logits=y_conv) |
| 143 | + cross_entropy = tf.reduce_mean(cross_entropy) |
| 144 | + |
| 145 | + with tf.name_scope('adam_optimizer'): |
| 146 | + train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) |
| 147 | + |
| 148 | + with tf.name_scope('accuracy'): |
| 149 | + correct_prediction = tf.equal(tf.argmax(y_conv, 1), y_) |
| 150 | + correct_prediction = tf.cast(correct_prediction, tf.float32) |
| 151 | + accuracy = tf.reduce_mean(correct_prediction) |
| 152 | + |
| 153 | + graph_location = tempfile.mkdtemp() |
| 154 | + print('Saving graph to: %s' % graph_location) |
| 155 | + train_writer = tf.summary.FileWriter(graph_location) |
| 156 | + train_writer.add_graph(tf.get_default_graph()) |
| 157 | + |
| 158 | + saver = tf.train.Saver() |
| 159 | + |
| 160 | + with tf.Session() as sess: |
| 161 | + sess.run(tf.global_variables_initializer()) |
| 162 | + for i in range(20000): |
| 163 | + batch = mnist.train.next_batch(50) |
| 164 | + |
| 165 | + if i % 1000 == 0: |
| 166 | + train_accuracy = accuracy.eval(feed_dict={ |
| 167 | + x: batch[0], y_: batch[1]}) |
| 168 | + print('step %d, training accuracy %g' % (i, train_accuracy)) |
| 169 | + |
| 170 | + save_path = saver.save(sess, "./ckpt/model.ckpt") |
| 171 | + print("Model saved in path: %s" % save_path) |
| 172 | + train_step.run(feed_dict={x: batch[0], y_: batch[1]}) |
| 173 | + |
| 174 | + print('test accuracy %g' % accuracy.eval(feed_dict={ |
| 175 | + x: mnist.test.images, y_: mnist.test.labels})) |
| 176 | + |
| 177 | +if __name__ == '__main__': |
| 178 | + parser = argparse.ArgumentParser() |
| 179 | + parser.add_argument('--data_dir', type=str, |
| 180 | + default='/tmp/tensorflow/mnist/input_data', |
| 181 | + help='Directory for storing input data') |
| 182 | + FLAGS, unparsed = parser.parse_known_args() |
| 183 | + tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) |
| 184 | + |
0 commit comments