Source

Module 8 · MobileNetV2 and transfer learning: TrayCheck's model, line by line

Time: about 6 hours with readings · Lab: python course/labs/lab08_mobilenet.py (needs TensorFlow)

You need: Module 1 §5 (transfer learning in outline), Module 6 (learning rates, augmentation, dropout, early stopping) and Module 7 (convolutions, batch normalisation, MobileNetV2's blocks).

By the end you can:

  • explain transfer learning and why it works with only 400 training photos;
  • explain feature extraction vs fine-tuning, and why TrayCheck does both in that order;
  • explain the batch-normalisation trap in fine-tuning and how TrayCheck avoids it;
  • walk through vision_train.py and food_model.py line by line;
  • justify the choice of MobileNetV2, and name realistic alternatives.

Why this matters in TrayCheck

This is the module the interview will probe hardest. "How did you train it?" deserves a precise answer: "A MobileNetV2 pre-trained on ImageNet, with a new head trained first while the backbone was frozen, then the last 20 layers fine-tuned at a low learning rate with batch-norm frozen."

Why this matters for the internship

Almost every commercial food-recognition model is built this way: a large pre-trained network, adapted to food with a much smaller dataset. Knowing how transfer learning works tells you what to ask the vendor:

  • What was it pre-trained on, and what was it fine-tuned on? Generic food photos, other hospitals' trays, or this site's? The further the fine-tuning data is from your trays (crockery, lighting, camera angle, texture-modified meals), the bigger the risk that accuracy drops here.
  • Will it be fine-tuned on this site's photos during the PoC? If so, the model changes mid-pilot: results before and after must be reported separately (Module 12 §3, model versioning), and the test trays must never be used for the fine-tuning (Module 9 §4, leakage).
  • How many local examples does it need per dish? Transfer learning reduces this from hundreds of thousands to hundreds, as TrayCheck's 100 per dish shows, but not to zero. A new menu item needs labelled photos before it can be recognised at all.

1. Transfer learning: borrowing what another model learned

Training MobileNetV2's 2.26 million backbone parameters from scratch would need hundreds of thousands of labelled photos. TrayCheck has 400. Transfer learning reuses a network trained on a huge dataset as the starting point for a new task.

The source here is ImageNet: about 1.28 million training photos in 1,000 categories. A network trained on it learns general visual features: edges, colours, textures, shapes and object parts. They turn out to be useful far beyond those 1,000 categories.

Why it works. Think about what each layer needs to know (Module 1 §5). An edge detector or a "glossy surface" texture detector is useful for recognising almost anything, so the early layers learned on ImageNet are already right for food. The final layers are the opposite: they combine parts into ImageNet's particular 1,000 categories ("golden retriever", "fire truck"), which TrayCheck doesn't need. Researchers have measured this directly: features from early layers transfer well to new tasks, and the further up the network, the more specific to the original task they become. They also found that networks that do better on ImageNet tend to transfer better. Hence the standard recipe: keep the general early layers, replace the task-specific end, and adapt the last few layers.

Two ways to transfer

Approach What's trained When
Feature extraction Only a new head; the backbone is frozen Little data; new task similar to the source
Fine-tuning The new head plus some top backbone layers, at a low learning rate A bit more data, or the new task differs more

TrayCheck does both, in order. A randomly initialised head produces large, essentially random gradients at first. If the backbone were unfrozen then, those gradients would wreck its pre-trained features. So stage 1 trains only the head; stage 2, with the head already sensible, gently fine-tunes the top of the backbone. This head-first sequence is the standard recipe.


2. vision_train.py, line by line

Loading data

tf.keras.utils.image_dataset_from_directory(DATA / name, labels="inferred", label_mode="int",
    batch_size=32, image_size=(96, 96), shuffle=shuffle, seed=SEED)
ds.cache().prefetch(tf.data.AUTOTUNE)
  • Labels come from folder names (train/bibimbap/…), sorted alphabetically: 0 = baby_back_ribs, 1 = beet_salad, 2 = bibimbap, 3 = bread_pudding.
  • Every photo is resized to 96 × 96 with bilinear resizing (each new pixel is a distance-weighted average of the four nearest original pixels); food_model.py uses the same resize at prediction time. Training/serving skew, where preprocessing differs between training and use, is a classic silent bug (Module 12).
  • cache() keeps decoded images in memory after the first epoch, so photos aren't re-read from disk; prefetch prepares the next batch while the current one trains.

Building the model

backbone = tf.keras.applications.MobileNetV2(input_shape=(96, 96, 3), alpha=1.0,
                                             include_top=False, weights="imagenet", pooling="avg")
backbone.trainable = False
inputs = tf.keras.Input(shape=(96, 96, 3), name="food_image")
x = tf.keras.layers.RandomFlip("horizontal", seed=SEED)(inputs)          # augmentation (Module 6)
x = tf.keras.layers.RandomRotation(.05, seed=SEED)(x)                     # up to ±18°
x = tf.keras.applications.mobilenet_v2.preprocess_input(x)                # 0..255 → -1..1
x = backbone(x, training=False)                                           # keep BN in inference mode
x = tf.keras.layers.Dense(96, activation="relu")(x)
x = tf.keras.layers.Dropout(.25)(x)
output = tf.keras.layers.Dense(class_count, activation="softmax", name="food_class")(x)
Argument Meaning
include_top=False Drop ImageNet's own 1,000-class classifier
weights="imagenet" Start from the pre-trained weights
pooling="avg" Global average pooling: the 3 × 3 × 1280 map becomes a 1280-vector
alpha=1.0 Width multiplier: 1.0 is the standard width; 0.35–0.75 are thinner and faster
input_shape=(96, 96, 3) One of the input sizes Keras provides ImageNet weights for (96, 128, 160, 192, 224). Smaller is faster but sees less detail
preprocess_input Scales pixels as during pre-training: x / 127.5 − 1. Getting this wrong silently ruins transfer learning

Lab 8 confirms the preprocessing (0.0 to 255.0 becomes -1.000 to 1.000) and rebuilds a prediction by hand as backbone → dense → dropout (off) → softmax layer, matching the app's score_image to within 2.4 × 10⁻¹¹.

Stage 1: train the head

compile_model(model, 5e-4)       # Adam, sparse_categorical_crossentropy, accuracy
model.fit(train, epochs=12, validation_data=val,
          callbacks=[EarlyStopping(monitor="val_loss", patience=3, restore_best_weights=True)])

It ran 9 epochs and kept epoch 6's weights (Module 6).

Stage 2: fine-tune the top of the backbone

backbone.trainable = True
for layer in backbone.layers[:-20]:
    layer.trainable = False                       # freeze all but the last 20 layers
for layer in backbone.layers:
    if isinstance(layer, tf.keras.layers.BatchNormalization):
        layer.trainable = False                   # keep every BN layer frozen
compile_model(model, 1e-5)                        # re-compile so the change takes effect; 50x smaller lr
model.fit(train, epochs=6, ..., EarlyStopping(monitor="val_loss", patience=2, ...))

Lab 8 shows which backbone layers actually ended up with trainable weights:

['block_15_depthwise', 'block_15_project', 'block_16_expand', 'block_16_depthwise', 'block_16_project', 'Conv_1']

"The last 20 layers" includes BN, ReLU and Add layers, which have no weights to train or are frozen. So fine-tuning really adjusts six convolution layers at the very top. In total 1,164,644 of the 2,381,348 parameters are trainable: those six layers (about 1.04 M) plus the head (123,364).

The batch-normalisation trap

If BN layers were unfrozen and run in training mode during fine-tuning, they would recompute statistics from small batches of 32 food photos and overwrite the ImageNet statistics everything downstream depends on: every later layer learned to expect inputs standardised with ImageNet's averages (Module 7 §4), and would suddenly receive differently scaled ones. Accuracy can collapse. TrayCheck guards against it twice: every BN layer is frozen, and the backbone is always called with training=False. This is a well-known pitfall of fine-tuning.

Testing once, at the end

After both stages the script reads the test photos for the first time, computes accuracy, macro F1 and the confusion matrix, and writes vision/metrics.json and held_out_predictions.csv. vision_score.py later re-scores the same photos and asserts that its predictions match, to guard against preprocessing drift.


3. food_model.py: using the model in the app

image = tf.io.decode_image(contents, channels=3, expand_animations=False)
image = tf.image.resize(image, IMAGE_SIZE, method="bilinear")       # same as training
scores = model.predict(np.expand_dims(image.numpy(), 0), verbose=0)[0]
  • No explicit preprocess_input: it's inside the saved model, so the app can't forget it.
  • np.expand_dims(…, 0) adds the batch dimension: (96, 96, 3) → (1, 96, 96, 3).
  • model.predict runs in inference mode: no augmentation, no dropout, BN uses stored statistics. Lab 8 shows the difference on the less certain beet-salad photo (the training-mode numbers are random, so yours will differ run to run):
training=True,  run 1: [0.038  0.109  0.853  0.0001]   ← random flip/rotation + dropout
training=True,  run 2: [0.0315 0.9272 0.0408 0.0005]   ← this random flip made it right!
training=False, run 1: [0.0089 0.0347 0.9564 0.    ]   ← what the app uses: deterministic
training=False, run 2: [0.0089 0.0347 0.9564 0.    ]

Its confident "bibimbap" answer flips to the correct "beet salad" under one random flip and rotation, a hint that this mistake is fragile. Averaging predictions over a few flipped copies (test-time augmentation) is one of the extension ideas in Module 14.

  • model_version() hashes the model file, so every saved record knows which model produced it.

What the network "sees": embeddings

The 1280-number vector the backbone produces is an embedding: photos that look alike to the network get similar vectors.

To measure "similar", compare directions rather than sizes. The cosine similarity of two vectors is their dot product divided by the product of their lengths (a vector's length is the square root of the sum of its squared entries):

\[\cos(a, b) = \frac{a \cdot b}{\lVert a \rVert\,\lVert b \rVert}\]

It is 1 when the vectors point the same way, 0 when they share nothing, and it ignores overall size. Example with three numbers: a = [1, 2, 0], b = [2, 1, 1]. Dot product 1×2 + 2×1 + 0×1 = 4; lengths √5 = 2.24 and √6 = 2.45; cosine 4 / (2.24 × 2.45) = 0.73. Lab 8 computes this between the six example photos' 1280-number embeddings. Both confident mistakes are closest to the bibimbap example, the dish the model wrongly predicted for each:

Nearest neighbour of baby_back_/2134746 (a confident mistake): bibimbap/2425339 (0.44)
Nearest neighbour of beet_salad/1990111 (a confident mistake): bibimbap/2425339 (0.54)

The mistakes are understandable: the ribs photo has a large mound of rice; the salad has rice-like and egg-like colours. Embeddings also power similarity search and duplicate detection (Module 9).


4. Why MobileNetV2, and what else could work

Model Parameters (ImageNet, full) Why you might choose it
MobileNetV2 (chosen) ~3.5 M Small, fast on CPU, well supported in Keras, good transfer performance
EfficientNet-B0 ~5.3 M Usually more accurate per parameter; a bit slower
ResNet-50 ~25.6 M Strong, classic baseline; much heavier
Vision Transformer (ViT-B/16) ~86 M Excellent with lots of data and compute; overkill here

(MobileNetV2 is ~3.5 M with its 1,000-class top; TrayCheck's headless version is 2.26 M.)

The honest justification: CPU-only laptop, 400 training photos, an existing project built on it, and accuracy that's good enough for a demo of a review workflow. With more time, the first experiments would be EfficientNet-B0, a larger input size (128 or 160), and more photos per class.


Check your understanding

1. Why train the head first with the backbone frozen, instead of fine-tuning everything from the start?

A randomly initialised head sends large, noisy gradients backwards. If the backbone were trainable then, those gradients would damage its pre-trained features before the head had learned anything useful.

2. What would happen if you forgot preprocess_input?

The backbone would receive pixels in 0..255 instead of −1..1, a distribution it never saw during pre-training. The features would be garbage and accuracy would collapse, often without any error message.

3. vision_train.py unfreezes "the last 20 layers", yet only 6 backbone layers have trainable weights. Why?

Many of those 20 layers have no weights (ReLU, Add) or are deliberately kept frozen (batch normalisation). Only the convolution layers among them are actually updated.

4. Why does calling the backbone with training=False matter even when its BN layers are frozen?

In Keras, training=False makes BN use its stored running statistics instead of the current batch's statistics. Freezing (trainable=False) stops weights updating; training=False controls which statistics are used in the forward pass. TrayCheck sets both, so BN stays exactly as pre-trained.

5. Give two cheap experiments that might improve accuracy, and how you'd evaluate them fairly.

For example: a larger input size (128 or 160), EfficientNet-B0 as the backbone, test-time augmentation, or more training photos per dish. Compare candidates on the validation set only, pick one, then measure it once on the test set.


Go deeper

Short on time or new to this? The study guide says exactly which of these to read first.

Core

  • Keras guide, Transfer learning & fine-tuning (François Chollet): keras.io/guides/transfer_learning. TrayCheck's two-stage recipe and the batch-norm advice come straight from it.
  • Deep Learning with Python, 3rd ed. (Chollet & Watson), free at deeplearningwithpython.io: the chapter on image classification (data augmentation, feature extraction with a pre-trained model, fine-tuning), then the chapter on convnet architecture patterns (residual connections, batch normalization, depthwise separable convolutions).
  • Stanford CS231n notes, Transfer Learning (cs231n.github.io/transfer-learning): when to fine-tune and how much.

Optional

  • fast.ai, Practical Deep Learning for Coders, Lesson 1: a working transfer-learning image classifier in a few lines, with practical advice. course.fast.ai
  • Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow, 3rd ed. (Géron), Chapter 14, Deep Computer Vision Using CNNs, the sections on using pretrained models for transfer learning.
  • Dive into Deep Learning, chapter Computer Vision: Image Augmentation and Fine-Tuning.
  • TensorFlow guide, tf.data: Build TensorFlow input pipelines (cache, prefetch).
  • Papers: Sandler et al., MobileNetV2, CVPR 2018; Yosinski et al., NeurIPS 2014; Kornblith et al., Do Better ImageNet Models Transfer Better?, CVPR 2019; Russakovsky et al., ImageNet Large Scale Visual Recognition Challenge, IJCV 2015.

Interview angle

"It's transfer learning. MobileNetV2's ImageNet weights already encode general visual features, so with 400 photos I train a new head with the backbone frozen, then fine-tune the top six convolution layers at 1e-5 with batch norm frozen and the backbone in inference mode. That last part avoids small food batches overwriting the ImageNet statistics. Preprocessing lives inside the saved model, so the app can't apply it differently from training."