DAY 99-100 DAYS MLCODE: Cat Vs Dog Classification

My Tech World

DAY 99-100 DAYS MLCODE: Cat Vs Dog Classification

February 19, 2019 100-Days-Of-ML-Code blog 0

In the previous blog, we discussed emotion detection using Keras, in this blog, we’ll develop Cat Vs Dog classification problem.

We are going to use the test data from Kaggle website. Kaggle has Dog-Vs-Cat challenge. Let’s start by downloading the data from Kaggle website.

!kaggle competitions download -c dogs-vs-cats

Now, we can extract the data and store into test and train folder, also create a folder models to store the model and val to have validation data.

#prepare directory
!mkdir data
!cd data/
!mv train.zip data/
!mv test1.zip data/
!mkdir models
!mkdir val

Now, prepare the training data by resizing the image to 100 using CV2 and store into list.

IMG_SIZE = 100
training_data = []

def create_training_data():

t_path = os.path.join(PATH, ‘train’) # create path to dogs and cats
class_num = ” # get the classification (0 or a 1). 0=dog 1=cat

for img in tqdm(os.listdir(t_path)): # iterate over each image per dogs and cats
try:
img_array = cv2.imread(os.path.join(t_path,img) ,cv2.IMREAD_GRAYSCALE) # convert to array
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize to normalize data size
if ‘dog’ in img :
class_num = 0
else:
class_num = 1
training_data.append([new_array, class_num]) # add this to our training_data
except Exception as e: # in the interest in keeping the output clean…
pass
#except OSError as e:
# print(“OSErrroBad img most likely”, e, os.path.join(path,img))
#except Exception as e:
# print(“general exception”, e, os.path.join(path,img))

create_training_data()

print(len(training_data))

100%|██████████| 25000/25000 [00:27<00:00, 901.88it/s]

Let’s save this data, so that we don’t need to keep calculating it every time we want to play with the neural network model

import pickle

pickle_out = open(“X.pickle”,”wb”)
pickle.dump(X, pickle_out)
pickle_out.close()

pickle_out = open(“y.pickle”,”wb”)
pickle.dump(y, pickle_out)
pickle_out.close()

Construct Model

Our model will have three layers and user Adam as optimizer and Sigmoid as activation function.

# Create a Model
model = Sequential()
# Add layer
model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))

# 2nd Layer
model.add(Conv2D(256, (3, 3)))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors

#3rd
model.add(Dense(64))

model.add(Dense(1))
model.add(Activation(‘sigmoid’))

model.compile(loss=’binary_crossentropy’,
optimizer=’adam’,
metrics=[‘accuracy’])

model.fit(X, y, batch_size=32, epochs=100, validation_split=0.3)

This training will take long time, so we’ll come back tomorrow and test our model. Just before closing the code, let’s save our trained model weights.

#Save the modesl
# define the checkpoint
filepath = “modelcat.h5”
model.save(filepath)

In conclusion, we have developed a model of dog-vs-cat problem and saved the model with name modelcat.h5. In the next blog, we’ll test our model. You can find the code here.