This is a classic cats vs dogs classification using Keras. You can use this starter code for any kind of binary classification and get started in mere minutes.

In this example I have used cats vs dogs dataset from Kaggle. It has 10000 total images with 80-20 split. It is a pretty light download so suitable for quickly getting up and running with Keras.

Before we start, I assume that you have downloaded the dataset and installed all the needed libraries. The most hassle-free approach would be to open an account on Kaggle.com because a kaggle ‘kernel’ (aka virtual environment) comes with all the things we’ll need pre-installed. If you want to setup and work on you own computer, you should follow this article to setup an environment using Anaconda Navigator.

Loading the dataset

At first we declare our train and test dataset directories

test_dir="/kaggle/input/dog vs cat/dataset/test_set"
train_dir="/kaggle/input/dog vs cat/dataset/training_set"

We now load the images with built in ImageDataGenerator method which is awesome for loading images easily.

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255)

test_datagen = ImageDataGenerator(rescale = 1./255)

batch_size=64

training_set = train_datagen.flow_from_directory(train_dir,
target_size = (100, 100),
batch_size = batch_size,
color_mode='rgb',
class_mode = 'binary',
shuffle=True)

test_set = test_datagen.flow_from_directory(test_dir,
target_size = (100, 100),
batch_size = batch_size,
color_mode='rgb',
class_mode = 'binary')

Building The Model

Before we can build the model, we need to do some necessary imports. The convention is to import everything at the top, but I find it convenient to import things as I go along in a notebook setting.

import keras
from keras.models import Sequential
from keras.layers import Conv2D, Activation, MaxPooling2D, Flatten, Dense
from keras.optimizers import adam
import numpy as np

We now build the model. We are going to use multiple layers here.

classifier = Sequential()

classifier.add(Conv2D(32, (3, 3), input_shape = (100, 100, 3)))
classifier.add(Activation("relu"))
classifier.add(MaxPooling2D(pool_size = (3, 3)))
classifier.add(Conv2D(64, (3, 3), input_shape = (100, 100, 3)))
classifier.add(Activation("relu"))
classifier.add(MaxPooling2D(pool_size = (3, 3)))

classifier.add(Flatten())

classifier.add(Dense(64))
classifier.add(Activation("relu")) 
classifier.add(Dense(128))
classifier.add(Activation("relu")) 
classifier.add(Dense(activation = 'sigmoid', units=1))

We compile the model using ‘adam’ as an optimizer and ‘binary_crossentropy’ as loss function.

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

We now use fit_generator method to train the network

classifier.fit_generator(training_set, steps_per_epoch=np.ceil(training_set.samples / batch_size), epochs=6, validation_steps=np.ceil(test_set.samples / batch_size), validation_data=test_set)

Evaluating The Model

We now feed the network an image and see if it can predict correctly what the image is. Change test_image to see result on different images.

import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
test_image = image.load_img("/kaggle/input/dog vs cat/dataset/training_set/dogs/dog.1056.jpg", target_size = (100, 100)) 
plt.imshow(test_image)
plt.grid(None) 
plt.show()
res_list= ["It's a cat !","It's a dog !"]
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
print(res_list[int(classifier.predict(test_image))])

That’s it ! See the full code in my github. Also while copy pasting, beware of the indentations because python will punish you for wrong indentation ! Thank you for reading the article. Be sure to comment if you face any trouble !