Skip to content

Instantly share code, notes, and snippets.

@Tydus
Last active November 4, 2016 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Tydus/66b94ef9319580a3471272fc64266888 to your computer and use it in GitHub Desktop.
Save Tydus/66b94ef9319580a3471272fc64266888 to your computer and use it in GitHub Desktop.
mnist.py
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
weight_variable = lambda shape: tf.Variable(tf.truncated_normal(shape, stddev=0.1))
bias_variable = lambda shape: tf.Variable(tf.constant(0.1, shape=shape))
conv2d = lambda x, W: tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
max_pool_2x2 = lambda x: tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
Layer = lambda input, layer_type, activate_function, dimensions: (
activate_function(layer_type(input, weight_variable(dimensions)) + bias_variable([dimensions[-1]])))
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
keep_prob = tf.placeholder(tf.float32)
h_conv1 = Layer(tf.reshape(x, [-1, 28, 28, 1]), conv2d, tf.nn.relu, [5, 5, 1, 32])
h_pool1 = max_pool_2x2(h_conv1)
h_conv2 = Layer(h_pool1, conv2d, tf.nn.relu, [5, 5, 32, 64])
h_pool2 = max_pool_2x2(h_conv2)
h_fc1 = Layer(tf.reshape(h_pool2, [-1, 7 * 7 * 64]), tf.matmul, tf.nn.relu, [7 * 7 * 64, 1024])
y = Layer(tf.nn.dropout(h_fc1, keep_prob), tf.matmul, tf.nn.softmax, [1024, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
for i in range(40000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
if i%1000 == 0:
print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment