🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Transfer Learning: Fine-tuning Pre-trained Models

Module 13: Computer VisionTransfer Learning🟢 Free Lesson

Advertisement

Transfer Learning: Fine-tuning Pre-trained Models

Transfer learning is one of the most powerful paradigms in modern deep learning. Instead of training networks from scratch — a process demanding millions of labeled images and weeks of GPU time — we repurpose knowledge encoded in models trained on massive datasets. This lecture covers the theory, mechanics, and practical strategies for applying transfer learning to real-world problems.


1. What is Transfer Learning?

Transfer learning is the practice of taking a model trained on one task (the source task) and adapting it to a different but related task (the target task).

1.1 Why Transfer Learning Works

Deep networks learn hierarchical representations. Early layers capture universal visual primitives — edges, textures, color gradients. Middle layers compose these into motifs: corners, contours, repeated patterns. Deeper layers encode task-specific semantics — object parts, faces, scenes.

This hierarchy exhibits a key property: lower layers are more general, higher layers are more specific. The same Gabor-like edge detectors useful for ImageNet classification are equally useful for medical image segmentation or satellite imagery analysis.

Formally, consider a source model \mathcal{D}_S = {(x_i^S, y_i^S)}\mathcal{D}_T = {(x_i^T, y_i^T)}\phi_S(x) shares structure with an optimal representation for the target task.

ℹ️

The key insight: natural images share statistical structure. A model that has learned to recognize 1,000 ImageNet classes has implicitly learned useful features for many other visual tasks.

1.2 The Taxonomy of Transfer

Transfer TypeSource → TargetExample
InductiveSame domain, different tasksImageNet → X-ray classification
UnsupervisedSame domain, no target labelsImageNet → feature extraction for clustering
Domain AdaptationDifferent domains, same taskSynthetic → real images for segmentation
Multi-taskShared features, multiple tasksSingle backbone for detection + depth

1.3 When Does Transfer Help?

The benefit of transfer depends on two factors:

\text{Transfer Gain} \propto \underbrace{\text{Task Similarity}(\mathcal{T}_S, \mathcal{T}T)}{\text{how related are the tasks?}} \times \underbrace{\frac{|\mathcal{D}_S|}{|\mathcal{D}T|}}{\text{data scarcity ratio}}

  • High similarity + small target dataset: Maximum benefit (e.g., ImageNet → CIFAR-10)
  • Low similarity + large target dataset: Transfer may hurt (negative transfer)
  • Any similarity + tiny dataset: Transfer is almost always beneficial

2. Pre-trained Models

2.1 ImageNet and the ILSVRC Benchmark

The ImageNet Large Scale Visual Recognition Challenge (ILSVRC) provided 1.28 million training images across 1,000 categories. This dataset catalyzed the deep learning revolution and remains the standard source for pre-trained visual features.

2.2 Architecture Evolution

Pre-trained Architecture EvolutionAlexNet2012 - 8 layers61M paramsTop-5: 16.4%VGG-162014 - 16 layers138M paramsTop-5: 7.3%ResNet-502015 - 50 layers25M paramsTop-5: 3.6%EfficientNet-B72019 - Compound scaling66M paramsTop-5: 1.3%Key Architectural InnovationsResidual Connections (ResNet)Skip connections: y = F(x) + xEnables training of very deep networksInverted Bottlenecks (EfficientNet)Compound scaling: depth x width x resolutionNAS-optimized architectureBatch NormalizationNormalizes layer inputs for stable trainingReduces internal covariate shiftSE Attention (EfficientNet)Squeeze-and-Excitation channel attentionAdaptive feature recalibration

2.3 Choosing a Pre-trained Model

ModelParametersTop-1 (ImageNet)Best For
ResNet-1811.7M69.8%Quick prototyping, edge deployment
ResNet-5025.6M76.1%Good balance of speed/accuracy
EfficientNet-B05.3M77.1%Mobile/embedded
EfficientNet-B419.3M82.9%General-purpose
EfficientNet-B766.3M84.3%Maximum accuracy
ConvNeXt-B89M83.8%Transformer-like performance
ViT-B/1686M77.9%Vision Transformer baseline

3. Feature Extraction vs. Fine-tuning

Feature Extraction vs. Fine-tuningFeature ExtractionPre-trained Backbone (FROZEN)Conv Layers 1-3: Edges, TexturesConv Layers 4-6: Patterns, PartsConv Layers 7-8: High-level FeaturesFC: ImageNet Classes (REMOVED)All layers frozen (no gradient update)New Classifier Head (TRAINABLE)Fast training | Low data | SimpleFine-tuningPre-trained Backbone (PARTIAL)Conv Layers 1-3: FrozenConv Layers 4-6: UnfrozenConv Layers 7-8: UnfrozenFC: ImageNet Classes (REMOVED)Upper layers updated with target dataNew Classifier Head (TRAINABLE)Higher accuracy | Moderate data | More compute

3.1 Feature Extraction

In feature extraction mode, the pre-trained backbone is treated as a fixed feature extractor. Only the newly added classification head is trained.

3.2 When to Use Each Approach

CriterionFeature ExtractionFine-tuning
Training dataLess than 1,000 imagesMore than 1,000 images
Domain similarityHigh (e.g., natural images)Low (e.g., medical, satellite)
Compute budgetLowHigh
Accuracy needModerateHigh
Training timeMinutes to hoursHours to days
Risk of overfittingLowModerate to high

4. Fine-tuning Strategies

Fine-tuning Strategies: Layer FreezingFull Fine-tuningAll layers: TrainableAll layers: TrainableAll layers: TrainableClassifier: TrainableMaximum flexibilityRisk of catastrophic forgettingRequires large datasetPartial Fine-tuningEarly layers: FrozenMiddle layers: FrozenLate layers: TrainableClassifier: TrainablePrevents overfittingGood for small-medium dataMust choose cutoff pointGradual UnfreezingStage 1: Classifier onlyStage 2: + Layer 4Stage 3: + Layer 3Stage 4: + Layer 2Stable trainingBest for very small dataSlower convergenceDecision GuideDataset size less than 500 images: Feature Extraction (frozen backbone)Dataset size 500-5000 images: Partial Fine-tuning or Gradual UnfreezingDataset size 5000+ images: Full Fine-tuning with differential learning ratesDomain mismatch between source and target: Gradual Unfreezing + Domain Adaptation

4.1 Full Fine-tuning

Unfreeze all layers and train the entire network. Use this when you have sufficient data and compute.

4.2 Partial Fine-tuning

Freeze early layers, fine-tune later layers. This is the most common practical approach.

4.3 Gradual Unfreezing

Start by training only the classifier, then progressively unfreeze deeper layers. Popularized by the ULMFiT paper for NLP.

4.4 Layer Freezing Visualization

The diagram below shows how gradients flow through frozen and unfrozen layers:


5. Learning Rate Differentiation

5.1 Differential Learning Rates

Lower layers encode universal features that already generalize well — they need only slight adjustment. Higher layers encode more task-specific features that need more substantial adaptation. Using a single learning rate for all layers is suboptimal.

where is the learning rate for layer , is the total number of layers, and is a decay factor (typically 0.1 to 0.5).

5.2 Practical Implementation

5.3 Learning Rate Scheduling

Combined with differential LRs, schedulers adapt rates during training:


6. Domain Adaptation

When source and target domains differ (e.g., synthetic vs. real images, daytime vs. nighttime), domain adaptation aligns feature distributions.

6.1 Transfer Learning Concept Diagram

Transfer Learning: Source to Target DomainSource DomainLarge labeled datasetImageNet (1.28M images)1,000 classesPre-trained modelRich feature representationsShared FeatureSpaceEdges, TexturesPatterns, ShapesSemantic PartsObject LevelDomain-invariant featuresTarget DomainSmall labeled datasetMedical ImagesSatellite ImageryIndustrial InspectionTask-specific adaptation

6.2 Maximum Mean Discrepancy (MMD)

Minimize the distance between source and target feature distributions:

where is a kernel-induced feature mapping, and are the number of source and target samples.

Intuition: If MMD is zero, the distributions are identical in the feature space. By minimizing MMD during training, we force the feature extractor to learn domain-invariant representations.

6.3 Adversarial Domain Adaptation

Train a domain discriminator to distinguish source vs. target features, while the feature extractor learns to fool it:

where is the feature generator, is the domain discriminator, and controls the trade-off.


7. Data Augmentation

Data augmentation is critical for transfer learning — it artificially expands small datasets and improves generalization.

7.1 Data Augmentation Examples

Data Augmentation Techniques[ ]Original224 x 224RGB[|]H-Flip (p=0.5)Mirror imageSymmetry-invariant[/]Rotate 15 degRotation invariance-15 to +15 deg[star]Color JitterBrightness, ContrastSaturation, Hue[#]Rand CropScale variationSize 0.8-1.0[_]CutoutRandom erasinghole size 16x16[~]Gaussian Blursigma 0.1-2.0Scale invariance[R]RandAugmentN ops, magnitude MAuto-selected ops[M]MixupBlend two imageslambda ~ Beta(0.2)[C]CutMixCut and paste regionBlend labels by area

7.2 Implementation with torchvision

7.3 Advanced Augmentation: Mixup and CutMix

These techniques create virtual training examples by blending existing ones:

Mixup:

CutMix: Cut a patch from image and paste it onto image . Labels are mixed proportionally to the area ratio.


8. Implementation in PyTorch

8.1 Complete Fine-tuning Pipeline

8.2 Gradual Unfreezing with ULMFiT-style Training

8.3 Model Export and Inference


9. Fine-tuning Strategies Comparison

Strategy ComparisonStrategyParams ChangedLR RangeBest Data SizeRiskFeature Extraction2-5% (head only)1e-3 to 1e-2100 - 1KLowPartial Fine-tuning15-40% (top layers)1e-5 to 1e-31K - 10KMediumGradual UnfreezingProgressive 5-100%1e-4 to 1e-3500 - 5KLowFull Fine-tuning100% (all layers)1e-5 to 1e-410K+HighFrom Scratch100% (random init)1e-3 to 1e-1100K+Very High

10. Common Pitfalls and Solutions

10.1 Catastrophic Forgetting

When fine-tuning erases source knowledge. Solutions: lower learning rates, freeze early layers, Elastic Weight Consolidation (EWC):

where is the Fisher information (importance) of parameter , and are optimal source parameters.

10.2 Negative Transfer

When source knowledge hurts target performance. Solutions: validate transfer benefits empirically; use similarity metrics to select source tasks.

10.3 Overfitting on Small Datasets

Solutions: strong augmentation, dropout, weight decay, early stopping, label smoothing.

10.4 Batch Normalization Issues

Frozen BN layers use source statistics, which may mismatch target data. Solution: use LayerNorm or train BN in eval mode with running statistics.


11. Key Takeaways

  • Feature extraction (frozen backbone) is the fastest and safest approach for small datasets (less than 1K images per class)
  • Fine-tuning with differential learning rates gives best results when data is sufficient; use smaller LR for pre-trained layers, larger LR for new layers
  • Progressive unfreezing prevents catastrophic forgetting and stabilizes training by gradually unfreezing layers from top to bottom
  • Domain adaptation (MMD, adversarial training) helps when source and target domains differ
  • EWC penalizes changes to important parameters using Fisher information, preserving source knowledge
  • Data augmentation (Mixup, CutMix, RandAugment) is essential for small datasets
  • Negative transfer occurs when source and target tasks are too dissimilar; always validate empirically

12. Practice Exercises

Exercise 1: Compare Strategies

Exercise 2: Gradual Unfreezing Schedule

Exercise 3: Domain Adaptation

Exercise 4: Ablation Study

Need Expert Data Science Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement