Building a Convolutional Neural Network (CNN) Model for Image classification.

Original article was published on Becoming Human: Artificial Intelligence Magazine

In this blog, I’ll show how to build CNN model for image classification.

In this project, I have used MNIST dataset, which is the basic and simple dataset which helps the beginner to understand the theory in depth.

So let’s start….

About Dataset

The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available from NIST. The digits have been size-normalized and centred in a fixed-size image.

So, now let’s jump into CODES!!

Big Data Jobs

You can access codes for this project here.

Import necessary libraries.

#Import necessary libraries
import pandas as pd
import numpy as np
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
%matplotlib inline
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D,
Flatten
from tensorflow.keras.callbacks import EarlyStopping

Loading Dataset

#Loading Dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

Check the shape of the training data

x_train.shape
>>(60000, 28, 28)

This means there are 60000 images of size 28 X 28.

Assigning the first image as single_image and finding the shape of the same.

single_image = x_train[0]
single_image.shape
>>(28, 28)

Now let’s check the shape of y_train

y_train.shape
>>(60000,)

Top 4 Most Popular Ai Articles:

1. AI for CFD: Intro (part 1)

2. Using Artificial Intelligence to detect COVID-19

3. Real vs Fake Tweet Detection using a BERT Transformer Model in few lines of code

4. Machine Learning System Design

Applying to_categorically to y_train — It converts a class vector (integer) to binary class matrix

y_example = to_categorical(y_train)

Checking the shape of y_example

y_example.shape
>>(6000, 10)

Apply to_categorical to y_test and y_train

y_cat_test = to_categorical(y_test,10)
y_cat_train = to_categorical(y_train,10)

Divide x_train and x_test by 255 in order to normalise the image

x_train = x_train/255
x_test = x_test/255

Now let’s again check the shape of x_train and x_test

x_train.shape
>>(60000, 28, 28)
x_test.shape
>>(10000, 28, 28)

Now we need to reshape x_train and x_test

x_train = x_train.reshape(60000, 28, 28, 1)
x_train.shape
>>(60000, 28, 28, 1)
x_test = x_test.reshape(10000,28,28,1)
x_test.shape
>>(10000, 28, 28, 1)

Now let’s build a Convolutional Neural Network Model.

model = Sequential()
# CONVOLUTIONAL LAYER
model.add(Conv2D(filters=32, kernel_size=(4,4),input_shape=(28, 28, 1), activation=’relu’,))
# POOLING LAYER
model.add(MaxPool2D(pool_size=(2, 2)))
# FLATTEN IMAGES FROM 28 by 28 to 764 BEFORE FINAL LAYER
model.add(Flatten())
# 128 NEURONS IN DENSE HIDDEN LAYER
model.add(Dense(128, activation=’relu’))
# LAST LAYER IS THE CLASSIFIER, THUS 10 POSSIBLE CLASSES
model.add(Dense(10, activation=’softmax’))
model.compile(loss=’categorical_crossentropy’,optimizer=’adam’,metrics=[‘accuracy’])

Let’s check the model

model.summary()

Now we’ll use EarlyStopping while fitting the model.

early_stop = EarlyStopping(monitor=’val_loss’,patience=2)
model.fit(x_train,y_cat_train,epochs=10,validation_data=(x_test,y_cat_test),callbacks=[early_stop])

Evaluating our model

print(model.evaluate(x_test,y_cat_test,verbose=0))
>>[0.044399578124284744, 0.9868999719619751]

Now we are going to predict from the model

my_number = x_test[5]
plt.imshow(my_number.reshape(28,28))
The image is for “one”
model.predict_classes(my_number.reshape(1,28,28,1))
>>array([1])

Great!! we are getting prediction as 1.

You can view my codes in my GitHub account, details are mentioned below.

So, that’s all about how to build a Convolutional Neural Network.

I hope you like this blog. Feel free to share your thoughts in the comment section and you can also connect with me.

Don’t forget to give us your 👏 !


Building a Convolutional Neural Network (CNN) Model for Image classification. was originally published in Becoming Human: Artificial Intelligence Magazine on Medium, where people are continuing the conversation by highlighting and responding to this story.