<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://charlesreid1.com/w/index.php?action=history&amp;feed=atom&amp;title=TensorFlow%2FMNIST2</id>
	<title>TensorFlow/MNIST2 - Revision history</title>
	<link rel="self" type="application/atom+xml" href="https://charlesreid1.com/w/index.php?action=history&amp;feed=atom&amp;title=TensorFlow%2FMNIST2"/>
	<link rel="alternate" type="text/html" href="https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;action=history"/>
	<updated>2026-06-19T11:40:50Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.39.12</generator>
	<entry>
		<id>https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;diff=22109&amp;oldid=prev</id>
		<title>Admin at 01:44, 28 October 2017</title>
		<link rel="alternate" type="text/html" href="https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;diff=22109&amp;oldid=prev"/>
		<updated>2017-10-28T01:44:06Z</updated>

		<summary type="html">&lt;p&gt;&lt;/p&gt;
&lt;a href=&quot;https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;amp;diff=22109&amp;amp;oldid=22108&quot;&gt;Show changes&lt;/a&gt;</summary>
		<author><name>Admin</name></author>
	</entry>
	<entry>
		<id>https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;diff=22108&amp;oldid=prev</id>
		<title>Admin: Created page with &quot;=Simple MNIST Convolutional Network=  ==Input Function==  Define an input function. This has an internal function that parses the example data (one piece of data at a time) an...&quot;</title>
		<link rel="alternate" type="text/html" href="https://charlesreid1.com/w/index.php?title=TensorFlow/MNIST2&amp;diff=22108&amp;oldid=prev"/>
		<updated>2017-10-28T01:43:30Z</updated>

		<summary type="html">&lt;p&gt;Created page with &amp;quot;=Simple MNIST Convolutional Network=  ==Input Function==  Define an input function. This has an internal function that parses the example data (one piece of data at a time) an...&amp;quot;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;=Simple MNIST Convolutional Network=&lt;br /&gt;
&lt;br /&gt;
==Input Function==&lt;br /&gt;
&lt;br /&gt;
Define an input function. This has an internal function that parses the example data (one piece of data at a time) and one-hot encodes the labeled images with the digit it corresponds to.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def input_fn(mode, batch_size=1):&lt;br /&gt;
  &amp;quot;&amp;quot;&amp;quot;A simple input_fn using the contrib.data input pipeline.&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
  def example_parser(serialized_example):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;Parses a single tf.Example into image and label tensors.&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    features = tf.parse_single_example(&lt;br /&gt;
        serialized_example,&lt;br /&gt;
        features={&lt;br /&gt;
            &amp;#039;image_raw&amp;#039;: tf.FixedLenFeature([], tf.string),&lt;br /&gt;
            &amp;#039;label&amp;#039;: tf.FixedLenFeature([], tf.int64),&lt;br /&gt;
        })&lt;br /&gt;
    image = tf.decode_raw(features[&amp;#039;image_raw&amp;#039;], tf.uint8)&lt;br /&gt;
    image.set_shape([28 * 28])&lt;br /&gt;
&lt;br /&gt;
    # Normalize the values of the image from the range [0, 255] to [-0.5, 0.5]&lt;br /&gt;
    image = tf.cast(image, tf.float32) / 255 - 0.5&lt;br /&gt;
    label = tf.cast(features[&amp;#039;label&amp;#039;], tf.int32)&lt;br /&gt;
    return image, tf.one_hot(label, 10)&lt;br /&gt;
&lt;br /&gt;
  if mode == tf.estimator.ModeKeys.TRAIN:&lt;br /&gt;
    tfrecords_file = os.path.join(FLAGS.data_dir, &amp;#039;train.tfrecords&amp;#039;)&lt;br /&gt;
  else:&lt;br /&gt;
    assert mode == tf.estimator.ModeKeys.EVAL, &amp;#039;invalid mode&amp;#039;&lt;br /&gt;
    tfrecords_file = os.path.join(FLAGS.data_dir, &amp;#039;test.tfrecords&amp;#039;)&lt;br /&gt;
&lt;br /&gt;
  assert tf.gfile.Exists(tfrecords_file), (&lt;br /&gt;
      &amp;#039;Run convert_to_records.py first to convert the MNIST data to TFRecord &amp;#039;&lt;br /&gt;
      &amp;#039;file format.&amp;#039;)&lt;br /&gt;
&lt;br /&gt;
  dataset = tf.contrib.data.TFRecordDataset([tfrecords_file])&lt;br /&gt;
&lt;br /&gt;
  # For training, repeat the dataset forever&lt;br /&gt;
  if mode == tf.estimator.ModeKeys.TRAIN:&lt;br /&gt;
    dataset = dataset.repeat()&lt;br /&gt;
&lt;br /&gt;
  # Map example_parser over dataset, and batch results by up to batch_size&lt;br /&gt;
  dataset = dataset.map(&lt;br /&gt;
      example_parser, num_threads=1, output_buffer_size=batch_size)&lt;br /&gt;
  dataset = dataset.batch(batch_size)&lt;br /&gt;
  images, labels = dataset.make_one_shot_iterator().get_next()&lt;br /&gt;
&lt;br /&gt;
  return images, labels&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Prepare Model==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def mnist_model(inputs, mode):&lt;br /&gt;
  &amp;quot;&amp;quot;&amp;quot;Takes the MNIST inputs and mode and outputs a tensor of logits.&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
  # Input Layer&lt;br /&gt;
  # Reshape X to 4-D tensor: [batch_size, width, height, channels]&lt;br /&gt;
  # MNIST images are 28x28 pixels, and have one color channel&lt;br /&gt;
  inputs = tf.reshape(inputs, [-1, 28, 28, 1])&lt;br /&gt;
  data_format = FLAGS.data_format&lt;br /&gt;
&lt;br /&gt;
  if data_format is None:&lt;br /&gt;
    # When running on GPU, transpose the data from channels_last (NHWC) to&lt;br /&gt;
    # channels_first (NCHW) to improve performance.&lt;br /&gt;
    # See https://www.tensorflow.org/performance/performance_guide#data_formats&lt;br /&gt;
    data_format = (&amp;#039;channels_first&amp;#039; if tf.test.is_built_with_cuda() else&lt;br /&gt;
                   &amp;#039;channels_last&amp;#039;)&lt;br /&gt;
&lt;br /&gt;
  if data_format == &amp;#039;channels_first&amp;#039;:&lt;br /&gt;
    inputs = tf.transpose(inputs, [0, 3, 1, 2])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Construct Model==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  # Convolutional Layer #1&lt;br /&gt;
  # Computes 32 features using a 5x5 filter with ReLU activation.&lt;br /&gt;
  # Padding is added to preserve width and height.&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 28, 28, 1]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 28, 28, 32]&lt;br /&gt;
  conv1 = tf.layers.conv2d(&lt;br /&gt;
      inputs=inputs,&lt;br /&gt;
      filters=32,&lt;br /&gt;
      kernel_size=[5, 5],&lt;br /&gt;
      padding=&amp;#039;same&amp;#039;,&lt;br /&gt;
      activation=tf.nn.relu,&lt;br /&gt;
      data_format=data_format)&lt;br /&gt;
&lt;br /&gt;
  # Pooling Layer #1&lt;br /&gt;
  # First max pooling layer with a 2x2 filter and stride of 2&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 28, 28, 32]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 14, 14, 32]&lt;br /&gt;
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2,&lt;br /&gt;
                                  data_format=data_format)&lt;br /&gt;
&lt;br /&gt;
  # Convolutional Layer #2&lt;br /&gt;
  # Computes 64 features using a 5x5 filter.&lt;br /&gt;
  # Padding is added to preserve width and height.&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 14, 14, 32]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 14, 14, 64]&lt;br /&gt;
  conv2 = tf.layers.conv2d(&lt;br /&gt;
      inputs=pool1,&lt;br /&gt;
      filters=64,&lt;br /&gt;
      kernel_size=[5, 5],&lt;br /&gt;
      padding=&amp;#039;same&amp;#039;,&lt;br /&gt;
      activation=tf.nn.relu,&lt;br /&gt;
      data_format=data_format)&lt;br /&gt;
&lt;br /&gt;
  # Pooling Layer #2&lt;br /&gt;
  # Second max pooling layer with a 2x2 filter and stride of 2&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 14, 14, 64]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 7, 7, 64]&lt;br /&gt;
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2,&lt;br /&gt;
                                  data_format=data_format)&lt;br /&gt;
&lt;br /&gt;
  # Flatten tensor into a batch of vectors&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 7, 7, 64]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 7 * 7 * 64]&lt;br /&gt;
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])&lt;br /&gt;
&lt;br /&gt;
  # Dense Layer&lt;br /&gt;
  # Densely connected layer with 1024 neurons&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 7 * 7 * 64]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 1024]&lt;br /&gt;
  dense = tf.layers.dense(inputs=pool2_flat, units=1024,&lt;br /&gt;
                          activation=tf.nn.relu)&lt;br /&gt;
&lt;br /&gt;
  # Add dropout operation; 0.6 probability that element will be kept&lt;br /&gt;
  dropout = tf.layers.dropout(&lt;br /&gt;
      inputs=dense, rate=0.4, training=(mode == tf.estimator.ModeKeys.TRAIN))&lt;br /&gt;
&lt;br /&gt;
  # Logits layer&lt;br /&gt;
  # Input Tensor Shape: [batch_size, 1024]&lt;br /&gt;
  # Output Tensor Shape: [batch_size, 10]&lt;br /&gt;
  logits = tf.layers.dense(inputs=dropout, units=10)&lt;br /&gt;
  return logits&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Get Estimator==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def mnist_model_fn(features, labels, mode):&lt;br /&gt;
  &amp;quot;&amp;quot;&amp;quot;Model function for MNIST.&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
  logits = mnist_model(features, mode)&lt;br /&gt;
&lt;br /&gt;
  predictions = {&lt;br /&gt;
      &amp;#039;classes&amp;#039;: tf.argmax(input=logits, axis=1),&lt;br /&gt;
      &amp;#039;probabilities&amp;#039;: tf.nn.softmax(logits, name=&amp;#039;softmax_tensor&amp;#039;)&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  if mode == tf.estimator.ModeKeys.PREDICT:&lt;br /&gt;
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)&lt;br /&gt;
&lt;br /&gt;
  loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)&lt;br /&gt;
&lt;br /&gt;
  # Configure the training op&lt;br /&gt;
  if mode == tf.estimator.ModeKeys.TRAIN:&lt;br /&gt;
    optimizer = tf.train.AdamOptimizer(learning_rate=1e-4)&lt;br /&gt;
    train_op = optimizer.minimize(loss, tf.train.get_or_create_global_step())&lt;br /&gt;
  else:&lt;br /&gt;
    train_op = None&lt;br /&gt;
&lt;br /&gt;
  accuracy = tf.metrics.accuracy(&lt;br /&gt;
      tf.argmax(labels, axis=1), predictions[&amp;#039;classes&amp;#039;])&lt;br /&gt;
  metrics = {&amp;#039;accuracy&amp;#039;: accuracy}&lt;br /&gt;
&lt;br /&gt;
  # Create a tensor named train_accuracy for logging purposes&lt;br /&gt;
  tf.identity(accuracy[1], name=&amp;#039;train_accuracy&amp;#039;)&lt;br /&gt;
  tf.summary.scalar(&amp;#039;train_accuracy&amp;#039;, accuracy[1])&lt;br /&gt;
&lt;br /&gt;
  return tf.estimator.EstimatorSpec(&lt;br /&gt;
      mode=mode,&lt;br /&gt;
      predictions=predictions,&lt;br /&gt;
      loss=loss,&lt;br /&gt;
      train_op=train_op,&lt;br /&gt;
      eval_metric_ops=metrics)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Main Function==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def main(unused_argv):&lt;br /&gt;
  # Create the Estimator&lt;br /&gt;
  mnist_classifier = tf.estimator.Estimator(&lt;br /&gt;
      model_fn=mnist_model_fn, model_dir=FLAGS.model_dir)&lt;br /&gt;
&lt;br /&gt;
  # Train the model&lt;br /&gt;
  tensors_to_log = {&lt;br /&gt;
      &amp;#039;train_accuracy&amp;#039;: &amp;#039;train_accuracy&amp;#039;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  logging_hook = tf.train.LoggingTensorHook(&lt;br /&gt;
      tensors=tensors_to_log, every_n_iter=100)&lt;br /&gt;
&lt;br /&gt;
  batches_per_epoch = _NUM_IMAGES[&amp;#039;train&amp;#039;] / FLAGS.batch_size&lt;br /&gt;
&lt;br /&gt;
  mnist_classifier.train(&lt;br /&gt;
      input_fn=lambda: input_fn(tf.estimator.ModeKeys.TRAIN, FLAGS.batch_size),&lt;br /&gt;
      steps=FLAGS.train_epochs * batches_per_epoch,&lt;br /&gt;
      hooks=[logging_hook])&lt;br /&gt;
&lt;br /&gt;
  # Evaluate the model and print results&lt;br /&gt;
  eval_results = mnist_classifier.evaluate(&lt;br /&gt;
      input_fn=lambda: input_fn(tf.estimator.ModeKeys.EVAL))&lt;br /&gt;
  print()&lt;br /&gt;
  print(&amp;#039;Evaluation results:\n    %s&amp;#039; % eval_results)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Flags=&lt;br /&gt;
&lt;br /&gt;
[[Category:NN]]&lt;br /&gt;
[[Category:ML]]&lt;br /&gt;
[[Category:TensorFlow]]&lt;br /&gt;
[[Category:MNIST]]&lt;br /&gt;
[[Category:Convolutional NN]]&lt;/div&gt;</summary>
		<author><name>Admin</name></author>
	</entry>
</feed>