Transfer learning reuses a model trained on a huge dataset (such as ImageNet’s 1.2 million images, or the web text behind an LLM) as the starting point for your own task. You get strong results with a few hundred examples and minutes of training instead of weeks.
What You Will Learn
- Why pre-trained features transfer
- Feature extraction vs fine-tuning
- Keras image-classification example
- PyTorch example
- Transfer learning in NLP and LLMs
Prerequisites
Why It Works
Early layers of a CNN learn general patterns – edges, colours, textures – that are useful for almost any image. Later layers learn task-specific combinations. We keep the general layers and replace or retrain only the top.
Two Approaches
| Feature extraction | Fine-tuning | |
|---|---|---|
| Pre-trained layers | Frozen | Some or all unfrozen |
| Trainable part | New classification head only | Head + top layers |
| Learning rate | Normal (e.g. 1e-3) | Very small (e.g. 1e-5) |
| Data needed | Small (hundreds) | More (thousands) |
| Risk | Lower accuracy if domain differs | Overfitting / destroying features if lr too high |
Keras: Classify Your Own Images
from tensorflow import keras
train = keras.utils.image_dataset_from_directory("data/train", image_size=(224, 224), batch_size=32)
val = keras.utils.image_dataset_from_directory("data/val", image_size=(224, 224), batch_size=32)
base = keras.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights="imagenet")
base.trainable = False # 1) feature extraction
inputs = keras.Input(shape=(224, 224, 3))
x = keras.layers.RandomFlip("horizontal")(inputs) # light augmentation
x = keras.applications.mobilenet_v2.preprocess_input(x)
x = base(x, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.2)(x)
outputs = keras.layers.Dense(len(train.class_names), activation="softmax")(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(train, validation_data=val, epochs=5)
base.trainable = True # 2) fine-tune the top layers
for layer in base.layers[:-30]:
layer.trainable = False
model.compile(optimizer=keras.optimizers.Adam(1e-5), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(train, validation_data=val, epochs=5)
Explanation: Folder names become class labels (data/train/cats, data/train/dogs…). include_top=False removes ImageNet’s 1000-class layer. Phase 1 trains only the new head; phase 2 unfreezes the last 30 layers with a tiny learning rate. Re-compile after changing trainable. Keep training=False on the base so BatchNorm statistics are not disturbed.
PyTorch Version
import torch, torch.nn as nn
from torchvision import models
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for p in model.parameters():
p.requires_grad = False # freeze
model.fc = nn.Linear(model.fc.in_features, 3) # new head for 3 classes (trainable)
optimizer = torch.optim.Adam(model.fc.parameters(), lr=1e-3)
Popular Pre-trained Models
| Domain | Models | Where |
|---|---|---|
| Images | ResNet, EfficientNet, MobileNet, ConvNeXt, ViT | keras.applications, torchvision, timm |
| Text | BERT, RoBERTa, DistilBERT | Hugging Face – see Hugging Face |
| LLMs | Llama, Mistral, Gemma | Fine-tune with LoRA – see Fine-Tuning LLMs |
| Audio | Whisper, wav2vec 2.0 | Hugging Face |
| Vision-language | CLIP | Zero-shot image classification |
Series
Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow
Interview Questions
Q: What is transfer learning?
Reusing a model trained on a large dataset as the starting point for a related task.
Q: Feature extraction vs fine-tuning?
Feature extraction freezes the pre-trained layers and trains a new head; fine-tuning also updates some pre-trained layers with a small learning rate.
Q: Why use a small learning rate when fine-tuning?
Large updates would destroy the useful pre-trained features.
Practice Exercises
- Train the Keras example on 3 classes of your own photos (100 images each).
- Compare MobileNetV2 and EfficientNetB0 accuracy and training time.
Summary
Start from a pre-trained model, freeze it and train a new head, then optionally fine-tune top layers with a tiny learning rate. It is the default approach for vision, NLP and LLM projects with limited data.
Next: Autoencoders · Fine-Tuning LLMs
Machine Learning Tutorials, Courses and Certifications