Dog Breed Classification with TensorFlow, Step by Step
A step-by-step tutorial and practical reference for building an image classifier with TensorFlow, TensorFlow Hub, and transfer learning.
What you'll build
A machine learning model that takes a photograph of a dog and predicts which of 120 dog breeds it most likely belongs to.
By the end, you'll be able to:
- Understand a multiclass image classification problem.
- Explore a real-world image dataset.
- Prepare images and labels for machine learning.
- Build an efficient TensorFlow data pipeline.
- Apply transfer learning with a pretrained MobileNet V2.
- Train and monitor a model with TensorBoard and early stopping.
- Evaluate predictions and investigate mistakes.
- Save and reload trained models.
- Generate predictions for Kaggle test images and your own photographs.
- Prepare a CSV submission for a machine learning competition.
Who is this for? Beginners who know basic Python and want a practical introduction to machine learning through a complete project.
Roadmap
| Part | Focus |
|---|---|
| 1 | Understand the problem and prepare the environment |
| 2 | Explore and prepare the dataset |
| 3 | Build the image data pipeline |
| 4 | Build and train the model |
| 5 | Evaluate and understand predictions |
| 6 | Save, scale, and use the model |
| 7 | Quick reference and troubleshooting |
Part 1 — Understand the problem and prepare the environment
Step 1: Define the problem
You take a photograph of a dog in a park. You want a computer to predict whether it's a Golden Retriever, German Shepherd, Beagle, or another breed.
This is an image classification problem: the input is an image, the output is a category. Because there are 120 possible categories, it's a multiclass classification problem.
The model learns from labeled examples. During training, it sees dog images alongside their correct breed names and adjusts its trainable parameters to reduce prediction error.
Step 2: Understand the dataset
We'll use the Kaggle Dog Breed Identification dataset.
| Component | Purpose |
|---|---|
labels.csv |
Maps each training image ID to its breed |
train/ |
Dog photographs used for learning |
test/ |
Photographs for which we must predict breeds |
sample_submission.csv |
Shows the required submission structure |
Download: https://www.kaggle.com/competitions/dog-breed-identification/data (free Kaggle account required). Step 5 explains where to place the ZIP.
The dataset contains approximately 10,222 training images, 10,357 test images, and 120 breeds.
Important distinction: Training labels tell the model the correct answers. Test images have no labels, so predictions can't be evaluated directly unless true labels are available separately.
Step 3: Define the evaluation metric
The Kaggle competition uses categorical cross-entropy (log loss).
The model doesn't return a single breed. It returns a probability for each of the 120 breeds, and those probabilities must sum to 1.
For a single image, a prediction might look like:
| Breed | Predicted probability |
|---|---|
| Beagle | 0.70 |
| Basset Hound | 0.15 |
| Bloodhound | 0.08 |
| Other 117 breeds | 0.07 combined |
Log loss measures how well those probabilities align with the correct class. A confident correct prediction scores better than a confident incorrect prediction.
- Lower log loss is better.
- Accuracy is also useful during training because it's more intuitive, but it doesn't capture confidence calibration the way log loss does.
- We'll use categorical cross-entropy as the loss and accuracy as a training metric.
Step 4: Identify features and target
Following the usual convention:
- Input
X: dog image file paths (eventually image tensors) - Target
y: the correct breed, one-hot encoded - Number of classes: 120
- Input shape:
(224, 224, 3)after preprocessing - Output shape: 120 probabilities per image
Images are unstructured data. Unlike a spreadsheet row, an image doesn't arrive as neatly labeled columns — we must convert its pixels into numerical arrays the model can process.
Step 5: Set up Google Colab
We'll use Google Colab to run Python code, access a GPU when available, and connect Google Drive for the dataset. We'll keep the dataset ZIP on Drive and extract it into Colab's local /content/ folder, which is much faster to read from during training.
Mount Google Drive:
from google.colab import drive
drive.mount("/content/drive")Download the dataset (if you don't have it yet):
Download link: https://www.kaggle.com/competitions/dog-breed-identification/data
A free Kaggle account is required. Download
dog-breed-identification.zipand place it in your Google Drive, e.g. underMyDrive/Colab Notebooks/.
Extract the dataset to Colab's local filesystem:
import os, time
# ZIP lives on Drive (persists across sessions)
zip_path = "/content/drive/MyDrive/Colab Notebooks/dog-breed-identification.zip"
# Extract to local /content/ (fast, temporary)
dataset_dir = "/content/dog-breed-identification"
print("Extracting dataset...")
start = time.time()
!unzip -o -q "$zip_path" -d "/content/dog-breed-identification"
elapsed = time.time() - start
train_count = len(os.listdir(os.path.join(dataset_dir, "train")))
test_count = len(os.listdir(os.path.join(dataset_dir, "test")))
print(f"Done in {elapsed:.1f}s")
print(f"Train images: {train_count}")
print(f"Test images: {test_count}")The -o flag overwrites existing files without prompting, and -q suppresses per-file output so the notebook stays readable. Image counts are printed at the end as a sanity check — you should see roughly 10,222 training and 10,357 test images.
Note: The
zip_pathmust match wherever you actually uploaded the ZIP in your Drive. The default shown here isMyDrive/Colab Notebooks/dog-breed-identification.zip. If you placed it elsewhere, changezip_pathaccordingly.
Why extract locally instead of into Drive?
| Location | Speed | Persistence | Recommendation |
|---|---|---|---|
| Google Drive | Slow (syncs every file) | Survives runtime reset | Store the ZIP here |
Colab /content/ |
Fast (local disk) | Lost on runtime reset | Extract here |
The ZIP stays on Drive, so you only download it once. Extraction happens into /content/, a normal local directory — fast to read from, which matters because the training pipeline reads every image many times.
Note: If the runtime resets, re-run the extraction cell. Because it uses
-o, it overwrites existing files without prompting and takes only a few seconds — no need to re-download from Kaggle.
Expected directory structure:
/content/dog-breed-identification/
├── labels.csv
├── sample_submission.csv
├── train/
│ ├── image_id_1.jpg
│ ├── image_id_2.jpg
│ └── ...
└── test/
├── test_image_1.jpg
├── test_image_2.jpg
└── ...
The actual image IDs are long hex strings, not image_id_1.
Step 6: Install and import libraries
We'll use TensorFlow for deep learning and TensorFlow Hub to load the pretrained model.
!pip install tf_kerasImport the libraries:
import os
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_hub as hub
import tf_keras
from sklearn.model_selection import train_test_split
from IPython.display import Image, displayWhy do we need these libraries?
| Library | Purpose |
|---|---|
| TensorFlow | Image processing, tensors, datasets and model inference. |
| TensorFlow Hub | Loads the pretrained MobileNet V2 model |
tf_keras |
Provides the Keras API used to construct and train the model |
| NumPy | Numerical operations on arrays |
| Pandas | Reads and explores labels.csv |
| Matplotlib | Visualizes images, class distributions and predictions |
| Scikit-learn | Splits the dataset into training and validation sets |
os |
Works with directories and file paths |
Check your environment:
print("TensorFlow:", tf.__version__)
print("TensorFlow Hub:", hub.__version__)
print("tf_keras:", tf_keras.__version__)
print(
"GPU available!"
if tf.config.list_physical_devices("GPU")
else "GPU not available."
)If Colab reports that no GPU is available, you can enable one through Runtime → Change runtime type → T4 GPU when that option is available
Checkpoint: You should be able to import all libraries and see the TensorFlow version. If you hit a compatibility error between TensorFlow, Keras, and TensorFlow Hub, resolve it before continuing.
Part 2 — Explore and prepare the dataset
Step 7: Load the labels
Before training a model, we need to understand the information available to us
The labels.csv file maps each image ID to its correct breed.
Load it with Pandas:
# Same path set in Step 5 — repeated here so this section is self-contained
dataset_dir = "/content/dog-breed-identification"
labels_csv = pd.read_csv(
os.path.join(dataset_dir, "labels.csv")
)Explore the data:
# Column types, non-null counts, memory usage
labels_csv.info()
# First five rows
labels_csv.head()A typical row looks like this:
| id | breed |
|---|---|
image_id_1 |
beagle |
image_id_2 |
golden_retriever |
image_id_3 |
german_shepherd |
These IDs are illustrative; your CSV contains the real identifiers.
Why start with labels? They tell us what the model needs to learn, and they help us verify that each image is associated with the correct answer.
Note:
labels_csv.describe()is not very useful here because both columns are strings.info()gives you the counts and types you actually need.
Step 8: Examine breed distribution
A dataset may contain different numbers of images for different classes. This matters because a model can find it harder to learn classes with fewer examples.
Count the images per breed:
breed_counts = labels_csv["breed"].value_counts()
breed_counts.plot.bar(
figsize=(20, 10),
title="Number of Images per Breed"
)
plt.show()Calculate the median number of images per breed:
breed_counts.median()The median is the middle value when the breed counts are sorted. It provides a useful indication of how many examples a typical breed has.
What to look for: Are the class counts reasonably similar, or are some breeds underrepresented? The chart helps you spot possible class imbalance before training.
Step 9: Display a sample image
Connect a label to its actual image:
image_id = labels_csv.iloc[0]["id"]
image_path = os.path.join(
dataset_dir,
"train",
f"{image_id}.jpg"
)
display(Image(filename=image_path))
labels_csv.iloc[0]This displays the first image and its corresponding label.
Why this matters: A correct-looking CSV isn't enough. We need to verify that paths point to real files and that images match their labels.
Step 10: Create file paths for all training images
The CSV contains image IDs, not full paths. We'll convert each ID into the corresponding file path.
filenames = [
os.path.join(dataset_dir, "train", f"{image_id}.jpg")
for image_id in labels_csv["id"]
]
filenames[:10]For example, an ID such as abc123 becomes:
.../dog-breed-identification/train/abc123.jpgDefine the training directory and check the files:
train_dir = os.path.join(dataset_dir, "train")
print("Files in train directory:", len(os.listdir(train_dir)))
print("Paths created:", len(filenames))Check whether the counts match:
if len(os.listdir(train_dir)) == len(filenames):
print("Number of image files matches number of filenames.")
else:
print("Number of image files does not match number of filenames.")This is a useful first check, but matching counts alone doesn't guarantee that every path is valid. A stronger check is:
missing_files = [
path for path in filenames
if not os.path.isfile(path)
]
print("Missing files:", len(missing_files))If there are missing files, investigate the dataset extraction and directory paths before training.
Step 11: Create the label array
Next, extract the breed names.
labels = labels_csv["breed"].to_numpy()
print(labels[:10])
print("Number of labels:", len(labels))Check that every image has a corresponding label:
assert len(filenames) == len(labels)
print("Every image path has a corresponding label.")The order matters: filenames[i] must correspond to labels[i].
Step 12: Find all unique breeds
The model needs to know which categories it can predict.
unique_breeds = np.unique(labels)
print("Number of unique breeds:", len(unique_breeds))
print(unique_breeds)For this dataset, the expected number of unique breeds is 120.
We now have a list that defines our classes. The position of each breed in this list will determine the position of its probability in the model's output.
For example if unique_breeds[15] is "beagle", output index 15 is the Beagle class.
Keep this mapping consistent when training, saving, and using the model.
Step 13: Convert breeds to one-hot encoding
Machine learning models operate on numerical representations. We need to turn each breed label into a form the model can learn from.
One approach is one-hot encoding. Suppose we have only five breeds:
["beagle", "boxer", "bulldog", "collie", "poodle"]If a dog belongs to "bulldog" , its one-hot representation is:
[0, 0, 1, 0, 0]
The correct class is represented by 1, all other classes are represented by 0.
Let's see how this works with our data.
# Compare the first label against every unique breed
print(labels[0])
print(labels[0] == unique_breeds)The comparison returns a Boolean array containing True at the correct class position.
Convert all labels:
boolean_labels = np.array([
label == unique_breeds
for label in labels
])
print("Label array shape:", boolean_labels.shape)For the full dataset, the expected shape is:
(number_of_images, 120)Each row contains 120 values, one for every breed.
Understand how the encoding works
# Find the index of the first dog's breed
class_index = np.where(unique_breeds == labels[0])[0][0]
# Find the index of True in the encoded label
encoded_index = boolean_labels[0].argmax()
print("Class index:", class_index)
print("Encoded index:", encoded_index)
print(boolean_labels[0].astype(int))What each operation does:
np.where()finds the position of a breed in the class list..argmax()finds the position of the largest value (the singleTrue)..astype(int)convertsTrue/Falseto1/0.
Checkpoint: Every row should have exactly one
1. Categorical cross-entropy relies on this.
Step 14: Define features and target
Now we can organize the data using the conventional machine learning names X and y.
X = filenames # Image file paths
y = boolean_labels # One-hot encoded labelsAt this point, X is still paths — we'll turn them into image tensors in Part 3.
Step 15: Create a training/validation split
We need a way to measure whether the model can classify images it hasn't seen during training.
The original Kaggle training dataset doesn't provide a separate validation set, so we'll create one.
For initial experiments, let's use 1,000 images:
NUM_IMAGES = 1000
X_small = X[:NUM_IMAGES]
y_small = y[:NUM_IMAGES]
X_train, X_val, y_train, y_val = train_test_split(
X_small,
y_small,
test_size=0.2,
random_state=42
)| Set | Size | Purpose |
|---|---|---|
| Training | 800 | Update model weights |
| Validation | 200 | Monitor performance on held-out images |
Verify the split:
print("Training images:", len(X_train))
print("Training labels:", len(y_train))
print("Validation images:", len(X_val))
print("Validation labels:", len(y_val))The random_state=42 parameter makes the split reproducible, so you can repeat the experiment with the same partition.
One consideration: taking the first 1,000 rows is convenient for experimentation, but those rows may not represent every breed equally. For more reliable experiments, consider a stratified split using breed IDs, particularly when working with imbalanced data.
Why not train on all images immediately?
Smaller experiments help us detect code and data problems quickly. Once the complete workflow works, we can increase the dataset size.
Part 3 — Build the image data pipeline
Step 16: Understand images as numerical tensors
A computer vision model doesn't receive an image as a human-readable photograph. It processes numerical pixel values.
An RGB image can be represented as a three-dimensional array:
The three channels are red, green, and blue.
Load a sample image:
from matplotlib.pyplot import imread
image = imread(filenames[0])
print(image.shape)The result might resemble:
(375, 500, 3)The exact height and width depend on the original photograph.
Convert it to a TensorFlow tensor:
image_tensor = tf.constant(image)
print(image_tensor.shape)
print(image_tensor.dtype)A tensor is a multidimensional array of numerical values. TensorFlow uses tensors to represent image pixels, labels, intermediate calculations, and model outputs.
Step 17: Define a consistent image size
The photographs in a dataset can have different dimensions. However, our model expects a consistent input shape.
We'll resize every image to 224 × 224 pixels.
IMG_SIZE = 224Target shape: (224, 224, 3) — 224 pixels high, 224 wide, and three color channels. This matches MobileNet V2's expected input dimensions.
Step 18: Create an image preprocessing function
The preprocessing function will:
- Read the image file.
- Decode its JPEG contents into RGB pixels.
- Normalize pixel values.
- Resize the image.
- Return the processed tensor.
def preprocess_image(image_path):
"""
Read an image file and return a preprocessed image tensor.
"""
# Read the file as raw bytes
raw = tf.io.read_file(image_path)
# Decode JPEG bytes into RGB pixel values
image = tf.image.decode_jpeg(
raw,
channels=3
)
# Convert pixels to float values in the 0–1 range
image = tf.image.convert_image_dtype(
image,
tf.float32
)
# Resize to the model's required dimensions
image = tf.image.resize(
image,
size=[IMG_SIZE, IMG_SIZE]
)
return imageUnderstand each operation
| Operation | Purpose |
|---|---|
tf.io.read_file() |
Reads raw file bytes |
tf.image.decode_jpeg() |
Converts JPEG bytes into numerical pixel values |
tf.image.convert_image_dtype() |
Converts to float and scales 0–255 to 0–1 |
tf.image.resize() |
Resizes to 224 × 224 |
Why normalize the pixels? Integer pixel values 0–255 become floats 0–1 (e.g. 128 / 255 ≈ 0.502). This gives the model a consistent, smaller numerical range.
Why resize? The model expects a fixed input size regardless of the original photograph's dimensions.
Note on preprocessing for this specific model: This TF Hub variant of MobileNet V2 expects inputs in
[0, 1], whichconvert_image_dtypegives you. If you swap in a different pretrained model that expects[-1, 1](many do), you won't get an error — you'll silently get poor predictions. Always check the pretrained model's input requirements.
Test it:
sample_image = preprocess_image(
tf.constant(filenames[0])
)
print(sample_image.shape) # (224, 224, 3)
print(sample_image.dtype) # <dtype: 'float32'>Step 19: Create image-label pairs
The model must receive an image and its correct label together.
We'll create a helper function that combines preprocessing with label pairing.
def get_image_label(image_path, label):
"""
Preprocess an image and return it with its label.
"""
image = preprocess_image(image_path)
return image, labelTest it:
sample_image, sample_label = get_image_label(
tf.constant(X_train[0]),
tf.constant(y_train[0])
)
print("Image shape:", sample_image.shape) # (224, 224, 3)
print("Label shape:", sample_label.shape) # (120,)Step 20: Understand batching
Instead of processing the whole dataset at once, we process small groups called batches.
We'll use a batch size of 32.
BATCH_SIZE = 32For 800 training images: 800 / 32 = 25 batches.
For 200 validation images: 6 full batches + 1 batch of 8.
Batching controls memory use and gives the model data in manageable chunks.
Step 21: Build the TensorFlow dataset pipeline
TensorFlow's tf.data.Dataset API lets us build a pipeline for loading, preprocessing, shuffling, and batching data.
We'll create a function that supports three scenarios:
- Training data, with labels and shuffling.
- Validation data, with labels but without shuffling.
- Test data, without labels.
def create_data_batches(
X,
y=None,
batch_size=BATCH_SIZE,
valid_data=False,
test_data=False
):
"""
Create batches of preprocessed images and labels.
Training: shuffle examples.
Validation: preserve example order.
Test: process images without labels.
"""
# Test data has no labels
if test_data:
print("Creating test data batches...")
data = tf.data.Dataset.from_tensor_slices(
tf.constant(X)
)
data = data.map(preprocess_image)
data = data.batch(batch_size)
return data
# Validation data is not shuffled
elif valid_data:
print("Creating validation data batches...")
data = tf.data.Dataset.from_tensor_slices(
(tf.constant(X), tf.constant(y))
)
data = data.map(get_image_label)
data = data.batch(batch_size)
return data
# Training data is shuffled
else:
print("Creating training data batches...")
data = tf.data.Dataset.from_tensor_slices(
(tf.constant(X), tf.constant(y))
)
# Shuffle image paths and labels together
# Seeded so results are reproducible across runs.
data = data.shuffle(buffer_size=len(X), seed=42)
# Preprocess each image
data = data.map(get_image_label)
# Group examples into batches
data = data.batch(batch_size)
return dataEach operation:
| Operation | What it does |
|---|---|
from_tensor_slices() |
Creates a dataset of individual examples |
shuffle() |
Randomizes order (training only), keeping image-label pairs together |
map() |
Applies preprocessing to each example |
batch() |
Groups examples into batches |
Datasets are processed lazily: images are loaded as the pipeline consumes them rather than all at once.
Step 22: Create training and validation datasets
Now use the function:
train_data = create_data_batches(
X_train,
y_train
)
valid_data = create_data_batches(
X_val,
y_val,
valid_data=True
)Inspect the dataset structures:
print(train_data.element_spec)
print(valid_data.element_spec)Expected:
- Images:
(None, 224, 224, 3) - Labels:
(None, 120)
Here, None is the batch dimension. The batch may contain fewer than 32 images, such as the final validation batch of 8.
Checkpoint: Image and label shapes should match the expected forms. If they don't, investigate
preprocess_imageand the one-hot encoding.
Step 23: Visualize a batch of images
Before training, it's useful to see whether the pipeline produces sensible images and labels.
Create a helper function to display 25 images:
def show_25_images(images, labels):
"""
Display 25 images with their corresponding breed labels.
"""
plt.figure(figsize=(10, 10))
for i in range(25):
ax = plt.subplot(5, 5, i + 1)
plt.imshow(images[i])
plt.axis("off")
breed_index = labels[i].argmax()
plt.title(unique_breeds[breed_index])
plt.tight_layout()
plt.show()Retrieve the first training batch:
train_images, train_labels = next(
train_data.as_numpy_iterator()
)
show_25_images(train_images, train_labels)Notice the difference:
- Training images are shuffled.
- Validation images remain in a consistent order.
The visualization function uses labels[i].argmax() to locate the 1 in each one-hot vector; that index is then used to retrieve the corresponding breed name.
Checkpoint: Images should display correctly, and titles should match the breeds you see. If not, the image-label mapping is broken somewhere in Step 10 or 11.
Part 4 — Build and train the model
Step 24: Understand transfer learning
Training a deep network from scratch means teaching it to recognize edges, textures, shapes, and structure — from millions of examples.
Transfer learning reuses a model that has already learned those patterns on a large dataset, then adapts it to a new task.
The pretrained model already recognizes:
- Edges and lines
- Shapes and textures
- Fur patterns and facial structure
- Higher-level visual concepts
We keep that knowledge and add a new output layer for our 120 breeds.
Step 25: Choose a pretrained model
We'll use MobileNet V2 from TensorFlow Hub.
- Designed for efficient image recognition
- Accepts 224 × 224 images
- Produces 1,001 outputs (1,000 ImageNet classes + 1 background class)
- Pretrained on over a million images
We'll use its output as input to a new layer that predicts 120 breeds.
Step 26: Define model configuration
Let's define three variables:
# Image input: batch, height, width, RGB channels
INPUT_SHAPE = [None, IMG_SIZE, IMG_SIZE, 3]
# Number of dog breeds
OUTPUT_SHAPE = len(unique_breeds)
# Pretrained model
MODEL_URL = (
"https://www.kaggle.com/models/google/"
"mobilenet-v2/TensorFlow2/130-224-classification/2"
)Understand each variable:
INPUT_SHAPE: Defines the expected image tensor dimensions.None: Allows different batch sizes.OUTPUT_SHAPE: Gives us 120 output classes.MODEL_URL: Identifies the pretrained model to load.
Step 27: Build the model
We'll use a sequential model consisting of two main layers:
- A pretrained MobileNet V2 model.
- A new Dense layer with 120 outputs.
def create_model(
input_shape=INPUT_SHAPE,
output_shape=OUTPUT_SHAPE,
model_url=MODEL_URL
):
print("Building model with:", model_url)
model = tf_keras.Sequential([
hub.KerasLayer(model_url, trainable=False),
tf_keras.layers.Dense(
units=output_shape,
activation="softmax"
)
])
model.compile(
loss=tf_keras.losses.CategoricalCrossentropy(),
optimizer=tf_keras.optimizers.Adam(),
metrics=["accuracy"]
)
model.build(input_shape)
return modelUnderstand Layer 1: MobileNet V2
hub.KerasLayer(model_url, trainable=False)This loads the pretrained model.
The parameter trainable=False freezes the pretrained model's weights. During training, these weights remain unchanged.
Why freeze them?
- Preserves the pretrained model's learned representations.
- Reduces the number of parameters that need updating.
- Training is generally faster than updating the entire pretrained network.
Only the newly added Dense layer needs to learn the mapping from the pretrained model's outputs to our dog breeds.
This is called using the pretrained network as a fixed feature extractor, although the selected classification model's original outputs are being used as the features here.
Understand Layer 2: Dense output layer
tf_keras.layers.Dense(units=output_shape, activation="softmax")The Dense layer contains 120 output units, one per dog breed.
The softmax activation converts the output scores into a probability distribution:
You don't need to memorize this equation immediately. The important idea is that each output becomes a probability, and the probabilities across the 120 breeds sum to 1.
The class with the highest probability becomes the model's predicted breed.
Step 28: Understand loss, optimizer, and metric
When compiling the model, we configure three important components.
model.compile(
loss=tf_keras.losses.CategoricalCrossentropy(),
optimizer=tf_keras.optimizers.Adam(),
metrics=["accuracy"]
)| Component | What it does |
|---|---|
| Loss: categorical cross-entropy | Measures how well predicted probabilities match the correct one-hot labels |
| Optimizer: Adam | Updates trainable weights to reduce the loss |
| Metric: accuracy | Fraction of images with the correct top prediction |
The distinction between loss and accuracy is important.
A model may predict the correct breed but assign it a relatively low probability. It can receive credit for accuracy while still receiving a worse log-loss score.
Step 29: Create and inspect the model
model = create_model()
model.summary()Expected summary:
Layer (type) Output Shape Param #
=====================================================
keras_layer (KerasLayer) (None, 1001) 5,432,713
dense (Dense) (None, 120) 120,240
=====================================================
Total params: 5,552,953
Trainable params: 120,240
Non-trainable params: 5,432,713
What this tells us:
- Pretrained layer: outputs 1,001 values per image — the original ImageNet probabilities.
- Dense layer: maps those to 120 breed probabilities.
- Trainable parameters: only 120,240 (the Dense layer).
- Non-trainable parameters: 5.4M frozen weights.
Exact counts depend on the model version. Inspect your own model.summary() rather than assuming the numbers above.
Step 30: Create a TensorBoard callback
Training a model can involve many epochs, and it's helpful to track the loss and accuracy over time.
TensorBoard provides visualizations of training metrics.
First, load the notebook extension:
%load_ext tensorboardImport datetime if you haven't already, then create a callback
def create_tensorboard_callback():
"""Create a TensorBoard callback with a timestamped log directory."""
log_dir = os.path.join(
"logs",
datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
)
return tf_keras.callbacks.TensorBoard(log_dir=log_dir)Each call creates a timestamped directory for the training logs.
Why use timestamps? They help distinguish separate training experiments so you can compare their results.
Step 31: Create an early stopping callback
Training for more epochs doesn't always improve a model.
Eventually, a model may stop improving on validation data even while continuing to improve on training data. This can be a sign of overfitting.
We'll monitor validation accuracy:
early_stopping = tf_keras.callbacks.EarlyStopping(
monitor="val_accuracy",
patience=3
)Here's what the settings mean:
monitor="val_accuracy": Watch validation accuracy after each epoch.patience=3: Allow three consecutive epochs without improvement before stopping.
For this configuration, early stopping does not automatically restore the best model weights. To do that, you could set restore_best_weights=True.
TensorBoard and early stopping serve different purposes:
- TensorBoard helps you understand training.
- Early stopping prevents unnecessary training when the monitored metric stops improving.
Step 32: Choose the number of epochs
An epoch is one complete pass through the training dataset.
NUM_EPOCHS = 100For 800 images:
- 1 epoch = 800 images processed once
- 10 epochs = the dataset processed 10 times
- 100 epochs is the maximum — early stopping may end training sooner
There's no universally correct number. The right value depends on the dataset, model, and observed learning curves.
Step 33: Create a training function
Let's put model creation and training into one reusable function.
def train_model():
"""
Build, train, and return a fresh model.
"""
# Create a new model
model = create_model()
# Record training metrics
tensorboard = create_tensorboard_callback()
# Train the model
model.fit(
x=train_data,
validation_data=valid_data,
epochs=NUM_EPOCHS,
validation_freq=1,
callbacks=[
tensorboard,
early_stopping
]
)
return modelUnderstand the fit() arguments:
| Argument | Meaning |
|---|---|
x=train_data |
Supplies training image-label batches. |
validation_data=valid_data |
Evaluates the model on held-out images. |
epochs=NUM_EPOCHS |
Sets the maximum training duration. |
validation_freq=1 |
Runs validation after every epoch. |
callbacks |
Records metrics and controls early stopping. |
The function creates a fresh model each time it runs. It does not continue training a model previously stored in a variable.
Step 34: Train the model
Now run:
model = train_model()Training may take some time, depending on your hardware, available GPU, and data pipeline.
During training, pay attention to:
loss: training lossaccuracy: training accuracyval_loss: validation lossval_accuracy: validation accuracy
Expected outcome on 1,000 images: training accuracy reaches 100%, validation accuracy peaks around 67.5% (approximately and will vary).
This gap is a textbook example of overfitting.
| Metric | Value | Meaning |
|---|---|---|
| Training accuracy | 100% | Model classified all training examples correctly |
| Best validation accuracy | 67.5% | Performance on held-out images was lower |
Generalization means performing well on new examples that weren't used for training.
A large train/validation gap suggests the model memorized the training data rather than learning patterns that transfer.
Step 35: Visualize the training curves
Run TensorBoard:
%tensorboard --logdir logsYou can use it to inspect:
- How training loss changes over time.
- Whether validation loss continues improving.
- How training and validation accuracy compare.
- Whether performance stops improving after several epochs.
For example, if training accuracy rises while validation accuracy remains flat or falls, you should investigate overfitting rather than automatically increasing the number of epochs.
Checkpoint: You should have a trained model variable, and TensorBoard should display the recorded metrics if the logs were written successfully.
Part 5 — Evaluate and understand predictions
Step 36: Generate predictions on the validation set
Now let's inspect what the trained model actually predicts.
predictions = model.predict(
valid_data,
verbose=1
)
print(predictions.shape) # (200, 120)The shape is (number_of_validation_images, 120) — one probability vector per image. Each column corresponds to a breed in unique_breeds.
Step 37: Understand a single prediction
Let's examine the first validation image.
index = 0
print(predictions[index])
print("Maximum probability:", np.max(predictions[index]))
print("Sum of probabilities:", np.sum(predictions[index]))
print("Predicted class index:", np.argmax(predictions[index]))
print(
"Predicted breed:",
unique_breeds[np.argmax(predictions[index])]
)Here's what these operations do:
predictions[index]returns all 120 probabilities for one image.np.max()returns the highest probability.np.sum()checks that the probabilities add up to approximately 1.np.argmax()finds the index of the highest probability.unique_breeds[...]converts the index into a breed name.
A high probability means the model assigns substantial probability to that breed. However, the model can still be wrong, and its confidence is not necessarily a well-calibrated measure of real-world certainty.
Step 38: Convert predictions into breed names
Let's create a reusable helper function:
def get_pred_label(prediction_probabilities):
"""
Convert a probability vector into a breed label.
"""
predicted_index = np.argmax(
prediction_probabilities
)
return unique_breeds[predicted_index]Test it on a validation image:
get_pred_label(predictions[69])The function returns the breed with the highest predicted probability.
Step 39: Extract validation images and true labels
Our validation data is stored in batches. For visualization, it is useful to collect the images and convert the one-hot labels back into breed names.
def unbatchify(data):
"""
Convert a batched dataset into lists of images
and their corresponding true breed labels.
"""
images = []
labels = []
for image, label in data.unbatch().as_numpy_iterator():
images.append(image)
breed_index = np.argmax(label)
labels.append(unique_breeds[breed_index])
return images, labelsExtract the validation data:
valid_images, valid_labels = unbatchify(valid_data)
print("Validation images:", len(valid_images))
print("Validation labels:", len(valid_labels))Now we have three matching collections:
valid_images: The preprocessed validation images.valid_labels: The actual breed names.predictions: The predicted probabilities.
Important: These collections must stay in the same order. This works because the validation dataset is not shuffled, and predictions were generated from it in sequence. If you shuffle validation data, this breaks silently.
Step 40: Visualize individual predictions
Let's display an image alongside the predicted breed, confidence and true label.
def plot_pred(
prediction_probabilities,
labels,
images,
n=1
):
"""
Display an image with its predicted breed,
confidence and true label.
"""
pred_prob = prediction_probabilities[n]
true_label = labels[n]
image = images[n]
pred_label = get_pred_label(pred_prob)
confidence = np.max(pred_prob) * 100
color = (
"green"
if pred_label == true_label
else "red"
)
plt.imshow(image)
plt.xticks([])
plt.yticks([])
plt.title(
f"{pred_label} - {confidence:.2f}% "
f"({true_label})",
color=color
)Try it:
plot_pred(
prediction_probabilities=predictions,
labels=valid_labels,
images=valid_images,
n=0
)
plt.show()Inspect additional examples:
plot_pred(predictions, valid_labels, valid_images, n=42)
plt.show()
plot_pred(predictions, valid_labels, valid_images, n=77)
plt.show()Reading the display:
- Green title: The predicted breed matches the true label.
- Red title: The predicted breed is incorrect.
- Percentage: The probability assigned to the top predicted breed.
- Breed in parentheses: The true breed.
This makes it easier to see whether the model is confusing visually similar breeds.
Step 41: Visualize the top 10 predicted breeds
Sometimes the top prediction is wrong, but the correct breed is still among the model's most likely choices.
Let's inspect the 10 highest predicted probabilities:
def plot_pred_conf(
prediction_probabilities,
labels,
n=1
):
"""
Plot the top 10 predicted breeds and highlight
the true breed if it appears among them.
"""
pred_prob = prediction_probabilities[n]
true_label = labels[n]
# Get indices of the 10 highest probabilities
top_10_pred_indexes = pred_prob.argsort()[-10:][::-1]
# Get probabilities and breed names
top_10_pred_values = pred_prob[top_10_pred_indexes]
top_10_pred_labels = unique_breeds[top_10_pred_indexes]
# Plot probabilities
bars = plt.bar(
np.arange(len(top_10_pred_labels)),
top_10_pred_values,
tick_label=top_10_pred_labels
)
plt.xticks(rotation=90)
plt.ylabel("Predicted probability")
# Highlight the true breed when present
if true_label in top_10_pred_labels:
true_index = np.where(
top_10_pred_labels == true_label
)[0][0]
bars[true_index].set_color("green")Test it:
plot_pred_conf(
prediction_probabilities=predictions,
labels=valid_labels,
n=9
)
plt.tight_layout()
plt.show()The bars show the 10 most likely breeds, from highest to lowest probability.
If the true breed appears in the top 10, its bar is highlighted in green.
This gives us more information than top-1 accuracy alone. For example, a correct breed ranked second indicates that the model recognized it as a plausible candidate, even though its top prediction was incorrect.
Step 42: Compare images and confidence charts side by side
We can combine both visualizations to examine several examples at once.
num_rows = 3
num_images = num_rows * 2
start_index = 0
plt.figure(figsize=(16, 15))
for i in range(num_images):
index = start_index + i
# Left: image and predicted label
plt.subplot(num_rows, 4, 2 * i + 1)
plot_pred(
prediction_probabilities=predictions,
labels=valid_labels,
images=valid_images,
n=index
)
# Right: top 10 predicted breeds
plt.subplot(num_rows, 4, 2 * i + 2)
plot_pred_conf(
prediction_probabilities=predictions,
labels=valid_labels,
n=index
)
plt.tight_layout()
plt.show()You can change start_index to inspect different groups of validation images.
This visualization helps answer three questions:
- Did the model predict the correct breed?
- How much probability did it assign to its top prediction?
- Was the correct breed among its other likely predictions?
Part 6 — Save, scale, and use the model
Step 43: Save the trained model
Training can take time, so we should save the model instead of retraining it whenever we reopen the notebook.
We'll use Keras's .keras format.
def save_model(model, suffix="model"):
"""
Save a model in a timestamped directory.
"""
modeldir = os.path.join(
"models",
datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
)
os.makedirs(modeldir, exist_ok=True)
model_path = os.path.join(
modeldir,
f"{suffix}.keras"
)
print(f"Saving model to: {model_path}")
model.save(model_path)
return model_pathSave our model:
saved_model_path = save_model(
model,
suffix="1000-images-Adam"
)
print(saved_model_path)The saved model includes the model architecture and learned weights, along with its training configuration.
The timestamped directory helps you keep different experiments separate.
Storage note: The example saves to the notebook's working directory. If you need the model to persist across Colab runtime resets, save it to a suitable Google Drive location.
Step 44: Load a saved model
Now let's load the model without training it again.
Because this model uses TensorFlow Hub's KerasLayer, we supply that layer through custom_objects.
def load_model(model_path):
"""
Load a saved TensorFlow Hub-based Keras model.
"""
print(f"Loading saved model from: {model_path}")
model = tf_keras.models.load_model(
model_path,
custom_objects={
"KerasLayer": hub.KerasLayer
}
)
return modelLoad the saved model:
model_1000_images = load_model(
saved_model_path
)Version note: TensorFlow, Keras, and TensorFlow Hub must be roughly compatible with the versions used to save the model. If you upgrade any of them between save and load, expect possible failures.
Step 45: Verify the loaded model works
Evaluate the original and reloaded models on the same validation dataset:
original_results = model.evaluate(
valid_data,
verbose=0
)
loaded_results = model_1000_images.evaluate(
valid_data,
verbose=0
)
print("Original model:", original_results)
print("Loaded model:", loaded_results)Results should be approximately identical. Saving is only useful if you can successfully reload and reproduce behavior.
Step 46: Train a new model on the full dataset
Once the smaller experiment works, we can scale up to all the labeled training images.
First, confirm the full dataset is available:
print("Total image paths:", len(X))
print("Total labels:", len(y))You should see ~10,222 examples.
Create a dataset from all the training images:
full_data = create_data_batches(
X,
y
)
print(full_data.element_spec)Create a fresh model (independent of the earlier 1,000-image experiment):
full_model = create_model()Configure callbacks:
full_model_tensorboard = create_tensorboard_callback()
full_model_early_stopping = tf_keras.callbacks.EarlyStopping(
monitor="accuracy",
patience=3
)Important limitation: This training run uses all labeled data, so there's no separate validation set. Early stopping here monitors training accuracy, which does not measure generalization. A stronger design would reserve 10–20% of the data as a validation set, use
val_accuracyfor early stopping, and evaluate the final model on that held-out set.
Train:
full_model.fit(
full_data,
epochs=NUM_EPOCHS,
callbacks=[
full_model_tensorboard,
full_model_early_stopping
]
)Step 47: Save and reload the full-data model
Save the newly trained model:
saved_full_model_path = save_model(
full_model,
suffix="all-images-Adam"
)Reload it:
loaded_full_model = load_model(
saved_full_model_path
)You now have a model trained using the full labeled training dataset and a reloaded copy ready for inference.
Step 48: Collect test image paths
The test dataset contains images without breed labels.
Define the directory:
test_path = os.path.join(
dataset_dir,
"test"
)Collect the image paths:
test_filenames = [
os.path.join(test_path, filename)
for filename in os.listdir(test_path)
if filename.lower().endswith(".jpg")
]
print("Test images:", len(test_filenames))
print(test_filenames[:10])The original notebook uses os.listdir(), which doesn't guarantee a consistent ordering. Here, we filter for JPEG files, but the crucial rule remains: preserve the same file ordering throughout prediction and submission creation.
For reproducible ordering across separate runs, you can sort the paths:
test_filenames = sorted(test_filenames)If you sort them, use that same ordered list for all subsequent prediction and submission steps.
Step 49: Create test data batches
Test images don't have labels, so we use test_data=True.
test_data = create_data_batches(
test_filenames,
test_data=True
)
print(test_data.element_spec)The pipeline will preprocess and batch the test images using the same image transformations as our training data.
This consistency is essential. A model trained on normalized 224 × 224 images should receive inputs prepared in the same way during inference.
Step 50: Generate test predictions
Use the full-data model:
test_predictions = loaded_full_model.predict(
test_data,
verbose=1
)
print(test_predictions.shape)The expected shape is:
(number_of_test_images, 120)Each row contains the predicted probabilities for one test image.
Save the predictions so you don't need to run inference again:
np.savetxt(
"test_predictions.csv",
test_predictions,
delimiter=","
)Reload them later:
test_predictions = np.loadtxt(
"test_predictions.csv",
delimiter=","
)
print(test_predictions.shape)For this competition, the expected output has 120 probability columns per image.
Step 51: Create a Kaggle submission file
The competition expects one row per test image: an id column plus one probability column per breed.
Extract IDs from filenames:
test_ids = [
os.path.splitext(os.path.basename(filepath))[0]
for filepath in test_filenames
]Create the DataFrame:
submission_df = pd.DataFrame(
test_predictions,
columns=unique_breeds
)
submission_df.insert(
0,
"id",
test_ids
)
submission_df.head()The breed column names must match the competition's expected breed columns. The unique_breeds array is appropriate for the training labels, but you should verify the exact expected column order against sample_submission.csv before submitting.
Validate the submission
Check its shape:
print(submission_df.shape)If there are test images, the expected shape is:
That is one ID column plus 120 breed probability columns.
Check for missing values:
print(
"Missing values:",
submission_df.isnull().sum().sum()
)Check whether each row's breed probabilities sum to approximately 1:
submission_df[unique_breeds].sum(axis=1).head()Save the submission:
submission_df.to_csv(
"submission.csv",
index=False
)The file can then be uploaded to the Kaggle competition if it meets the competition's submission requirements.
Checkpoint: Verify the column names, column order, number of rows, absence of missing values, and correspondence between each image ID and its predictions before submitting.
Step 52: Predict the breed of your own dog photographs
The final step is to use the model on images outside the Kaggle dataset.
This is where the project becomes especially practical: you can provide a photograph and see what breed the model predicts.
Create a folder for custom images:
We'll store the images in Colab's temporary filesystem:
custom_image_dir = "/content/custom_images"
os.makedirs(
custom_image_dir,
exist_ok=True
)Upload your own dog photographs into this folder using the Files panel on the left side of Colab.
Note that files stored under
/content/can disappear when the runtime resets.
Collect the image paths:
custom_image_filenames = [
os.path.join(custom_image_dir, filename)
for filename in os.listdir(custom_image_dir)
if filename.lower().endswith((".jpg", ".jpeg"))
]
print("Custom images:", len(custom_image_filenames))
print(custom_image_filenames)If the count is zero, verify that the images are in the correct folder and use supported file extensions.
Create batches and predict:
custom_data = create_data_batches(
custom_image_filenames,
test_data=True
)Generate predictions using the saved full-data model:
custom_predictions = loaded_full_model.predict(
custom_data,
verbose=1
)
print(custom_predictions.shape)Display the results:
for image_path, probabilities in zip(
custom_image_filenames,
custom_predictions
):
predicted_index = np.argmax(probabilities)
predicted_breed = unique_breeds[predicted_index]
confidence = probabilities[predicted_index] * 100
image = tf_keras.utils.load_img(image_path)
plt.figure(figsize=(5, 5))
plt.imshow(image)
plt.title(
f"Predicted breed: {predicted_breed}\n"
f"Confidence: {confidence:.2f}%"
)
plt.axis("off")
plt.show()The output displays each photograph, the model's predicted breed, and the probability assigned to that prediction.
Remember that the model was trained on the competition dataset. Its predictions on photographs with unusual backgrounds, poor lighting, multiple dogs, or unfamiliar breeds may be unreliable. The confidence score should not be treated as a guarantee that the breed is correct.
Part 7 — Quick reference and troubleshooting
The complete workflow at a glance
| Step | Action |
|---|---|
| 1 | Load the dataset — read labels and locate images |
| 2 | Prepare labels — map 120 breeds into one-hot vectors |
| 3 | Split the data — create training and validation sets |
| 4 | Preprocess images — decode, normalize, resize |
| 5 | Build data pipelines — shuffle training examples and batch images. |
| 6 | Build the model — load MobileNet V2 and add a Dense output layer. |
| 7 | Train the model — optimize weights and monitor validation performance. |
| 8 | Evaluate predictions — inspect probabilities, accuracy and mistakes. |
| 9 | Save the model — store and reload trained weights. |
| 10 | Run inference — predict test images and custom photographs |
Important concepts to remember
| Concept | Remember this |
|---|---|
| Multiclass classification | One image is assigned to one of many possible classes |
| Tensor | A multidimensional array of numerical values |
| One-hot encoding | A vector with one positive entry identifying the correct class |
| Batch | A group of examples processed together |
| Epoch | One complete pass through the training dataset |
| Transfer learning | Reusing a pretrained model for a related task |
| Frozen weights | Parameters that are not updated during training |
| Softmax | Converts scores into class probabilities that sum to 1 |
| Loss | Measures prediction error against a chosen objective |
| Accuracy | Measures the proportion of correct top-class predictions |
| Overfitting | Strong training performance but weaker performance on unseen data |
| Generalization | The ability to perform well on new examples |
| Inference | Using a trained model to make predictions |
Common problems and how to investigate them
| Symptom | Investigation |
|---|---|
| Training directory empty or file count wrong | Verify the ZIP was extracted to the expected directory. Print os.listdir(dataset_dir) and check the train/ subdirectory exists. |
| Image and label counts don't match | Check len(filenames), len(labels), and that every path exists. Confirm the arrays are in the same order. |
| Unexpected tensor shape | Check sample_image.shape, sample_label.shape, and train_data.element_spec. Expected (224, 224, 3) and (120,) before batching. |
| High training accuracy, low validation accuracy | Investigate overfitting, the training/validation split, class imbalance, and the quality of your data. More epochs alone may not solve the problem. |
| Loaded model fails | Verify the path and TensorFlow/Keras compatibility. KerasLayer requires custom_objects={"KerasLayer": hub.KerasLayer} at load time. |
| Custom image predictions seem wrong | Confirm the image was preprocessed identically to training data. Also remember predictions can be unreliable on images far from the training distribution. |
| Kaggle submission rejected | Compare your column names, column order, and row IDs to sample_submission.csv. Check for missing values. |
Suggested exercises
Use these exercises to turn the tutorial into an actual learning experience rather than simply running every cell.
- Explore the data. Find the breed with the most images and the breed with the fewest.
- Understand labels. Convert one breed name to a one-hot vector by hand and explain what each position means.
- Experiment with batch size. Try 16 and 32. Compare batch counts and training behavior.
- Inspect predictions. Find three correctly classified images and three incorrect ones. Are the errors on visually similar breeds?
- Study overfitting. Compare training accuracy and validation accuracy across epochs.
- Try custom images. Test the model on photos with varied backgrounds, lighting, and angles. Where does it break down?
Final notes before using this as a reference
A few things are worth remembering when extending this notebook:
-
Metric alignment. The competition scores log loss. The notebook tracks accuracy during training — validate on
val_lossas well, since accuracy can be misleading when predictions are correct but poorly calibrated. -
Validation during full-data training. The full-data training stage uses training accuracy for early stopping because no validation set is provided. If you want to claim a real accuracy figure for the final model, hold out a validation set before scaling up.
-
Reproducibility. Preserve and save:
- The class-to-index mapping (
unique_breeds) - Preprocessing settings (size, normalization)
- Image ordering for test predictions
The model alone is not enough — without these, its predictions can be silently misinterpreted.
- The class-to-index mapping (
-
Input preprocessing. Reusing the right image dimensions is not the same as matching normalization. Check the pretrained model's documented input requirements. A mismatch doesn't raise an error; it just produces worse predictions.
-
Experiment tracking. For each run, record: dataset size, batch size, epochs, training loss, validation loss, validation accuracy. Without this log, it's difficult to know whether a change genuinely helped or was noise.
-
On the ~67.5% validation accuracy. This is a reasonable starting result for a frozen feature extractor on 1,000 images. Improvements usually come from: more training data (10,000+ images), fine-tuning the top layers of the pretrained model, data augmentation, and a stratified split. Each of these is a natural next step — but each should be measured against a proper validation set.
The central lesson: Building a machine learning model isn't just about constructing a neural network. Data preparation, consistent preprocessing, validation, evaluation, and reproducibility are equally important — and often determine whether the model works in practice.
Once you understand this workflow, you can adapt it to many other image classification tasks: classifying flowers, identifying plant diseases, recognizing objects, or detecting defects in industrial images. The pipeline stays largely the same; only the data and the number of classes change.