This lab trains a cat vs dog image classifier with transfer learning on a pretrained MobileNet model in TensorFlow/Keras, and uses MLflow to record each training run's parameters, metrics and model. The notebook above covers downloading images, checking them and loading them into a dataset. The sections below add a complete training script that runs as it is, MLflow tracking and model loading, fixes for outdated parts of the notebook, and troubleshooting.
What this lab builds and why MLflow is used
The notebook downloads about 100 cat and 100 dog images from Bing and removes broken files. It then fine-tunes a classifier on top of MobileNet, which was pretrained on ImageNet. With only about 200 images, training a convolutional network from scratch would overfit badly. Reusing MobileNet's learned features and training only a small classification head gives reasonable accuracy in a few minutes on a CPU.
MLflow handles the MLOps side of the lab. Each training run is stored under the experiment cat-dog-classifier-mobilenet with a timestamp as its run name. A run records the hyperparameters, the loss and accuracy for each epoch, and the trained model as an artifact. You can then change the learning rate or the number of epochs, run training again, and compare the runs side by side in the MLflow UI instead of keeping notes by hand.
Prerequisites and environment setup
- A Python version that your TensorFlow release supports. Check TensorFlow's install page before you create the environment, because new Python releases are often supported only some time after they come out.
- About 2 GB of free disk space for TensorFlow, the MobileNet weights and the images.
- Internet access for the first run. MobileNet's ImageNet weights are downloaded once and cached in
~/.keras/models.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install --upgrade pip
pip install mlflow tensorflow pillow bing-image-downloader jupyter
# Start a local tracking server with its UI in a separate terminal
mlflow server --host 127.0.0.1 --port 5000Code language: PHP (php)
Open http://127.0.0.1:5000 in a browser to check that the server is running. If you skip the server, MLflow writes runs to a local store in the working directory, and you can view them with mlflow ui from that same directory.
Preparing and cleaning the dataset
image_dataset_from_directory uses subfolder names as class labels, sorted alphabetically. Because bing-image-downloader creates one subfolder per query, downloading the queries cat and dog into ./data/cat_dogs/ gives exactly the layout it expects. cat becomes label 0 and dog becomes label 1.
data/cat_dogs/
โโโ cat/
โ โโโ Image_1.jpg
โ โโโ ...
โโโ dog/
โโโ Image_1.jpg
โโโ ...
Images scraped from the web often include truncated downloads, WebP files saved with a .jpg extension, or HTML error pages. Any one of these can make training fail partway through an epoch. The script below downloads the images with the safe-search filter on, then deletes every file that Pillow cannot verify or that TensorFlow cannot decode. This replaces the imghdr check in the notebook.
from pathlib import Path
from PIL import Image
from bing_image_downloader import downloader
image_path = "./data/cat_dogs/"
for query in ["cat", "dog"]:
downloader.download(query, limit=100, output_dir=image_path,
adult_filter_off=False, # keep Bing's adult filter ON
force_replace=False, timeout=60)
accepted = {"jpeg", "png", "gif", "bmp"} # formats TensorFlow can decode
removed = 0
for p in Path(image_path).rglob("*"):
if not p.is_file():
continue
try:
with Image.open(p) as im:
fmt = (im.format or "").lower()
im.verify() # detects truncated/corrupt files
if fmt not in accepted:
raise ValueError(f"unsupported format '{fmt}'")
except Exception as err:
print(f"Removing {p}: {err}")
p.unlink()
removed += 1
print(f"Removed {removed} invalid files")Code language: PHP (php)
Note: Scraped images can contain near-duplicates, cartoons, and photos showing both a cat and a dog. Look through each folder quickly before training. With a dataset this small, a few mislabelled images change validation accuracy noticeably.
Complete training script with MLflow tracking
The notebook above stops after loading the data. The script below finishes the workflow with transfer learning, light data augmentation, early stopping and MLflow autologging. Save it as train.py and run python train.py, or paste it into notebook cells.
from datetime import datetime
import mlflow
import mlflow.tensorflow
import tensorflow as tf
from tensorflow import keras
image_path = "./data/cat_dogs/"
learning_rate = 0.001
num_epochs = 20
batch_size = 32
input_shape = (224, 224, 3)
experiment_name = "cat-dog-classifier-mobilenet"
run_name = datetime.now().strftime("%Y%m%d_%H%M%S")
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment(experiment_name)
common = dict(validation_split=0.2, seed=1337, image_size=input_shape[:2],
batch_size=batch_size, label_mode="binary")
train_ds = keras.utils.image_dataset_from_directory(image_path, subset="training", **common)
val_ds = keras.utils.image_dataset_from_directory(image_path, subset="validation", **common)
class_names = train_ds.class_names # ['cat', 'dog']
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(AUTOTUNE)
val_ds = val_ds.cache().prefetch(AUTOTUNE)
base = keras.applications.MobileNet(input_shape=input_shape,
include_top=False, weights="imagenet")
base.trainable = False # freeze pretrained features
inputs = keras.Input(shape=input_shape)
x = keras.layers.RandomFlip("horizontal")(inputs)
x = keras.layers.RandomRotation(0.1)(x)
x = keras.layers.Rescaling(1.0 / 127.5, offset=-1)(x) # MobileNet expects [-1, 1]
x = base(x, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.2)(x)
outputs = keras.layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer=keras.optimizers.Adam(learning_rate),
loss="binary_crossentropy", metrics=["accuracy"])
mlflow.tensorflow.autolog() # params, per-epoch metrics, model
with mlflow.start_run(run_name=run_name) as run:
mlflow.log_params({"base_model": "MobileNet",
"input_size": f"{input_shape[0]}x{input_shape[1]}",
"class_names": ",".join(class_names)})
model.fit(train_ds, validation_data=val_ds, epochs=num_epochs,
callbacks=[keras.callbacks.EarlyStopping(
monitor="val_loss", patience=3, restore_best_weights=True)])
val_loss, val_acc = model.evaluate(val_ds, verbose=0)
mlflow.log_metric("final_val_accuracy", val_acc)
print(f"Run ID: {run.info.run_id} val_accuracy={val_acc:.3f}")Code language: PHP (php)
label_mode="binary"returns labels as floats of shape (batch, 1), which match a single sigmoid output andbinary_crossentropy.- The
Rescaling(1/127.5, offset=-1)layer applies MobileNet's expected preprocessing inside the model. Without it, the frozen ImageNet features receive inputs in the wrong range and accuracy stays near chance. Because the scaling is part of the model, inference code can pass raw 0โ255 pixels. mlflow.tensorflow.autolog()records the optimizer settings, epochs, per-epochloss,accuracy,val_lossandval_accuracy, the early-stopping details and the trained model.- Use custom parameter names such as
base_modelandinput_sizefor manual logging. MLflow raises an error if a run logs the same parameter key twice with different values, so names that autolog already uses would conflict.
Expected output: the loader reports something like Found 195 files belonging to 2 classes, then Using 156 files for training and Using 39 files for validation. On clean data, validation accuracy usually rises above 0.9 within a few epochs. Early stopping then ends the run before all 20 epochs complete.
Comparing runs and using the logged model
- Open
http://127.0.0.1:5000and select the experimentcat-dog-classifier-mobilenet. - Change one hyperparameter, for example
learning_rate = 0.0005, and run the script again. Every execution creates a new run named with its timestamp. - Tick two or more runs and click Compare to see parameters side by side and plot
val_accuracyagainst the epoch. - Open the best run and copy its model URI from the artifacts or logged-model section. In MLflow 2.x autologging this is usually
runs:/<RUN_ID>/model.
import mlflow.tensorflow
from tensorflow import keras
model = mlflow.tensorflow.load_model("runs:/<RUN_ID>/model")
img = keras.utils.load_img("my_pet.jpg", target_size=(224, 224))
batch = keras.utils.img_to_array(img)[None, ...] # shape (1, 224, 224, 3)
prob_dog = float(model.predict(batch, verbose=0)[0][0])
print("dog" if prob_dog >= 0.5 else "cat", round(prob_dog, 3))Code language: PHP (php)
Corrections to the original notebook
| Original | Corrected | Reason |
|---|---|---|
import imghdr and imghdr.what(filepath) | Pillow Image.open() plus verify() | imghdr was deprecated in Python 3.11 and removed in 3.13, so the import fails on current Python. |
Check only covers .png and .jpg and only prints problems | Check every file and delete invalid ones | .jpeg and extensionless files were skipped. The notebook also left deletion as a manual step, so a bad file could still break training. |
keras.preprocessing.image_dataset_from_directory | keras.utils.image_dataset_from_directory | The keras.preprocessing alias is deprecated and is not available in newer Keras releases. |
adult_filter_off=True | adult_filter_off=False | True turns off Bing's adult content filter, which is unsafe for a training lab. |
import mlflow.keras for a tf.keras model | mlflow.tensorflow.autolog() | In recent MLflow versions, the TensorFlow flavor handles tf.keras training, while mlflow.keras targets standalone Keras 3. |
learning_rate = 0.01, num_epochs = 50 | 0.001, 20 epochs with EarlyStopping | With about 156 training images, a high learning rate and 50 epochs make overfitting likely. Early stopping keeps the best weights. |
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'imghdr' | Running on Python 3.13 or later | Use the Pillow-based check from the dataset section. |
InvalidArgumentError: ... Unknown image file format during fit | A corrupt or WebP file saved with a .jpg extension | Run the cleaning script again. It deletes files that Pillow cannot identify as JPEG, PNG, GIF or BMP. |
Found 0 files belonging to 0 classes | Wrong path, or images placed directly in cat_dogs/ without class subfolders | Make sure the layout is data/cat_dogs/cat/* and data/cat_dogs/dog/*. |
| Validation accuracy stuck near 0.5 | Missing MobileNet preprocessing, or a label/loss mismatch | Keep the Rescaling layer, and use label_mode="binary" with a sigmoid output. |
MlflowException: Changing param values is not allowed | A manually logged param key is the same as one autolog writes | Rename the manual param, or log it only once per run. |
Connection refused to 127.0.0.1:5000 | The tracking server is not running | Start mlflow server, or remove set_tracking_uri to use the local store. |
Best practices for taking this lab further
- Keep a separate test folder that is never used for training or early stopping, and log the test accuracy as its own metric.
- Once the classification head has converged, set
base.trainable = Truefor the top layers only, recompile with a learning rate around1e-5, and log the fine-tuning as a new run. - Log the dataset size and a hash of the file list with
mlflow.log_param, so every run can be traced back to the data it used. - Register the best model in the MLflow Model Registry so deployment code loads it by name instead of by run ID.
- Check the licensing of scraped images before you use the model anywhere other than a private lab.
Frequently asked questions
What does mlflow.tensorflow.autolog() record for a Keras model?
It logs the training parameters, such as epochs and the optimizer settings, along with per-epoch loss and accuracy for both training and validation data. It also saves the trained model as a run artifact. Call it before model.fit() so the training is captured.
Why use MobileNet instead of training a CNN from scratch?
About 200 images is far too few to train a convolutional network from scratch without heavy overfitting. MobileNet's ImageNet features already recognise shapes and textures, so only a small classification head has to be trained. MobileNet is also light enough to train on a CPU.
Where does MLflow store runs if no tracking server is configured?
MLflow writes runs to a local store in the current working directory. Running mlflow ui from that same directory shows them. For a team or a longer-lived setup, run mlflow server with a database backend and point clients to it with set_tracking_uri.
How do I load the trained cat vs dog model for predictions?
Copy the model URI from the run in the MLflow UI and pass it to mlflow.tensorflow.load_model(). In the training script above, rescaling is part of the model, so you can pass raw 224×224 RGB pixel arrays to predict(). An output of 0.5 or more means dog.
How many images do I need for a reasonable cat vs dog classifier?
With transfer learning, a few hundred clean, correctly labelled images per class usually give good results. Data quality matters more than quantity at this scale, so remove mislabelled and broken files before adding more.
Related tutorials
- More MLOps tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals