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
| Resource | Link |
|---|---|
| Previous | Text & embeddings |
| Next | Transfer learning capstone |
| Prerequisites | CNNs 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:
| Strategy | What you do | Data needed | Risk |
|---|---|---|---|
| Feature extraction | Freeze pretrained layers; train new head only | Less | Underfit if task very different |
| Fine-tuning | Unfreeze top layers; small learning rate | More | Overfit 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:
weights="imagenet"— download pretrained weights (first run needs internet)include_top=False— remove original 1000-class headbase.trainable = False— freeze convolutional blockspreprocess_input— MobileNet-specific scaling- New head — your 10 Indian craft categories
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:
- Separate studio vs seller-uploaded photos in validation if possible
- Augment for varied backgrounds (market stall vs white backdrop)
- Watch class imbalance — oversample rare categories
Transfer learning for text (preview)
Same idea for NLP:
| Vision | Text |
|---|---|
| MobileNetV2, ResNet50 | BERT, DistilBERT |
| ImageNet weights | Wikipedia + books pretraining |
| Replace classifier head | Fine-tune on your tickets |
Details in capstone when comparing DL vs classical ML.
Model choice table
| Backbone | Size | Speed | Use case |
|---|---|---|---|
| MobileNetV2 | Small | Fast mobile | Seller app on phone |
| EfficientNetB0 | Medium | Balanced | Web catalog |
| ResNet50 | Larger | Slower | Maximum accuracy, server GPU |
Essential commands
| Command / action | What it does |
|---|---|
applications.MobileNetV2(weights="imagenet") | Pretrained CNN |
base.trainable = False | Freeze for feature extraction |
GlobalAveragePooling2D() | Pool spatial features |
image_dataset_from_directory | Load folder-labelled images |
Low learning_rate when fine-tuning | Protect 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 = Falsethen selective unfreeze - [ ] Smaller learning rate for fine-tuning
- [ ] Next: Transfer learning capstone