More Deep Learning Projects…

Project 12: Classifying Dogs and Cats with Deep Learning

Convolutional neural networks (CNNs) are mainly used to classify images or to find similarities in patterns between them.

A convolutional network therefore receives an ordinary color image as a rectangular box whose width and height are measured by the number of pixels along those dimensions, and whose depth is three layers, one for each letter in RGB.

As images move through a convolutional network, different patterns are recognized, just as in an ordinary neural network.

But here, instead of focusing on one pixel at a time, the convolutional network takes square patches of pixels and passes them through a filter.

This filter is also a square matrix, smaller than the image itself, and its size equals the patch. It is also called a kernel.

Let's now start by importing the libraries

 

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, Conv2D

We need to train a model first, so to check the training data, in the code below we loop through all the images in the training folder and then split the image name using the delimiter “.”

We have names such as dog.0, dog.1, cat.2 and so on. So after splitting, we will get results such as ” dog” and ” cat” as the class value of the image. To make this example easier, we will treat a dog as “1” and a cat as “0”.

Now each image is really a collection of pixels, so how do we make our computer know that? It is simple: it converts all those pixels into an array.

So here we will use the cv2 library to read our image into an array, and it will also be read as a grayscale image.

train_dir = # your path to train dataset
path = os.path.join(main_dir,train_dir)

for p in os.listdir(path):
    category = p.split(".")[0]
    img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)
    new_img_array = cv2.resize(img_array, dsize=(80, 80))
    plt.imshow(new_img_array,cmap="gray")
    break

OK, the code above was more for understanding the purpose. Now we get to the real programming part.

Declare your training set X and your target array y. Here X will be a collection of pixels and y will be the value 0 or 1 to indicate a dog or a cat. Write a conversion function that maps the class ” dog” or ” cat” to 1 and 0.

Create a function create_test_data that takes all the training images in a loop. It converts each into an image array. Resize the image to 80 × 80. Add the image to the X array, and add the class value to the y array.

X = []
y = []
convert = lambda category: int(category == 'dog')
def create_test_data(path):
    for p in os.listdir(path):
        category = p.split(".")[0]
        category = convert(category)
        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)
        new_img_array = cv2.resize(img_array, dsize=(80, 80))
        X.append(new_img_array)
        y.append(category)

Now call the function, but also convert X and y into numpy arrays afterwards, and we also need to reshape X with the code below:

create_test_data(path)
X = np.array(X).reshape(-1, 80,80,1)
y = np.array(y)

If you look at the values of X, you can see a wide range of values between 0 and 255. That is because each pixel has a different intensity of white and black. But with such a wide range of values, it becomes hard for the training model to learn (and it sometimes memorizes instead).

How do you solve this? You guessed it right. You can normalize the data. We could use Keras normalization here as well. But we know well that all the values range between 0 and 255, so we can simply divide them by 255 and get all the values scaled between 0 and 1.

That is what we did below. You can skip this step to see the difference in accuracy. Don't believe everything I say. Try it and see for yourself:

#Normalize data
X = X/255.0

Training the model

model = Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(Conv2D(64,(3,3), activation = 'relu', input_shape = X.shape[1:]))
model.add(MaxPooling2D(pool_size = (2,2)))
# Add another:
model.add(Conv2D(64,(3,3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(Dense(1, activation='sigmoid'))

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

Now we will fit our model to the training data.

Epochs: how many times our model will pass through the data.

Batch size: how much data you want to pass through the model in one go.

Validation_split: how much of the data (20% in this case) you will need to check the validation error.

model.fit(X, y, epochs=10, batch_size=32, validation_split=0.2)

It is now finally time to PREDICT, so feed your CNN model the test data for prediction.

predictions = model.predict(X_test)

We round the result here because we used a sigmoid function and obtained probability values in our predicted dataset:

predicted_val = [int(round(p[0])) for p in predictions]

Now you need to build a submission data frame to submit your set of results.

submission_df = pd.DataFrame({'id':id_line, 'label':predicted_val})

Write your data frame to a csv file:

submission_df.to_csv("submission.csv", index=False)

Post links

One comment

Leave a comment

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