Rana Maninder Singh
Lesson 7 of 8Deep Learning

Transfer Learning — Standing on Giant Shoulders

Lesson opener

In one line: What transfer learning is - reuse pretrained weights on your smaller dataset.

Why it matters: Low data + high accuracy = reuse pretrained features.

Before this lesson: CNNs introduction / First Keras model

Before you start

ResourceLink
PreviousText & embeddings
NextTransfer learning capstone
PrerequisitesCNNs introduction, First Keras model
Time~55 minutes

What you will learn

  • What transfer learning is — reuse pretrained weights on your smaller dataset
  • Feature extraction vs fine-tuning — when to freeze layers
  • ImageNet-pretrained CNNs for Indian product classification
  • Practical Keras workflow with tensorflow.keras.applications

Why train from scratch rarely makes sense on images

The problem it solves: Your Ahmedabad handicraft marketplace has 2,000 labelled photos across 10 categories. Training a CNN from random weights needs millions of images. Transfer learning starts from a network already trained on ImageNet (1M+ general photos) — edges, textures, shapes already learned.

WHY Low data + high accuracy = reuse pretrained features.

WHEN Image classification with hundreds to tens of thousands of labelled photos — not 20 icons.

Two strategies:

StrategyWhat you doData neededRisk
Feature extractionFreeze pretrained layers; train new head onlyLessUnderfit if task very different
Fine-tuningUnfreeze top layers; small learning rateMoreOverfit if data tiny

Keras applications — pretrained backbones

from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input

IMG_SIZE = 160
base = MobileNetV2(
    input_shape=(IMG_SIZE, IMG_SIZE, 3),
    include_top=False,
    weights="imagenet",
)
base.trainable = False  # feature extraction mode

model = keras.Sequential([
    layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3)),
    layers.Lambda(preprocess_input),
    base,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation="relu"),
    layers.Dropout(0.3),
    layers.Dense(10, activation="softmax"),  # 10 product categories
])

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=0.001),
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)

Breaking it down:

Use this when: catalog has consistent product photos per category.


Simulated training loop — inline numpy images

import numpy as np

rng = np.random.default_rng(0)
n_train, n_val = 160, 40
X_train = rng.random((n_train, IMG_SIZE, IMG_SIZE, 3)).astype("float32")
y_train = rng.integers(0, 10, n_train)
X_val = rng.random((n_val, IMG_SIZE, IMG_SIZE, 3)).astype("float32")
y_val = rng.integers(0, 10, n_val)

history = model.fit(
    X_train, y_train,
    validation_data=(X_val, y_val),
    epochs=5,
    batch_size=16,
    verbose=1,
)

Replace random tensors with real image_dataset_from_directory when you have folders per class.


Fine-tuning — unfreeze top layers

After head trains with frozen base:

base.trainable = True
for layer in base.layers[:-20]:
    layer.trainable = False

model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-5),  # much smaller!
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=5)

WHY Lower learning rate prevents destroying pretrained weights in one epoch.

WHEN Feature extraction plateaus and you have ≥~1k images per class (rough guide).


Loading real image folders

train_ds = keras.utils.image_dataset_from_directory(
    "data/product_photos/train",
    image_size=(IMG_SIZE, IMG_SIZE),
    batch_size=32,
    label_mode="int",
)
# Apply augmentation:
augment = keras.Sequential([
    layers.RandomFlip("horizontal"),
    layers.RandomRotation(0.1),
])

Indian catalog tips:


Transfer learning for text (preview)

Same idea for NLP:

VisionText
MobileNetV2, ResNet50BERT, DistilBERT
ImageNet weightsWikipedia + books pretraining
Replace classifier headFine-tune on your tickets

Details in capstone when comparing DL vs classical ML.


Model choice table

BackboneSizeSpeedUse case
MobileNetV2SmallFast mobileSeller app on phone
EfficientNetB0MediumBalancedWeb catalog
ResNet50LargerSlowerMaximum accuracy, server GPU

Essential commands

Command / actionWhat it does
applications.MobileNetV2(weights="imagenet")Pretrained CNN
base.trainable = FalseFreeze for feature extraction
GlobalAveragePooling2D()Pool spatial features
image_dataset_from_directoryLoad folder-labelled images
Low learning_rate when fine-tuningProtect pretrained weights

Practice

Do this now: Build MobileNetV2 feature-extraction model for 10 classes. Train 5 epochs on synthetic or real images. List two reasons transfer learning beats training from scratch on a 2,000-image Indian catalog.

Checklist

  • [ ] Transfer learning defined — pretrained backbone + new head
  • [ ] Feature extraction vs fine-tuning distinguished
  • [ ] trainable = False then selective unfreeze
  • [ ] Smaller learning rate for fine-tuning
  • [ ] Next: Transfer learning capstone