Last active
March 22, 2019 15:58
-
-
Save Coldsp33d/594ac525fbaced1836bdc94291c73921 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Convolutional Neural Network with the MNIST dataset using Tensorflow.""" | |
import numpy as np | |
import tensorflow as tf | |
tf.logging.set_verbosity(tf.logging.INFO) | |
def cnn_model_fn(features, labels, mode): | |
"""Train a CNN model on the MNIST dataset. | |
Args: | |
features: input images as arrays | |
labels: categorical labels (digits) | |
mode: one of TRAIN/TEST/EVAL | |
Returns: | |
`tf.estimator.EstimatorSpec` | |
""" | |
input_layer = tf.reshape(features, [-1, 28, 28, 1]) | |
conv1 = tf.layers.conv2d( | |
inputs=input_layer, | |
filters=32, | |
kernel_size=[5, 5], | |
padding='same', | |
activation=tf.nn.relu) | |
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) | |
conv2 = tf.layers.conv2d( | |
inputs=pool1, | |
filters=6, | |
kernel_size=[5, 5], | |
padding='same', | |
activation=tf.nn.relu) | |
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) | |
pool2_flat = tf.layers.flatten(pool2) | |
dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) | |
dropout = tf.layers.dropout( | |
inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN) | |
logits = tf.layers.dense(inputs=dropout, units=10) | |
loss = tf.losses.sparse_softmax_cross_entropy(labels, logits=logits) | |
predictions = { | |
'classes': tf.argmax(input=logits, axis=1), | |
'probabilities': tf.nn.softmax(logits, name='softmax_tensor') | |
} | |
if mode == tf.estimator.ModeKeys.TRAIN: | |
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize( | |
loss, global_step=tf.train.get_global_step()) | |
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=optimizer) | |
elif mode == tf.estimator.ModeKeys.PREDICT: | |
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) | |
else: | |
eval_metric_ops = { | |
'accuracy': tf.metrics.accuracy( | |
labels=labels, predictions=predictions['classes'])} | |
return tf.estimator.EstimatorSpec( | |
mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) | |
def main(unused_args): | |
mnist = tf.contrib.learn.datasets.load_dataset('mnist') | |
train_data = mnist.train.images # Returns np.array | |
train_labels = np.asarray(mnist.train.labels, dtype=np.int32) | |
eval_data = mnist.test.images # Returns np.array | |
eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) | |
mnist_classifier = tf.estimator.Estimator( | |
model_fn=cnn_model_fn, model_dir='/tmp/mnist_convnet_model') | |
# Set up logging for predictions | |
# Log the values in the 'Softmax' tensor with label 'probabilities' | |
# Train the model | |
train_input_fn = tf.estimator.inputs.numpy_input_fn( | |
x=train_data, | |
y=train_labels, | |
batch_size=100, | |
num_epochs=None, | |
shuffle=True) | |
mnist_classifier.train( | |
input_fn=train_input_fn, | |
steps=20000) | |
# Evaluate the model and print results | |
eval_input_fn = tf.estimator.inputs.numpy_input_fn( | |
x=eval_data, | |
y=eval_labels, | |
num_epochs=1, | |
shuffle=False) | |
eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn) | |
print(eval_results) | |
if __name__ == '__main__': | |
tf.app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
numpy_input_fn is deprecated, can you do an example with an input pipeline instead?