Monday , November 30 2026
Transfer learning explained: feature extraction vs fine-tuning, a Keras MobileNetV2 image classifier, a PyTorch ResNet example and pre-trained models for NLP and LLMs.

Transfer Learning in Deep Learning (Keras and PyTorch)

Updated: 29 November 2026Level: IntermediateReading time: about 9 minutesKeras · PyTorch · Hugging Face

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

Introduction to CNN.

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

Keras (not run here – needs TensorFlow and your image folders)
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

PyTorch (not run here)
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
Note: If your images are very different from ImageNet (X-rays, satellite, microscopy), fine-tune more layers or use a domain-specific pre-trained model.

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

  1. Train the Keras example on 3 classes of your own photos (100 images each).
  2. 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

About Machine Learning

Check Also

Generative Adversarial Networks (GANs) Explained with PyTorch

GANs explained: generator vs discriminator, the adversarial training loop in PyTorch, mode collapse and fixes, GAN variants and GANs vs diffusion models.