Project Goal
We will build a model that looks at a photo and says whether it shows a cat or a dog. This project uses everything you learned about CNNs: folders, augmentation, dropout and callbacks.
Step 1: Get the Data
Use the cats and dogs dataset from TensorFlow Datasets, or any folder with two subfolders named cats and dogs. Keep around 1000 images of each class to start.
text
dataset/
cats/ ...
dogs/ ...
Step 2: Create Datasets
python
import keras
from keras import layers
import tensorflow as tf
import numpy as np
IMG = (160, 160)
common = dict(validation_split=0.2, seed=42, image_size=IMG, batch_size=32, label_mode="binary")
train_ds = keras.utils.image_dataset_from_directory("dataset", subset="training", **common)
val_ds = keras.utils.image_dataset_from_directory("dataset", subset="validation", **common)
train_ds = train_ds.cache().shuffle(1000).prefetch(tf.data.AUTOTUNE)
val_ds = val_ds.cache().prefetch(tf.data.AUTOTUNE)
Step 3: Build the Model
python
model = keras.Sequential([
keras.Input(shape=(160, 160, 3)),
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
layers.Rescaling(1.0 / 255),
layers.Conv2D(32, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(128, 3, activation="relu"),
layers.MaxPooling2D(),
layers.GlobalAveragePooling2D(),
layers.Dropout(0.4),
layers.Dense(64, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
GlobalAveragePooling2D: Instead of flattening thousands of values, it averages each feature map into one number. This gives a much smaller model with less overfitting.
Step 4: Train with Callbacks
python
callbacks = [
keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True),
keras.callbacks.ModelCheckpoint("cats_dogs.keras", save_best_only=True),
]
history = model.fit(train_ds, validation_data=val_ds, epochs=30, callbacks=callbacks)
Step 5: Plot the Results
python
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history["accuracy"], label="train")
plt.plot(history.history["val_accuracy"], label="validation")
plt.title("Accuracy"); plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history["loss"], label="train")
plt.plot(history.history["val_loss"], label="validation")
plt.title("Loss"); plt.legend()
plt.show()
Step 6: Predict on Your Own Photo
python
img = keras.utils.load_img("my_pet.jpg", target_size=IMG)
arr = keras.utils.img_to_array(img)
arr = np.expand_dims(arr, 0) # add batch dimension: (1, 160, 160, 3)
score = float(model.predict(arr)[0][0])
label = "dog" if score > 0.5 else "cat"
print(f"{label} (confidence {max(score, 1 - score):.0%})")
Class order is alphabetical, so cats is 0 and dogs is 1. A score near 1 means dog.
What Accuracy to Expect
A small CNN trained from scratch on a couple of thousand images usually gets about 75 to 85 percent. To reach 95 percent or more, use transfer learning, which is the next lesson.
Conclusion
You completed a full image classification workflow, from folders to predictions. The main limit is the small amount of data, which transfer learning solves.
Quick Summary: Load folders, augment, build a CNN with GlobalAveragePooling, train with callbacks and predict on new photos.