Classify Handwritten Digits using Neural Networks


In this blog post, you’ll learn How to Classify Handwritten Digits using Neural Networks, i.e we will build an Artificial Neural Network and as well as a Convolutional Neural Network to classify the Handwritten digits.

Results are going to look like this-

Original Class as well as Predicted Class


To begin with, you need a basic understanding of the Artificial Neural Network. If you don’t know what Artificial Neural Network is, please take a moment and read this blog post or watch this YouTube video to understand Artificial Neural Networks in detail.

Setting up the Environment

I will be using Google Colab, so no need to install anything on your local machine. But if you want to use your local machine, that’s absolutely fine.

If you are planning to use Google Colab, here are the steps to follow –

  • Go to Google Colab. Sign in with your Google account.
  • Click on File -> New notebook.
  • Click on Connect (you can find it at the top right side corner) and YOU ARE GOOD TO GO.

Overview of the Dataset

We will use the famous MNIST(Modified National Institute of Standards and Technology) dataset. It has 60,000 labeled training images and 10,000 labeled testing images of handwritten digits. Each and every image is grayscale and the size is 28×28.

Packages needed

We need to import only Three packages, Numpy, Keras, and Matplotlib.

Classifying using ANN

#Building Model
model.add(Dense(300, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(10, activation="softmax"))

To view the Full code, please refer to any of the buttons:

Classifying using CNN

#Building Model
model.add(Conv2D(32,(3,3), input_shape=(28,28,1)))
model.add(Conv2D(16, (3,3)))
model.add(Dense(300, activation='relu'))
model.add(Dense(10, activation="softmax"))

To view the Full code, please refer to any of the buttons:

Watch Tutorial

I have already explained how to build a classifier that can classify the Handwritten Digits on YouTube, please refer to these videos to learn in-depth.


Handwritten digit recognition is very much easy on the MNIST dataset. The images are properly labeled and they all are in the same size(28×28) and they all are in one single color (Grayscale). But in real-life situations, you have to pre-process the data a lot to fit the model. Here CNN performs well and we achieved 98% accuracy on the test data which is very appreciatable. Let me know in the comment section, how well your model has performed. CNN takes a little bit of extra time because it calculates a lot with filters. To learn more please visit our YouTube Channel and follow this website.

Learn more about Machine Learning, Deep Learning, Artificial Neural Network for FREE – Tec4Tric Machine Learning Blog.