Transfer Learning for Object Detection in EO Imagery (Metro Manila case)
Anefelo
Duration: 2.5 hours Type: Hands-on Coding Lab Platform: Google Colab with GPU
You will:
Prerequisites:
Resources:
dota8.yaml (8 aerial images, auto-download)Location: Metro Manila - National Capital Region (NCR) Focus Areas: Quezon City and Pasig River corridor Challenge: Rapid informal settlement growth and urban sprawl
Why This Matters
Metro Manila’s rapid urbanization creates challenges for:
Data Source: Sentinel-2 Multispectral Imagery
Lab Goal:
Automate building detection using transfer learning to enable rapid, scalable urban monitoring
7 Key Steps:
Definition: Adapt a model pre-trained on a large dataset to your specific task with minimal additional training data
Analogy: Like a doctor specializing in cardiology after completing general medical training - the foundational knowledge transfers, requiring less time to specialize
Trained on: COCO dataset (330K images, 80 classes)
Fine-tune with: 100-500 labeled satellite images
| Model | Speed | Accuracy | Best For |
|---|---|---|---|
| Faster R-CNN MobileNetV3-FPN (torchvision) | Fast | Good | Colab-friendly fine-tuning |
| Faster R-CNN ResNet-50-FPN v2 (torchvision) | Slow | Excellent | Offline analysis, small objects |
| YOLO11 / YOLO26 (Ultralytics) | Fast | Very Good | Simple training API; OBB variants for aerial imagery |
Recommendation for Lab
torchvision Faster R-CNN MobileNetV3 to see every step of the loop; Ultralytics YOLO for a one-call workflow.
Resolution reality check
Sentinel-2 = 10 m pixels: most Metro Manila houses are 1–2 pixels. Individual buildings need ≲1 m imagery; at 10 m, map built-up areas/clusters (segmentation) or large objects (ships, large buildings).
Objective: Load a COCO-pretrained object detector
from torchvision.models.detection import (
fasterrcnn_mobilenet_v3_large_fpn, FasterRCNN_MobileNet_V3_Large_FPN_Weights)
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT # not pretrained=True
model = fasterrcnn_mobilenet_v3_large_fpn(weights=weights)
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes=2) # bg + building
# Ultralytics alternative: from ultralytics import YOLO; model = YOLO("yolo26n.pt")What You’ll Learn:
Objective: Load and prepare satellite imagery with building annotations
Data Format:
Images:
Annotations:
Steps:
dota8.yaml or your own COCO exportData for this walkthrough
No annotated Metro Manila dataset ships with the course. Practise on dota8.yaml, DOTA, xView or SpaceNet, or annotate your own tiles in CVAT / Label Studio (COCO export).
Objective: Adapt the pre-trained detector to recognize buildings in satellite imagery
Fine-tuning Strategy:
# torchvision: images = list of [3,H,W] tensors in [0,1];
# targets = list of {"boxes": [N,4] xyxy, "labels": [N]}
for p in model.backbone.parameters():
p.requires_grad = False # freeze backbone
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=5e-4)
for epoch in range(20):
model.train()
for images, targets in train_loader:
loss_dict = model(images, targets) # cls, box-reg, objectness, rpn-box
loss = sum(loss_dict.values())
optimizer.zero_grad(); loss.backward(); optimizer.step()
print(f"Epoch {epoch}: loss={loss.item():.4f}")
# Ultralytics (oriented boxes, aerial): YOLO("yolo26n-obb.pt").train(data="dota8.yaml", epochs=20, imgsz=640)Training Progress:
dota8)Signs of Good Training:
Objective: Calculate mean Average Precision - the standard object detection metric
Precision: Of detected buildings, how many are correct?
\[\text{Precision} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Positives}}\]
Recall: Of all actual buildings, how many did we detect?
\[\text{Recall} = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}\]
Average Precision (AP):
mAP (mean Average Precision):
Intersection over Union (IoU):
\[\text{IoU} = \frac{\text{Area of Overlap}}{\text{Area of Union}}\]
Common Thresholds:
For This Lab
We’ll use mAP@0.5 - more lenient, suitable for satellite imagery where exact boundaries are challenging
# Evaluate on test set (torchmetrics; pip install torchmetrics pycocotools)
from torchmetrics.detection import MeanAveragePrecision
metric = MeanAveragePrecision(iou_type="bbox")
model.eval()
with torch.no_grad():
for images, targets in test_loader:
preds = model([img.to(device) for img in images])
metric.update([{k: v.cpu() for k, v in p.items()} for p in preds], targets)
results = metric.compute()
print(f"mAP@0.5: {results['map_50']:.3f}")
print(f"mAP@[0.5:0.95]: {results['map']:.3f}")
print(f"Recall@100 detections: {results['mar_100']:.3f}")| Phase | mAP@0.5 | Interpretation |
|---|---|---|
| Before fine-tuning | ≈ 0 | COCO has no “building” class |
| After fine-tuning (VHR ≲1 m) | ~0.5-0.8 (indicative) | Depends on labels, density, object size |
| After fine-tuning (Sentinel-2, 10 m) | low for single buildings | Use for clusters/large objects only |
Performance Depends On
Objective: Visualize model predictions on Metro Manila satellite imagery
Tasks:
import matplotlib.pyplot as plt
from torchvision.utils import draw_bounding_boxes
# image: [3,H,W] float tensor in [0,1] (e.g. a test tile)
model.eval()
with torch.no_grad():
pred = model([image.to(device)])[0] # dict: boxes (xyxy), labels, scores
keep = pred["scores"] > 0.5 # confidence threshold
canvas = draw_bounding_boxes((image * 255).byte(), pred["boxes"][keep].cpu(),
labels=[f"building {s:.2f}" for s in pred["scores"][keep]],
colors="red", width=2)
plt.figure(figsize=(12, 12))
plt.imshow(canvas.permute(1, 2, 0))
plt.title("Building detection (example tile)")
plt.axis("off")
plt.show()
# Ultralytics: results = model.predict("tile.png", conf=0.5); results[0].show()Quantitative:
Qualitative:
Application: Identify unplanned settlements in flood-prone areas Stakeholder: NDRRMC, Local Government Units (LGUs) Output: Building density maps, population estimates
Workflow:
Application: Track new construction over time Method: Compare detections from multi-temporal imagery Output: Change maps showing urban expansion hotspots
Process:
Application: Post-typhoon damage assessment Method: Detect changes in building footprints Output: Damage severity maps for relief operations
Indicators:
Application: Identify under-served areas Stakeholder: DPWH, MMDA Output: Priority areas for infrastructure development
Analysis:
1. Automated Data Acquisition
2. Pre-processing
3. Inference
4. Post-processing
5. GIS Export
1. Acquire Satellite Imagery:
2. Create Annotations:
3. Annotation Guidelines:
4. Validation:
| Challenge | Solution |
|---|---|
| Dense urban areas | Use higher resolution imagery (Pléiades, SPOT 6/7) |
| Cloud cover | Combine Sentinel-2 optical with Sentinel-1 SAR |
| Small buildings | Higher-resolution imagery, tiling, FPN-based or recent YOLO models |
| Shadow confusion | Include shadow-augmented training data |
| Computation cost | Use lighter models (MobileNet) or cloud GPUs |
| Activity | Duration | Notes |
|---|---|---|
| Introduction & Setup | 15 min | GPU check, open reference notebooks |
| Load Pre-trained Model | 20 min | torchvision / Ultralytics, test inference |
| Data Preparation | 30 min | Load data, visualize, split |
| Fine-tuning | 40 min | Training loop, monitor loss |
| Evaluation | 25 min | Calculate mAP, interpret metrics |
| Visualization | 20 min | Plot detections, analyze results |
| Export & Integration | 10 min | GeoJSON export, GIS demo |
| Troubleshooting | 10 min | Address common issues |
| Buffer | 10 min | Q&A, extensions |
| Total | 150 min | 2.5 hours |
Issue 1: Out of Memory (OOM)
Issue 2: mAP Very Low (<0.30)
Issue 3: Detects Everything as Buildings
Issue 4: Training Very Slow
!nvidia-smi to verify GPU allocationKey Achievements
✅ Loaded and understood pre-trained object detection models ✅ Prepared satellite imagery and COCO annotations ✅ Fine-tuned detector on urban building dataset ✅ Evaluated performance using mAP metrics ✅ Visualized detections on Metro Manila imagery ✅ Connected to real-world Philippine urban monitoring ✅ Understood deployment pipeline for operations
| Aspect | Session 2 (Segmentation) | Session 4 (Detection) |
|---|---|---|
| Task | Pixel-wise classification | Object localization + classification |
| Output | Binary flood mask | Bounding boxes + labels |
| Metric | IoU, F1-score, Dice | mAP, Precision, Recall |
| Use Case | Flood extent mapping | Building counting, urban growth |
| Data | Sentinel-1 SAR | Sentinel-2 Optical |
| Granularity | Every pixel labeled | Objects with boxes |
Both are complementary!
Apply This Workflow:
Advanced Extensions:
Advanced Exercise 1: Multi-class Detection
Advanced Exercise 2: Change Detection
Advanced Exercise 3: Anchor Box Optimization
By the end of this lab, you should be able to:
Object detection with transfer learning is a powerful and practical tool for Earth observation applications.
Key Benefits:
Final Message:
Even small teams with limited resources can build production-quality detectors for critical applications like disaster preparedness and urban planning!
Open Colab and Begin!
📓 torchvision detection tutorial · Ultralytics tutorial notebook
Estimated completion: 2-2.5 hours
Questions? Ask your instructor during the session.
Questions?
Contact:
Let’s build urban monitoring solutions for the Philippines!
EO AI/ML Training — Day 3, Session 4.
EO AI/ML Training | Day 3 · Session 4 | Object Detection Lab