In [1]:
#this annotated tutorial is a walkthrough of the official google tutorial
#from https://www.tensorflow.org/tutorials/mnist/beginners/
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
#there are 784 pixels in any image, note that the matrix has been flattened.
#'None' simply means that the number of rows in this 2d array can be anything
W = tf.Variable(tf.zeros([784, 10]))
#For each of the ten digits, W contains the weights that we expect for each pixel
b = tf.Variable(tf.zeros([10]))
#The bias term required to build the softmax model
y = tf.nn.softmax(tf.matmul(x, W) + b)
#this is a [None,10] matrix, which gives the likelihood for every digit produced by our model
y_ = tf.placeholder(tf.float32, [None, 10])
#this is the actual digit shown, used for training
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
#calculating the cross-entropy of the model. The reduce_mean and reduce_sum functions do NOT perform
#optimizations, but rather they simply reduce the dimensionality of the input according to certain rules.
#More about these functions can be read here:
#https://www.tensorflow.org/api_docs/python/math_ops/reduction#reduce_sum
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#The actual training is defined here. The algorithm being used is gradient descent, although this may be changed
#depending on user preference/the task at hand.
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#this section initializes the environment, and is required to run the previously defined operations
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
#Here we're running the training over 1000 iterations
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
#these last few lines are simply to test the accuracy of our model
In [ ]: