Cat & Dog Classifier¶

Import Libraries¶

In [1]:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense,  Dropout
from tensorflow.keras.preprocessing import image
from tensorflow.keras.callbacks import EarlyStopping

import warnings

warnings.filterwarnings('ignore')

Import Photos Using ImageDataGenerator¶

In [2]:
batch_size = 16

image_size = (150, 150)

train_datagen = ImageDataGenerator(
    rescale=1./255,
    zoom_range=0.2,
    rotation_range=15,
    width_shift_range=0.05,
    height_shift_range=0.05)

train_generator = train_datagen.flow_from_directory(
        'photos',
        target_size=image_size, 
        batch_size=batch_size,
        class_mode='binary')
Found 697 images belonging to 2 classes.

Design, Compile and Fit Model¶

In [3]:
model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
    MaxPooling2D(2, 2),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Conv2D(128, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Conv2D(128, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Flatten(),
    Dense(512, activation='relu'),
    Dropout(0.3),
    Dense(1, activation='sigmoid')
])
In [4]:
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
In [5]:
early_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1, restore_best_weights=True)
In [6]:
model.fit(
    train_generator,
    epochs=50,
    callbacks=[early_stopping],
    verbose = 0)
Out[6]:
<keras.src.callbacks.history.History at 0x106414710>

Function To Use Model to Classify New Image¶

In [7]:
def classify_pet(img_path):
    img = image.load_img(img_path, target_size=(150, 150))
    plt.imshow(img)
    plt.axis('off')
    plt.show()

    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)
    prediction = model.predict(img_array)
    if prediction < 0.5:
        print("It's a cat!")
    else:
        print("It's a dog!")
In [8]:
classify_pet('predict/dog1.jpg')
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 79ms/step
It's a dog!
In [18]:
classify_pet('predict/cat1.jpg')
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 17ms/step
It's a cat!