Image Classification Using CNN

Share this post

The convolutional neural network is one of the most popular deep learning model for image classification. In this Blog, we are designing a CNN model to classify the Cat Vs Dog (weather image is lable is cat or dog)  using Tensorflow.  

This is a simple CNN Network
# Importing the libraries
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#data sugmentation
# Preprocessing the Training set
train_datagen = ImageDataGenerator(rescale=1./255,
                                rotation_range=40,
                                width_shift_range=0.2,
                                height_shift_range=0.2,
                                shear_range=0.2,
                                zoom_range=0.2,
                                horizontal_flip=True,
                                fill_mode='nearest')
training_set = train_datagen.flow_from_directory('image_data/training',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

Found 198 images belonging to 2 classes.

# Preprocessing the Test set
test_datagen = ImageDataGenerator(rescale = 1./255)
test_set = test_datagen.flow_from_directory('image_data/validation',
                                            target_size = (64, 64),
                                              batch_size = 32,
                                              class_mode = 'binary')

Found 100 images belonging to 2 classes.

## showing some image from training
import matplotlib.pyplot as plt
def plotImages(images_arr):
    fig, axes = plt.subplots(1, 5, figsize=(20, 20))
    axes = axes.flatten()
    for img, ax in zip(images_arr, axes):
        ax.imshow(img)
    plt.tight_layout()
    plt.show()
images = [training_set[0][0][0] for i in range(5)]
plotImages(images)

Model Build Use Only CNN

from tensorflow.keras.layers import Conv2D
# Part 2 - Building the CNN
# Initialising the CNN
cnn = tf.keras.models.Sequential()
# Step 1 - # Adding a first convolutional layer
cnn.add(tf.keras.layers.Conv2D(filters=32,padding="same",kernel_size=3, activation='relu',
## step 2 - #apply maxpool
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) ## Apply pooing stride
# Adding a second convolutional layer
cnn.add(tf.keras.layers.Conv2D(filters=32,padding='same',kernel_size=3, activation='relu'))
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
# Step 3 - Flattening
cnn.add(tf.keras.layers.Flatten())
# Step 4 - Full Connection
cnn.add(tf.keras.layers.Dense(units=128, activation='relu'))
tf.keras.layers.Dropout(0.5)
# Step 5 - Output Layer
cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
# Part 3 - Training the CNN
# Compiling the CNN
cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Training the CNN on the Training set and evaluating it on the Test set
history = cnn.fit(x = training_set, validation_data = test_set, epochs = 2)

Save And Load Model

#save model
from tensorflow.keras.models import load_model
cnn.save('model.h5')
from tensorflow.keras.models import load_model
# load model
model = load_model('model.h5')
# Part 4 - Making a single prediction
import numpy as np
from tensorflow.keras.preprocessing import image
test_image = image.load_img('image_data/test/3285.jpg', target_size = (64,64))
test_image = image.img_to_array(test_image)
test_image=test_image/255
test_image = np.expand_dims(test_image, axis = 0)
result = cnn.predict(test_image)
result

array([[0.5059088]], dtype=float32)

if result[0]<=0.5:
    print("The image classified is cat")
else:
    print("The image classified is dog")
from IPython.display import Image
Image(filename='image_data/test/3285.jpg',height='200',width='200')

The image classified is dog

Model Predicted image

Share this post

8 thoughts on “Image Classification Using CNN”

  1. Hello There. I found your blog using msn.
    This is an extremely well written article.
    I will be sure to bookmark it and return to read more of your useful information. Thanks
    for the post. I will certainly return.

  2. you are truly a just right webmaster. The site loading velocity is incredible.
    It kind of feels that you’re doing any unique
    trick. Moreover, The contents are masterpiece.
    you’ve performed a excellent process in this subject!

  3. You are so interesting! I do not believe I’ve read through something like this before.

    So good to find someone with some original thoughts on this topic.
    Really.. thanks for starting this up. This website is something
    that is required on the internet, someone with some originality!

  4. Greetings! This is my first visit to your blog! We are a group of volunteers and starting a
    new project in a community in the same niche.
    Your blog provided us valuable information to work on. You
    have done a marvellous job!

  5. I absolutely love your blog and find the majority of your post’s to be precisely
    what I’m looking for. Does one offer guest writers to write content
    for yourself? I wouldn’t mind publishing a post or elaborating on some
    of the subjects you write concerning here. Again, awesome web site!

Leave a Comment

Your email address will not be published. Required fields are marked *