MNIST data set image classification using Tensor Flow


In [1]:
# Importing tensorflow lib
import tensorflow as tf

tf.__version__ #Checking if notebook is working in tensorflow


Out[1]:
'1.4.0'

In [2]:
# Reading the dataset from Yann LeCun's Website: http://yann.lecun.com/exdb/mnist/

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)


Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz

In [3]:
x = tf.placeholder(tf.float32, [None, 784])

x is a placeholder, a value that we'll input when we ask TensorFlow to run a computation. We want to be able to input any number of MNIST images, each flattened into a 784-dimensional vector. We represent this as a 2-D tensor of floating-point numbers, with a shape [None, 784]. (Here None means that a dimension can be of any length)


In [4]:
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

In [5]:
# Implement Softmax Regression
y = tf.nn.softmax(tf.matmul(x, W) + b)

In [6]:
# Implementing Cross entropy to calculate the loss/error

y_ = tf.placeholder(tf.float32, [None, 10]) # a placeholder to input the correct answers

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

In [7]:
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # Learning rate = 0.5

Execution of the Model in Session


In [8]:
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

In [9]:
for _ in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

Evaluating the model


In [10]:
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}))


0.9189

In [12]:
mnist.test.images


Out[12]:
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       ..., 
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.],
       [ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32)

In [ ]: