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 :
$ pip install numpy
$ pip install matplotlib
$ pip install tensorflow
Steps to follow
Step 1 : Importing all dependence
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf learn = tf.contrib.learn tf.logging.set_verbosity(tf.logging.ERROR) |
Step 2 : Importing Dataset using MNIST Data
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) |
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
max_examples = 10000data = data[:max_examples] labels = labels[:max_examples] |
Step 4 : Displaying dataset using MatplotLib
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) |
To display data we can use this function – display(0)
output :

Step 5 : Fitting data, using 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) |
Step 6 : Evaluate accuracy
classifier.evaluate(test_data, test_labels) print(classifier.evaluate(test_data, test_labels)["accuracy"]) |
Output :
0.9137
Step 7 : Predicting data
prediction = classifier.predict(np.array([test_data[0]], dtype=float), as_iterable=False) print("prediction : {}, label : {}".format(prediction, test_labels[0]) ) |
Output :
prediction : [7], label : 7
Full Code for classifying handwritten
# 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 = 10000data = 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) |
Recommended Posts:
- OCR of Handwritten digits | OpenCV
- Identifying handwritten digits using Logistic Regression in PyTorch
- Handwritten Equation Solver in Python
- Python | Tensorflow sin() method
- Python | Tensorflow nn.sigmoid()
- Python | Tensorflow tan() method
- Python | Tensorflow cos() method
- Python | Tensorflow nn.tanh()
- Python | Tensorflow exp() method
- Python | Tensorflow abs() method
- Python | Tensorflow nn.softplus()
- Python | Tensorflow log() method
- Python | Tensorflow acosh() method
- Python | Tensorflow atan() method
- Python | Tensorflow logical_xor() method
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.

