Python | Classify Handwritten Digits with Tensorflow

Classifying handwritten digits using a linear classifier algorithm, we will implement it by using TensorFlow learn module tf.contrib.learn. linear classifier achieves the classification of handwritten digits by making a choice based on the value of a linear combination of the features also known as feature values and is typically presented to the machine in a vector called a feature vector.

Modules required :

NumPy:



$ pip install numpy 

Matplotlib:

$ pip install matplotlib 

Tensorflow:

$ pip install tensorflow 

Steps to follow

Step 1 : Importing all dependence

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
  
learn = tf.contrib.learn
  
tf.logging.set_verbosity(tf.logging.ERROR)

chevron_right


Step 2 : Importing Dataset using MNIST Data

filter_none

edit
close

play_arrow

link
brightness_4
code

mnist = learn.datasets.load_dataset('mnist')
data = mnist.train.images
labels = np.asarray(mnist.train.labels, dtype=np.int32)
test_data = mnist.test.images
test_labels = np.asarray(mnist.test.labels, dtype=np.int32)

chevron_right


after this step a dataset of mnist will be downloaded.
output :

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

Step 3 : Making dataset

filter_none

edit
close

play_arrow

link
brightness_4
code

max_examples = 10000
data = data[:max_examples]
labels = labels[:max_examples]

chevron_right


Step 4 : Displaying dataset using MatplotLib

filter_none

edit
close

play_arrow

link
brightness_4
code

def display(i):
    img = test_data[i]
    plt.title('label : {}'.format(test_labels[i]))
    plt.imshow(img.reshape((28, 28)))
      
# image in TensorFlow is 28 by 28 px
display(0)

chevron_right


To display data we can use this function – display(0)
output :

Step 5 : Fitting data, using linear classifier


filter_none

edit
close

play_arrow

link
brightness_4
code

feature_columns = learn.infer_real_valued_columns_from_input(data)
classifier = learn.LinearClassifier(n_classes=10
                                    feature_columns=feature_columns)
classifier.fit(data, labels, batch_size=100, steps=1000)

chevron_right


Step 6 : Evaluate accuracy

filter_none

edit
close

play_arrow

link
brightness_4
code

classifier.evaluate(test_data, test_labels)
print(classifier.evaluate(test_data, test_labels)["accuracy"])

chevron_right


Output :

0.9137

Step 7 : Predicting data

filter_none

edit
close

play_arrow

link
brightness_4
code

prediction = classifier.predict(np.array([test_data[0]], 
                                         dtype=float), 
                                         as_iterable=False)
print("prediction : {}, label : {}".format(prediction, 
      test_labels[0]) )

chevron_right


Output :

prediction : [7], label : 7

Full Code for classifying handwritten

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing libraries
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
  
learn = tf.contrib.learn
tf.logging.set_verbosity(tf.logging.ERROR)\
  
# importing dataset using MNIST
# this is how mnist is used mnist contain test and train dataset
mnist = learn.datasets.load_dataset('mnist')
data = mnist.train.images
labels = np.asarray(mnist.train.labels, dtype = np.int32)
test_data = mnist.test.images
test_labels = np.asarray(mnist.test.labels, dtype = np.int32)
  
max_examples = 10000
data = data[:max_examples]
labels = labels[:max_examples]
  
# displaying dataset using Matplotlib
def display(i):
    img = test_data[i]
    plt.title('label : {}'.format(test_labels[i]))
    plt.imshow(img.reshape((28, 28)))
      
# img in tf is 28 by 28 px
# fitting linear classifier
feature_columns = learn.infer_real_valued_columns_from_input(data)
classifier = learn.LinearClassifier(n_classes = 10
                                    feature_columns = feature_columns)
classifier.fit(data, labels, batch_size = 100, steps = 1000)
  
# Evaluate accuracy
classifier.evaluate(test_data, test_labels)
print(classifier.evaluate(test_data, test_labels)["accuracy"])
  
prediction = classifier.predict(np.array([test_data[0]], 
                                         dtype=float), 
                                         as_iterable=False)
print("prediction : {}, label : {}".format(prediction, 
      test_labels[0]) )
  
if prediction == test_labels[0]:
     display(0)

chevron_right




My Personal Notes arrow_drop_up

A 3rd-year Computer Science and Engineering undergraduate student at IERT, Allahabad with an interest in Programming, Data Science/AI and web development

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.