Coders Packet

Predicting Hand-Written Digits in Python Using Keras

By Anoushka Mergoju

In this project, we are going to predict handwritten digits in Python using Keras deep learning API. We'll be importing the mnist dataset from Keras.

In this project, we are going to predict handwritten digits in Python using Keras deep learning API. We'll be importing the MNIST dataset from Keras. We will also be building a CNN model.

CNN stands for Convolutional Neural Network which is mainly used for image-related datasets. This project is divided into six steps namely:

1. Importing the libraries

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
from keras.datasets import mnist

import matplotlib.pyplot as plt

We've imported NumPy and Pandas here that are Python packages used in data manipulation and scientific computing. Dense, Conv2D, Flatten, MaxPooling2D are the layers we'll be using and Sequential defines the model being used.

2. Loading the dataset

(x_train, y_train), (x_test, y_test) = mnist.load_data()

3. Data Preprocessing

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

In the above code snippets, we have reshaped our dataset and normalized our data between 0 and 1.

Now, to deal with class variables, we execute the following code.

from keras.utils import np_utils
y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

4. Building the CNN Model

model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), activation = 'relu', input_shape = (28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dense(128, activation = 'relu'))
model.add(Dense(10,activation = 'softmax'))

Now, to compile our model:

model.compile(optimizer='adam', loss = 'mean_squared_error', metrics=['accuracy'])

The model has been successfully built.

5. Training the model, y_train, epochs = 5)

I have enabled 5 epochs. For training the model, we pass the x_train and y_train through the fit() function.

By doing so, we train our model with the dataset at hand.

Moving further, our last and final step would be to predict our test results. 

6. Predicting test results.

image_index = 5555
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))

Upon running the code, we will notice that a handwritten digit has been decrypted. This way, we have built a CNN model using MNIST dataset from Keras deep learning API.

Thank you.


Download Complete Code


No comments yet