Credits: Forked from TensorFlow-Examples by Aymeric Damien
Refer to the setup instructions
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Extracting /tmp/data/train-images-idx3-ubyte.gz Extracting /tmp/data/train-labels-idx1-ubyte.gz Extracting /tmp/data/t10k-images-idx3-ubyte.gz Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
# Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1
# tf Graph Input
x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes
# Create model
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model
activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
# Minimize error using cross entropy
# Cross entropy
cost = -tf.reduce_sum(y*tf.log(activation))
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
# Compute average loss
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print ("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print ("Optimization Finished!")
# Test model
correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print ("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
Epoch: 0001 cost= 30.201449143 Epoch: 0002 cost= 22.036444135 Epoch: 0003 cost= 21.054862718 Epoch: 0004 cost= 20.597353284 Epoch: 0005 cost= 20.190342429 Epoch: 0006 cost= 19.786361580 Epoch: 0007 cost= 19.593195786 Epoch: 0008 cost= 19.423822853 Epoch: 0009 cost= 19.390960660 Epoch: 0010 cost= 19.237225328 Epoch: 0011 cost= 19.129154354 Epoch: 0012 cost= 19.068082945 Epoch: 0013 cost= 18.961399286 Epoch: 0014 cost= 18.836373898 Epoch: 0015 cost= 18.799891092 Epoch: 0016 cost= 18.727478255 Epoch: 0017 cost= 18.591258308 Epoch: 0018 cost= 18.676952642 Epoch: 0019 cost= 18.548722290 Epoch: 0020 cost= 18.484304102 Epoch: 0021 cost= 18.437379690 Epoch: 0022 cost= 18.387524192 Epoch: 0023 cost= 18.353106305 Epoch: 0024 cost= 18.252915604 Epoch: 0025 cost= 18.257536320 Optimization Finished! Accuracy: 0.9233