Deep Learning · Visual Understanding
Classification tells us what an image contains. Many real systems must also say where each object is, which pixels belong to it, or which regions influenced a prediction. This lesson separates those questions, calculates bounding-box overlap, explains duplicate removal, follows an encoder–decoder segmentation network, and computes a small Grad-CAM heatmap without treating it as proof.
Choose the Output Before Choosing the Model
A warehouse camera may need to answer “is a helmet visible?” That is classification. If it must count workers without helmets, it needs a location for each person: object detection. If a robot must grasp the exact visible shape of every package, boxes are too coarse and instance masks are more useful.
Four questions produce four different outputs
The same street scene is represented differently according to the task.
| Task | Expected output | Example use |
|---|---|---|
| Image classification | One or more labels for the whole image | Product type, disease present/absent |
| Object detection | Class, confidence and bounding box for each object | Count vehicles; locate safety equipment |
| Semantic segmentation | A class label for every pixel | Road versus pavement; tumour region |
| Instance segmentation | Separate pixel mask for every object | Outline and count touching cells |
| Panoptic segmentation | Semantic labels for all pixels plus separate countable instances | Complete autonomous-driving scene map |
A Detector Predicts What, Where and How Confident
A bounding box is commonly stored as its top-left and bottom-right coordinates: (xmin, ymin, xmax, ymax). The origin is usually the top-left of the image; x grows right and y grows down. A detector returns many candidate boxes, each with class scores and a confidence/objectness value.
Class
What object might be here?
forklift
Box
Where is it?
[120, 45, 310, 220]
Score
How strongly did the model support it?
0.87
The box numbers are model-produced pixel coordinates: left x=120, top y=45, right x=310 and bottom y=220. The score 0.87 is also produced by the model. A developer chooses a score threshold that decides whether this candidate is shown; the threshold is not learned automatically by this output.
Training usually combines several losses. A classification term teaches the class, a localization term teaches box coordinates, and some detectors add objectness or mask losses. Their weights affect the trade-off; a low total number is meaningful only with the exact loss definition and validation metrics.
Simplified multi-task loss
Ltotal = Lclass + λboxLbox + λobjLobjectness
Each λ is a developer-selected hyperparameter that controls a term's relative contribution. It is multiplied by a loss because the raw terms can have different scales and priorities. The exact losses, weights and matching process differ across detector families.
class loss
0.40
box loss
0.20 × λ=5
objectness
0.10 × λ=1
total
0.40+1.00+0.10=1.50
These small values and weights are manually chosen only to demonstrate the arithmetic. During real training, the model produces the three losses from its predictions and labels; the training configuration supplies the λ values.
Calculate Intersection over Union
A predicted box can name the right class but be badly placed. Intersection over Union (IoU) compares its overlap with a labelled ground-truth box while accounting for their combined area.
Intersection over Union measures box overlap
Intersection over Union
IoU = area(A ∩ B) / area(A ∪ B)
The union includes every point covered by either box, counting the overlap once.
IoU = 1 means identical boxes; 0 means no overlap. A threshold such as 0.5 is a task/evaluation choice, not a universal definition of a correct detection.
Worked box example
Ground truth A = (10, 10, 50, 50). Prediction B = (30, 20, 70, 60). Coordinates are (xmin, ymin, xmax, ymax).
1. Areas
A=(50−10)(50−10)=1600
B=(70−30)(60−20)=1600
2. Intersection
width=min(50,70)−max(10,30)=20
height=30
area=600
3. Union
1600+1600−600
=2600
4. IoU
600/2600
≈ 0.231
Interpretation: only about 23.1% of the combined covered region overlaps. At IoU threshold 0.5 this prediction would not match the ground-truth object.
Why One Object Can Produce Several Boxes
Detectors examine many locations, scales or region proposals. Several candidates can surround the same car. Non-maximum suppression (NMS) is a post-processing step that keeps a high-scoring box and suppresses lower-scoring boxes of the same class that overlap it too strongly.
Non-maximum suppression turns duplicate proposals into cleaner detections
1 · Rank
A: 0.92, B: 0.78, C: 0.61
2 · Keep A
highest confidence
3 · Compare
IoU(A,B)=0.72; IoU(A,C)=0.08
4 · Suppress B
keep A and C
One-stage detectors such as YOLO, SSD and RetinaNet predict dense boxes/classes in one main pass and are often chosen for speed. Two-stage detectors such as Faster R-CNN first generate promising regions, then classify/refine them; they can offer strong accuracy but often cost more latency. This is a family-level tendency, not a guarantee for every model and device.
Segmentation Predicts a Class at Pixel Resolution
A semantic segmentation model produces a C × H × W grid of logits: C class scores at every pixel location. C is chosen from the number of categories in the task; H and W are the output grid's height and width. During training, the target is an H × W grid of class IDs supplied by the labelled mask.
A U-Net preserves detail while learning context
In the teaching diagram, 128 → 64 → 32 is caused by two downsampling steps that each halve height and width. The channel counts 32 → 64 → 128 are designer-selected capacities, not spatial measurements. The decoder reverses the spatial changes, while skip connections copy same-resolution encoder features across so boundary detail is available again.
U-Net uses an encoder to build context and a decoder to restore resolution. Same-scale skip connections recover fine detail. DeepLab families use atrous (dilated) convolution and multi-scale context so filters see wider regions without downsampling as aggressively. Mask R-CNN extends a detector with a mask branch for each detected instance.
Pixel IoU for one class
IoU = TP / (TP + FP + FN)
TP: correctly predicted class pixels; FP: extra predicted pixels; FN: missed class pixels.
Dice coefficient
Dice = 2TP / (2TP + FP + FN)
Dice emphasizes overlap and ranges from 0 to 1 under this definition.
Grad-CAM Explains a Class Score With a Coarse Heatmap
A classifier gives a label but no box. Grad-CAM uses gradients of one selected class score with respect to a convolutional feature tensor. It averages those gradients to assign one importance weight to each feature channel, combines the channel maps, and applies ReLU so positive support remains.
Grad-CAM asks which final feature-map regions supported one class score
product image
class logit
“defective”
gradients
weight feature maps
coarse heatmap
Grad-CAM for class c
αkc = (1/Z) Σi,j ∂yc/∂Ai,jk Lc = ReLU(Σk αkcAk)
Ak is feature map k produced by the model, yc is the selected class logit, Z is the calculated number of spatial cells, and α is that map's average sensitivity for class c. Division by Z turns a sum over locations into an average so channel weights remain comparable across the map.
Two 2 × 2 feature maps
We manually choose the two small feature maps so every cell is visible. Backpropagation would calculate four class-score gradients per map; averaging those four gradients produces α₁=0.5 and α₂=−0.25 for this teaching example.
A₁=[[1,2],[0,1]], A₂=[[0,1],[2,1]]
weight and add matching cells: 0.5A₁−0.25A₂
= [[0.50,0.75],[−0.50,0.25]]
keep positive support with ReLU: Lᶜ=[[0.50,0.75],[0,0.25]]
Interpretation: the top-right cell provides the strongest positive support for class c in this coarse map. A negative combined cell becomes zero; Grad-CAM is showing supporting evidence, not a pixel-accurate object mask.
Evaluate the Whole Detection System
Detection evaluation must match predicted boxes to ground truth at an IoU threshold. Precision asks how many reported detections were correct; recall asks how many labelled objects were found. Varying the confidence threshold creates a precision–recall curve. Average Precision (AP) summarizes that curve for a class under a specified evaluation protocol; mAP averages AP across classes and sometimes across multiple IoU thresholds.
| Failure | What it changes | What to inspect |
|---|---|---|
| Correct class, poor box | IoU and localization AP fall | Box annotation consistency; small-object resolution; regression loss |
| Many duplicate boxes | Precision falls | NMS threshold, class-aware suppression and score calibration |
| Missed small objects | Recall and small-object AP fall | Input resolution, feature pyramid, label quality and cropping |
| Good masks, rough boundaries | Boundary quality weak despite acceptable region IoU | Annotation resolution, decoder detail, loss and post-processing |
| Grad-CAM highlights background | Possible shortcut learning | Background diversity, occlusion tests and counterfactual data—not heatmap alone |
Run a Pretrained Detector Before Training One
This PyTorch example loads both pretrained weights and their matching preprocessing. A detector expects a list of C × H × W image tensors and returns one dictionary per image.
import torch
from torchvision.io import decode_image
from torchvision.models.detection import (
fasterrcnn_resnet50_fpn_v2,
FasterRCNN_ResNet50_FPN_V2_Weights,
)
weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn_v2(
weights=weights, box_score_thresh=0.80
)
model.eval()
image = decode_image("warehouse.jpg") # [C, H, W], uint8
input_image = weights.transforms()(image) # matching preprocessing
with torch.no_grad():
prediction = model([input_image])[0]
labels = [weights.meta["categories"][i] for i in prediction["labels"]]
for label, score, box in zip(labels, prediction["scores"], prediction["boxes"]):
print(label, round(float(score), 3), box.tolist())
# Each box is [x_min, y_min, x_max, y_max].For custom training, each target must contain correctly typed boxes of shape [N,4], integer labels, and optional [N,H,W] masks. In the pretrained torchvision detection convention, class index 0 represents background. Transform boxes and masks with the image.
Choose the Simplest Output That Solves the Product Need
| Need | Starting task/model direction | Trade-off |
|---|---|---|
| Say whether one condition exists | Classification + Grad-CAM for investigation | Cheapest labels; heatmap is not localization ground truth |
| Count and locate separate objects | Object detector | Box annotation costs more than image labels |
| Fast edge detection | Lightweight one-stage detector | Benchmark device latency and small-object recall |
| High-quality general detection baseline | Pretrained Faster R-CNN-family model | Often slower and heavier |
| Label every pixel by category | U-Net/DeepLab semantic segmentation | Pixel masks are expensive to annotate |
| Separate touching objects | Mask R-CNN or instance-segmentation model | More complex targets and evaluation |
Limits You Must Not Hide
Annotation cost
Boxes are slower to label than classes; high-quality masks are slower still. Ambiguous boundaries create disagreement.
Small and crowded objects
Downsampling removes detail, while NMS can suppress neighbouring instances. Report metrics by size and density.
Domain shift
Weather, camera, hospital or production-line changes can break performance even when benchmark mAP is strong.
Metric dependence
AP changes with IoU thresholds, class averaging, max detections and dataset protocol. State the exact metric.
Heatmap over-trust
Grad-CAM is coarse and class-specific. Use it for investigation with other tests, not as proof of model reasoning.
Real-time claims
Frames per second depends on resolution, batch size, preprocessing, post-processing, hardware and runtime. Measure end to end.
The Connected Picture
- Classification labels an image; detection adds boxes; segmentation assigns pixel labels; instance segmentation separates objects.
- IoU measures geometric overlap and supports matching, NMS and evaluation.
- NMS removes lower-scoring duplicate detections but needs careful thresholds in crowded scenes.
- U-Net combines contextual encoding with detail-preserving skip connections.
- Grad-CAM uses class gradients to weight feature maps and creates a coarse supporting-evidence map.
- Choose the output and metric from the real decision the system must support.