Skip to main content

Chapter 17 demo: Using pretrained image models

Read Chapter 17 · Download notebook (.ipynb)

Pretrained models let us reuse what a neural network learned from a large dataset. We can use them in three ways:

  1. Use them out of the box: keep the pretrained model, including its classifier, and predict its original labels without training.
  2. Use frozen weights: keep the pretrained CNN fixed as a feature extractor and train a new classifier for our own labels.
  3. Fine-tune: train some or all of the pretrained CNN weights on our new task, along with a task-specific classifier.

We will first classify images with an out-of-the-box ImageNet model, then use frozen features to learn seven food categories. We will finish by discussing fine-tuning.

Setup and data

Use a pretrained classifier and train a new classifier on frozen image features.

Run cells in order with the repository’s Python environment selected as the kernel. From the repository root, start Jupyter with uv run --locked jupyter lab, then open book/demo-chapter-17-transfer-learning.ipynb. Data paths work from either the repository root or book/. If using a downloaded notebook separately, place its required files in a data/ folder beside it.

Use data/test_images/ and the local data/food-transfer-learning/ subset, whose train/ and valid/ folders contain one subfolder per category. Source: Food-101. Requires PyTorch and torchvision; the first MobileNet run may download weights. CPU, CUDA, and Apple Silicon devices are supported by the example.

Class route: Run out-of-the-box predictions and frozen-feature classification. Fine-tuning is a discussion extension. Reserve the existing valid/ folder for final evaluation and select models within train/.

Pause at prediction and discussion questions before revealing results. Rendered pages show saved outputs; controls that depend on a running Python kernel require Jupyter. General environment and download guidance is on the Demos page.

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from PIL import Image
from IPython.display import display
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay, classification_report
from sklearn.model_selection import StratifiedKFold, cross_validate, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, models

RANDOM_STATE = 42
torch.manual_seed(RANDOM_STATE)
np.random.seed(42)
plt.rcParams["font.size"] = 14
pd.set_option("display.max_colwidth", 120)

DATA_DIR = Path("data") if Path("data").is_dir() else Path("book/data")
# Use a GPU when available, including Apple Silicon GPUs via MPS.
if torch.cuda.is_available():
    DEVICE = torch.device("cuda")
elif torch.backends.mps.is_available():
    DEVICE = torch.device("mps")
else:
    DEVICE = torch.device("cpu")
print("Device:", DEVICE)
Device: mps

1. Use a pretrained model out of the box

Keep MobileNet’s original classifier to predict the 1,000 ImageNet categories. No training is needed: use the resizing, cropping, and normalization supplied with the pretrained weights, then convert the model’s scores to probabilities with softmax.

Predict: Which of our test images fit ImageNet’s categories? What might happen for a campus scene or an unfamiliar object?

weights = models.MobileNet_V3_Small_Weights.IMAGENET1K_V1
imagenet_preprocess = weights.transforms()
imagenet_labels = weights.meta["categories"]
imagenet_model = models.mobilenet_v3_small(weights=weights).to(DEVICE).eval()
imagenet_model.requires_grad_(False)


def classify_image(image_path, topn=5):
    """Return the top ImageNet labels and probabilities without training."""
    with Image.open(image_path) as image:
        inputs = imagenet_preprocess(image.convert("RGB")).unsqueeze(0).to(DEVICE)
    with torch.inference_mode():
        probabilities = imagenet_model(inputs).softmax(dim=1)[0]
        top_probabilities, top_indices = probabilities.topk(topn)
    return pd.DataFrame({
        "label": [imagenet_labels[index] for index in top_indices.cpu().tolist()],
        "probability": top_probabilities.cpu().tolist(),
    })
# Predict top labels and their associated probabilities for unseen images.
images = sorted(
    path for path in (DATA_DIR / "test_images").iterdir()
    if path.suffix.lower() in {".jpg", ".jpeg", ".png"}
)
for img_path in images:
    with Image.open(img_path) as image:
        img = image.convert("RGB")
        img.load()
    plt.figure(figsize=(5, 5))
    plt.imshow(img)
    plt.title(img_path.name)
    plt.axis("off")
    plt.show()
    df = classify_image(img_path)
    print(df.to_string(index=False))
    print("--------------------------------------------------------------")

   label  probability
 macaque     0.873478
   patas     0.051679
  langur     0.032532
capuchin     0.010821
  guenon     0.009417
--------------------------------------------------------------

      label  probability
  tiger cat     0.276426
Persian cat     0.275406
   Pembroke     0.251487
      tabby     0.094764
     collie     0.019244
--------------------------------------------------------------

       label  probability
     cheetah     0.973194
     leopard     0.023899
      jaguar     0.001837
snow leopard     0.000904
        lynx     0.000113
--------------------------------------------------------------

                     label  probability
               EntleBucher     0.237392
Greater Swiss Mountain dog     0.234903
                    beagle     0.162165
               Appenzeller     0.151979
              Walker hound     0.147873
--------------------------------------------------------------

Discuss: Looking at the test images and their top-five predictions, when does the out-of-the-box model succeed, and when does it fail? What might explain the difference, and does a high predicted probability always mean the model is correct?

Reveal model answer

The model tends to succeed when an image contains a clear object from one of ImageNet’s categories and resembles the images used to train it. Look for examples where the correct label appears first or among the top five; related labels can also indicate that the model recognizes useful visual features.

It can fail when the subject has no suitable ImageNet label, when a scene contains several objects without a single obvious subject, or when lighting, viewpoint, background, or image quality differs from its training data. For example, a campus photograph may receive a label for a visible object rather than identify the campus; the model can only choose from its 1,000 original categories. Its preprocessing may also crop out useful context.

A high probability does not guarantee correctness: softmax distributes probability among the available labels even when none fits well. These examples suggest where the model may be useful, but we would need labeled images representative of our intended task to measure how often it succeeds.

To predict our own seven food labels, we will replace the original classifier and learn a new one from frozen CNN features.

2. Use frozen weights for a new task

Our food-classification workflow keeps the pretrained CNN fixed and trains a new classifier. We will compare learned features with pixels, select regularization using cross-validation, and evaluate on reserved images.

Predict: Can we learn seven food categories without training a CNN from scratch?

2.1. Inspect the food images and labels

ImageFolder uses subfolder names as labels. Check that the integer-to-label mapping agrees across splits. Keep duplicate images and photographs of the same meal in the same split when preparing a dataset.

Predict: What accuracy would a most-frequent classifier achieve on roughly balanced seven-class data?

food_dir = DATA_DIR / "food-transfer-learning"
for split in ["train", "valid"]:
    if not (food_dir / split).is_dir():
        raise FileNotFoundError(f"Required image folder: {(food_dir / split).resolve()}")
food_train = datasets.ImageFolder(food_dir / "train")
food_valid = datasets.ImageFolder(food_dir / "valid")
assert food_train.class_to_idx == food_valid.class_to_idx
class_names = food_train.classes
counts = pd.DataFrame({
    "training images": pd.Series(food_train.targets).value_counts(),
    "held-out images": pd.Series(food_valid.targets).value_counts(),
}).reindex(range(len(class_names)), fill_value=0)
counts.index = class_names
display(counts)
print("Training majority proportion:", counts["training images"].max() / len(food_train))
training images held-out images
beet_salad 40 10
chocolate_cake 38 9
edamame 40 10
french_fries 40 10
pizza 43 10
spring_rolls 41 9
sushi 41 9
Training majority proportion: 0.1519434628975265
fig, axes = plt.subplots(2, 4, figsize=(12, 6))
for ax, class_name in zip(axes.flat, food_train.classes):
    class_index = food_train.class_to_idx[class_name]
    image_index = food_train.targets.index(class_index)
    image, _ = food_train[image_index]
    ax.imshow(image)
    ax.set_title(class_name.replace("_", " "))
    ax.axis("off")
axes.flat[-1].axis("off")
plt.tight_layout()

2.2. Reuse a pretrained feature extractor

MobileNetV3-Small architecture illustration. AI-generated using OpenAI’s ChatGPT (2026)

Our workflow is image → fixed MobileNet preprocessing → frozen CNN → 576 features → scaler → logistic regression.

MobileNet learned its weights from ImageNet. Replacing its original classifier with Identity returns features instead of its 1,000 original class scores. Our logistic regression learns the seven food labels. Those labels do not need to match ImageNet’s categories.

  • weights.transforms() supplies the fixed resizing, cropping, and normalization expected by the pretrained weights.
  • requires_grad_(False) freezes parameters; eval() sets prediction behaviour; inference_mode() avoids gradient tracking.
  • shuffle=False preserves image order so feature rows, labels, and displayed images remain aligned.

Predict: Does extracting features from a held-out image update the CNN?

# Reuse the same pretrained weights and preprocessing from part 1.
feature_model = models.mobilenet_v3_small(weights=weights)
feature_model.classifier = nn.Identity() # bypasses the classifier
feature_model.requires_grad_(False) # freeze the CNN
feature_model = feature_model.to(DEVICE).eval()


def make_loader(split):
    dataset = datasets.ImageFolder(food_dir / split, transform=imagenet_preprocess)
    assert dataset.class_to_idx == food_train.class_to_idx
    reference = food_train if split == "train" else food_valid
    assert dataset.samples == reference.samples
    return DataLoader(dataset, batch_size=32, shuffle=False, num_workers=0)


def extract_features(model, data_loader, device):
    """Return feature rows and labels in loader order without updating weights."""
    model.eval()
    feature_batches, target_batches = [], []
    with torch.inference_mode():
        for images, targets in data_loader:
            feature_batches.append(model(images.to(device)).cpu())
            target_batches.append(targets)
    return torch.cat(feature_batches).numpy(), torch.cat(target_batches).numpy()


Z_train, y_train = extract_features(feature_model, make_loader("train"), DEVICE)
np.testing.assert_array_equal(y_train, food_train.targets)
assert Z_train.shape == (len(food_train), 576)
assert not any(p.requires_grad for p in feature_model.parameters())
print("Training feature matrix:", Z_train.shape)
print("Training targets:", y_train.shape)
Training feature matrix: (283, 576)
Training targets: (283,)
pd.DataFrame(Z_train)
0 1 2 3 4 5 6 7 8 9 ... 566 567 568 569 570 571 572 573 574 575
0 0.065005 0.307216 0.646746 1.720281 0.086926 0.659618 0.506121 1.223380 0.532087 -0.052967 ... 0.344599 0.341567 0.788955 0.371867 0.736098 0.428859 0.097702 1.387938 1.459649 0.024612
1 0.167246 0.235707 0.410976 1.606847 -0.092984 0.588055 0.294228 0.287905 0.173410 0.095332 ... 0.238556 0.518189 0.904692 0.594319 0.255907 0.649954 -0.161035 1.129329 2.164186 -0.095347
2 0.116648 0.023022 0.573673 1.194594 -0.182040 0.274724 0.360759 0.835169 0.386440 0.195884 ... 0.260969 0.274048 0.003042 0.705658 0.855403 -0.148950 0.365262 0.557554 0.897666 -0.214390
3 -0.089305 -0.077612 1.278619 0.093136 0.230158 0.282165 0.328338 0.179623 0.142146 0.525852 ... 0.099366 0.828092 -0.091061 0.429793 1.589177 0.433834 0.150853 0.691185 1.510969 0.236520
4 0.080721 -0.099458 1.107285 1.371158 -0.075188 0.561217 0.068708 -0.115517 0.950087 -0.186310 ... 1.312183 0.245219 0.677794 0.923300 0.814625 0.666127 0.496661 0.584851 1.733792 0.129834
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
278 -0.037663 0.055256 0.163862 0.802016 -0.133472 0.754452 -0.093076 1.248724 0.064371 -0.033280 ... -0.045533 0.168447 -0.032779 0.765886 0.194452 0.168160 0.379251 0.764010 0.034106 -0.067038
279 0.451984 0.522794 0.428441 1.282936 -0.109883 0.115250 0.720206 0.889436 0.035240 0.544038 ... 0.382850 0.602043 1.171747 1.853520 1.009478 0.506671 0.277902 1.498777 0.889843 0.051304
280 -0.083468 0.035552 0.284779 1.037745 -0.165024 -0.038161 0.590095 0.936090 0.010201 -0.024314 ... 0.255000 0.338436 0.832437 1.219927 1.137342 -0.189758 0.143398 0.396132 0.070935 -0.030583
281 1.023939 0.330895 0.448363 1.128224 0.037620 0.697102 1.050354 0.364351 0.221893 0.055687 ... -0.110054 0.928107 0.772166 0.466907 1.274941 0.275639 0.204165 1.331395 1.156334 -0.022983
282 0.028079 0.110493 -0.079782 2.461003 -0.094052 -0.007144 0.624308 0.387399 0.201818 0.936201 ... -0.140741 0.122371 1.638356 1.279141 -0.001683 -0.006713 0.224180 1.166102 -0.216662 0.294658

283 rows × 576 columns

Inspect: Each row is an image; each column is a learned feature, not a food probability.

Reveal explanation: what learns from which data?

The CNN learned from ImageNet and stays fixed here. Image preprocessing is fixed by its weights. The scaler learns feature means and scales, and logistic regression learns coefficients, from food training examples. Frozen deterministic features can be extracted once before CV because this step learns nothing from our food images. Scaling must be fitted separately inside each CV fold.

2.3. Compare representations with cross-validation

For a simple alternative, resize each image to 16 × 16 RGB pixels and flatten it into 768 values. Compare this representation with the 576 pretrained features using the same StandardScaler → LogisticRegression pipeline, C=1, and five stratified folds.

Predict: Would perfect training accuracy prove that a representation generalizes well?

def pixel_features(dataset):
    """Return fixed low-resolution pixels in ImageFolder order."""
    rows = []
    for image, _ in dataset:
        small_image = image.convert("RGB").resize((16, 16), Image.Resampling.BILINEAR)
        rows.append(np.asarray(small_image, dtype=np.float32).ravel() / 255.0)
    return np.stack(rows)


def new_pipeline(C=1.0):
    return make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=3000))


X_pixels_train = pixel_features(food_train)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=RANDOM_STATE)
models_to_compare = {
    "Most-frequent baseline": (DummyClassifier(strategy="most_frequent"), Z_train),
    "Pixels + logistic regression": (new_pipeline(), X_pixels_train),
    "Pretrained features + logistic regression": (new_pipeline(), Z_train),
}
comparison = {}
for name, (model, features) in models_to_compare.items():
    scores = pd.DataFrame(cross_validate(
        model, features, y_train, cv=cv, scoring="accuracy",
        return_train_score=True, n_jobs=1,
    ))
    comparison[name] = {
        "mean training accuracy": scores.train_score.mean(),
        "mean CV accuracy": scores.test_score.mean(),
        "std CV accuracy": scores.test_score.std(),
    }
display(pd.DataFrame(comparison).T.round(3))
mean training accuracy mean CV accuracy std CV accuracy
Most-frequent baseline 0.152 0.152 0.011
Pixels + logistic regression 1.000 0.339 0.040
Pretrained features + logistic regression 1.000 0.845 0.071

Inspect: Compare mean CV accuracy with the dummy baseline and examine training–CV gaps. Resolve convergence warnings before interpreting the scores.

Reveal explanation: reading the table

High training accuracy can coexist with poor generalization. CV accuracy evaluates held-out training folds; its standard deviation describes variation across those folds, not a confidence interval. cross_validate’s test_score refers to CV folds, not the reserved final set. This compares two particular representations and preprocessing choices, not every possible pixel-based model.

2.4. Select regularization using training folds only

Smaller C means stronger regularization. Reuse the extracted features and tune only the sklearn pipeline. Keep the scaler inside the pipeline so each fold fits its own means and scales.

Predict: As C increases, must CV accuracy increase along with training accuracy?

search = GridSearchCV(
    new_pipeline(), {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10, 100]},
    cv=cv, scoring="accuracy", return_train_score=True, refit=True, n_jobs=1,
)
search.fit(Z_train, y_train)
grid_results = pd.DataFrame(search.cv_results_)
display(grid_results.sort_values("rank_test_score")[[
    "param_logisticregression__C", "mean_train_score", "mean_test_score",
    "std_test_score", "mean_fit_time", "rank_test_score",
]])
ax = grid_results.plot(
    x="param_logisticregression__C", y=["mean_train_score", "mean_test_score"],
    logx=True, marker="o",
)
ax.set(xlabel="C (larger means weaker regularization)", ylabel="Accuracy",
       title="Training and five-fold CV accuracy")
plt.show()
best_C = float(search.best_params_["logisticregression__C"])
best_model = search.best_estimator_
print("Selected C:", best_C)
print("Selected mean CV accuracy:", search.best_score_)
param_logisticregression__C mean_train_score mean_test_score std_test_score mean_fit_time rank_test_score
1 0.010 1.000000 0.866040 0.038661 0.005847 1
2 0.100 1.000000 0.862594 0.050705 0.005618 2
0 0.001 0.956719 0.858835 0.028654 0.004999 3
3 1.000 1.000000 0.844987 0.063475 0.004802 4
4 10.000 1.000000 0.841479 0.067790 0.002515 5
5 100.000 1.000000 0.834461 0.075951 0.002553 6

Selected C: 0.01
Selected mean CV accuracy: 0.8660401002506266

Discuss: Does increasing C help held-out folds, mainly help training accuracy, or neither?

Reveal explanation: refitting and leakage

refit=True fits the selected scaler and classifier afresh on all training feature rows. The highest CV score helped select C, so it is not an independent final estimate. Fitting StandardScaler before CV would expose held-out folds through their means and scales. Fine-tuning the CNN on all training images before CV would also expose held-out folds to learned weights; our frozen extractor does not do that.

2.5. Evaluate the selected model on reserved images

Model selection is complete. Now use the existing valid/ folder as the final holdout, without further tuning. Extract its features with the same frozen model and preprocessing. No new fit call is needed.

Predict: Could high overall accuracy hide a food category with poor recall?

Z_valid, y_valid = extract_features(feature_model, make_loader("valid"), DEVICE)
np.testing.assert_array_equal(y_valid, food_valid.targets)
valid_predictions = best_model.predict(Z_valid)
print("Selected mean CV accuracy:", search.best_score_)
print("Final held-out accuracy:", best_model.score(Z_valid, y_valid))
print(classification_report(
    y_valid, valid_predictions, labels=np.arange(len(class_names)),
    target_names=class_names, zero_division=0,
))
fig, ax = plt.subplots(figsize=(8, 7))
ConfusionMatrixDisplay.from_predictions(
    y_valid, valid_predictions, labels=np.arange(len(class_names)),
    display_labels=[name.replace("_", " ") for name in class_names],
    xticks_rotation=45, ax=ax, colorbar=False,
)
ax.set_title("Final held-out confusion matrix")
plt.tight_layout()
plt.show()
Selected mean CV accuracy: 0.8660401002506266
Final held-out accuracy: 0.8805970149253731
                precision    recall  f1-score   support

    beet_salad       0.90      0.90      0.90        10
chocolate_cake       0.90      1.00      0.95         9
       edamame       1.00      0.90      0.95        10
  french_fries       0.89      0.80      0.84        10
         pizza       0.83      1.00      0.91        10
  spring_rolls       0.78      0.78      0.78         9
         sushi       0.88      0.78      0.82         9

      accuracy                           0.88        67
     macro avg       0.88      0.88      0.88        67
  weighted avg       0.88      0.88      0.88        67

valid_predictions = best_model.predict(Z_valid)
error_indices = np.flatnonzero(valid_predictions != y_valid)[:5]
if len(error_indices):
    fig, axes = plt.subplots(1, len(error_indices), figsize=(4 * len(error_indices), 4), squeeze=False)
    for ax, index in zip(axes.flat, error_indices):
        image_path, _ = food_valid.samples[index]
        ax.imshow(Image.open(image_path).convert("RGB"))
        ax.set_title(f"True: {class_names[y_valid[index]]}\nPredicted: {class_names[valid_predictions[index]]}")
        ax.axis("off")
    plt.tight_layout()
else:
    print("No validation mistakes; a small validation set still leaves uncertainty.")

Inspect: Identify two observations supported by the confusion matrix and displayed errors. Visual similarity may suggest an explanation, but does not prove which cues the model used.

Do not tune again using these results. If we use these images to change the workflow, they become development data and we need a fresh test set. A small holdout also leaves uncertainty about performance on new photographs.

2.6. Predict one image using the same workflow

Apply the same image transform, frozen extractor, and fitted pipeline. Do not fit a scaler to the incoming image.

Predict: What will this seven-class model do if we give it a photograph of a bicycle?

def predict_food(image_path):
    image = Image.open(image_path).convert("RGB")
    inputs = imagenet_preprocess(image).unsqueeze(0).to(DEVICE)
    with torch.inference_mode():
        features = feature_model(inputs).cpu().numpy()
    label_index = int(best_model.predict(features)[0])
    return class_names[label_index]


# Demonstrate on a held-out validation image; replace this path for a new photo.
example_path, true_index = food_valid.samples[0]
predicted_label = predict_food(example_path)
plt.figure(figsize=(5, 5))
plt.imshow(Image.open(example_path).convert("RGB"))
plt.title(f"True: {class_names[true_index]}\nPredicted: {predicted_label}")
plt.axis("off");
assert predicted_label == class_names[int(valid_predictions[0])]

Reveal explanation: predictions and unfamiliar images

The classifier always chooses one of its seven food labels, even for a bicycle. A single prediction demonstrates the workflow; it does not measure deployment accuracy. New lighting, backgrounds, mixed dishes, and unfamiliar categories can reduce performance. High confidence alone does not establish that an image belongs to a known class.

2.7. Check your interpretation

Select all statements that are true:

  • A. The CNN learns new weights when we call extract_features.
  • B. Frozen deterministic features can be reused across CV folds and different values of C.
  • C. Scaling all food features before CV gives the same leakage protection as using a pipeline.
  • D. best_model has been refitted on all training features by GridSearchCV.
  • E. Changing image preprocessing requires extracting features again.
Reveal answers

B, D, and E. The CNN stays frozen. Scaling learns from the supplied rows, so it must remain inside the CV pipeline. Changing C requires refitting the scaler/classifier pipeline but no new CNN inference. Changing the CNN weights or image preprocessing requires recomputing features.

2.8. Connection to HW7

Demo step HW7 application
Read food folders and check label mapping Load cleaned waste images and make a stratified train/test split
Extract 576 frozen MobileNet features in order Preserve feature/target alignment with the supplied index-based loaders
Compare dummy, pixels, and CNN features on identical folds Interpret CV means, variation, and training–CV gaps
Tune C with scaling inside the pipeline Select and refit using training data only
Evaluate the reserved folder once Report final test metrics, inspect mistakes, and assess application limits
Repeat the prediction workflow for one image Apply the same transforms, extractor, and fitted pipeline to a new photograph

Discuss: Would these results justify using the food model to identify allergens? What evidence would be missing?

Our labels describe food categories, not ingredients or allergen safety. Evaluate the task actually required, including unfamiliar images and realistic collection conditions. HW7 similarly asks whether recognizing material categories is enough to recommend waste-sorting deployment.

3. Fine-tune the pretrained model

Fine-tuning replaces the original classifier and updates some or all of the pretrained CNN weights on labeled examples from the new task, usually with a small learning rate to preserve useful learned features. Unlike frozen feature extraction, it requires training the CNN within each training split and recomputing features as weights change; use validation data to choose settings and keep a final test set untouched.