Chapter 6: Recognition
Instance recognition, image classification, object detection, semantic segmentation, and face recognition.
- Topics
- 4
- Demo
- 1
- Videos
- 3
- Min read
- 33
Chapter Overview
Recognition is where computer vision meets understanding. Given an image, can we determine what's in it? This seemingly simple question has driven decades of research.
What is this chapter about? We explore the major recognition tasks: classifying whole images, detecting and localizing objects, segmenting images pixel-by-pixel, and recognizing faces. Each builds on the deep learning foundations from Chapter 5.
Why does this matter? Recognition powers countless real-world applications:
- Image classification: Organizing photos, medical diagnosis, content moderation
- Object detection: Self-driving cars, security cameras, retail analytics
- Segmentation: Medical imaging, autonomous navigation, photo editing
- Face recognition: Biometric authentication, photo organization
How the topics connect: We start with image classification—the simplest task where we assign one label to an entire image. Then object detection adds localization—where are objects? Semantic segmentation provides pixel-level understanding. Finally, face recognition shows how these ideas apply to a specific, important domain.
Chapter Roadmap
Click any topic to jump in
Image Classification
Feature extraction, softmax, and cross-entropy — assigning a single category label to an entire image.
Where are objects? What label per pixel?
Object Detection
IoU, anchor boxes, NMS, and mAP — localizing and classifying multiple objects with bounding boxes.
Semantic Segmentation
Pixel-wise classification with encoder-decoder networks — assigning a class label to every pixel in the image.
Face Recognition
Embeddings, triplet loss, and ArcFace — mapping faces to a metric space for verification and identification.
Topics
4 topics in this chapter
You trained a deep network in Chapter 5, but a stack of convolutions and activations is not yet an answer: it produces a vector of numbers, not the word 'cat'. Image classification is the bridge that turns those numbers into a single categorical decision. The task is deceptively hard because the same object looks different under changes in pose, lighting, scale, and background, while different objects can look nearly identical. Before deep learning, engineers hand-crafted features such as SIFT and HOG and hoped a linear classifier could separate them; AlexNet's 2012 ImageNet win showed that letting the network learn its own features wins decisively. This topic follows the pipeline end to end. A CNN backbone maps pixels to a compact feature vector, a softmax layer turns that vector into a probability distribution over classes, cross-entropy loss measures how wrong the distribution is and supplies gradients, and top-k accuracy reports how good the trained model actually is. Master this loop and the detection and segmentation topics that follow become variations on the same theme.
Definition
Image classification is the task of assigning one label from a fixed set of K categories to an entire input image, by learning a function that maps the image to a probability distribution over the classes and returning the single highest-probability class.
In this topic
- 1Feature Extraction
- 2Softmax Classification
- 3Cross-Entropy Loss
- 4Top-k Accuracy
Feature Extraction
Raw pixels are a terrible representation for comparison: two photos of the same cat can differ in every pixel, so a classifier working directly on pixels would need astronomically many examples. Feature extraction solves this by learning a mapping that sends an image (say ) to a compact vector with around 512 or 2048. Good features are discriminative — different classes land far apart — and invariant — the same class stays close despite pose or lighting changes. This is exactly the representation the CNN backbone from Chapter 5 produces at its final pooling layer, and transfer learning succeeds because those features generalize across tasks.
A CNN backbone maps input to features through a sequence of convolutions, activations, and pooling. Good features satisfy the manifold hypothesis: high-dimensional data lies on a low-dimensional manifold, and the mapping should unfold this manifold so that linear classifiers work in feature space. Transfer learning works because early layers learn generic features (edges, textures) while later layers learn task-specific features. Fine-tuning adjusts the mapping with a small learning rate (typically to ) to shift features toward the new task distribution without destroying the learned representations.
A ResNet-50 takes 224×224×3 images and outputs 2048-dim features. What's the compression ratio?
Softmax Classification
A feature vector is not yet a decision — we need class scores that behave like probabilities. Softmax converts a vector of raw logits into a distribution: exponentiate each logit and divide by the sum over all classes. Here is the weight vector for class , its bias, and the number of classes. The exponential lets the largest logit dominate while keeping every probability positive, and the denominator forces them to sum to one. The predicted class is . It can overflow when logits grow huge, so stable implementations subtract the maximum logit before exponentiating.
Softmax produces a valid probability distribution on the -simplex: where are the logits. The decision boundary between classes and is the hyperplane where , i.e., . Temperature scaling controls confidence: as the distribution becomes one-hot (argmax), as it becomes uniform. Label smoothing replaces the one-hot target with , preventing the model from becoming overconfident and improving calibration.
Logits are [3, 1, 1]. Compute softmax probabilities.
Cross-Entropy Loss
Softmax gives probabilities, but training needs a scalar to minimize. Cross-entropy measures the mismatch between the predicted distribution and the true one . With one-hot labels — for the correct class and 0 elsewhere — the sum collapses to , so the loss depends only on the probability assigned to the truth. It is zero when that probability reaches 1 and grows without bound as it approaches 0, punishing confident mistakes hardest. Crucially, its gradient with respect to the logits is simply , bounded and well-conditioned, which is why it pairs so cleanly with the softmax from the previous concept.
Cross-entropy equals the KL divergence where is the entropy of the true distribution. For one-hot labels, so minimizing cross-entropy is equivalent to minimizing KL divergence. The gradient with respect to logits before softmax is simply — bounded in , well-conditioned regardless of how wrong the prediction is. Focal loss down-weights easy examples by the factor , focusing training on hard examples. With , a well-classified example with has its loss reduced by factor compared to standard cross-entropy.
Model predicts 90% for true class, 10% for wrong class. What's the cross-entropy loss?
Top-k Accuracy
Loss is a training signal, but to report how good a model is we want an interpretable score. Top-k accuracy is the fraction of examples whose true label appears among the model's highest-probability predictions. Top-1 is ordinary accuracy — the single guess must be exactly right. Top-5, standard on ImageNet's 1000 classes, forgives near-misses among visually similar categories such as dog breeds. The indicator scores a hit, and averaging over examples gives the rate. It reveals nothing about calibration, though: a model can be accurate yet systematically over-confident, which is why calibration metrics are reported alongside it.
Top- accuracy is the empirical probability that the true label falls within the largest predicted scores: . On ImageNet (1000 classes), random guessing gives top-1 accuracy of 0.1% and top-5 of 0.5%. The gap between top-1 and top-5 measures how often the model ranks the true class highly but not first — often due to fine-grained distinctions (similar dog breeds) or ambiguous images. A well-calibrated model has the property that when it predicts , the class is correct roughly 80% of the time. Expected calibration error (ECE) bins predictions by confidence and measures .
Model's top-5 predictions: [golden retriever, labrador, beagle, poodle, cat]. True: labrador. Is this correct?
Theory Exercise
Problem:
A classifier outputs logits [2.0, 1.0, 0.5] for classes [cat, dog, bird]. Calculate the softmax probabilities and cross-entropy loss if the true class is 'cat'.
Hints:
- Softmax: P(k) = exp(z_k) / sum(exp(z_j))
- First compute exp(2.0), exp(1.0), exp(0.5)
- Cross-entropy with one-hot label: L = -log(P(true_class))
Related Problems on PixelBank
Image classification, the previous topic, answers 'what is in this picture?' with a single label — but a street scene contains many objects, and a self-driving car needs to know not just that pedestrians exist but exactly where each one stands. Object detection extends classification with localization: for every object it outputs both a class label and a bounding box. This raises problems classification never faced. How many objects are there? They vary from image to image, so a fixed-size output does not fit. How do we score a box that is close but not perfect? And when a model fires several overlapping boxes on one object, which do we keep? This topic builds the machinery that answers these questions. Intersection over Union quantifies how well a predicted box matches the truth, anchor boxes give the network a fixed menu of shapes to refine so the variable-count problem becomes tractable, non-maximum suppression prunes duplicate detections, and mean average precision rolls everything into the single number the field competes on.
Definition
Object detection is the task of localizing and classifying every object of interest in an image, producing for each a bounding box with coordinates and a class label with a confidence score, where the number of outputs varies per image.
In this topic
- 1Intersection over Union (IoU)
- 2Non-Maximum Suppression (NMS)
- 3Anchor Boxes
- 4Mean Average Precision (mAP)
Intersection over Union (IoU)
A predicted box is rarely pixel-perfect, so we need a graded measure of how well it matches the ground truth rather than a yes/no test. IoU, also called the Jaccard index, divides the area where two boxes overlap by the area they jointly cover: . It is 0 when the boxes are disjoint and 1 only when they coincide exactly, and it is scale-invariant, so a small box and a large box are judged by the same standard. Detection benchmarks turn this continuous score into a correctness threshold — PASCAL VOC accepts a detection at IoU , COCO demands . Variants like GIoU add penalty terms so the measure still gives useful gradients when boxes do not overlap at all.
IoU measures overlap between two bounding boxes: . Since , the formula becomes . IoU is a metric in the mathematical sense: it satisfies , equals 1 only when , and is symmetric. For axis-aligned boxes, the intersection is computed as in . Generalized IoU (GIoU) adds a penalty for the area of the smallest enclosing box : , and unlike IoU, GIoU is differentiable everywhere and works as a loss function.
Box A: 100×100 pixels. Box B: 100×100 pixels. They overlap in a 50×50 region. What's the IoU?
Non-Maximum Suppression (NMS)
A detector typically fires many boxes on a single object because neighbouring anchors all latch onto it, so raw output is cluttered with duplicates. NMS is the greedy cleanup: sort all boxes by confidence, take the highest-scoring one as a true detection, discard every remaining box whose IoU with it exceeds a threshold (commonly 0.5), and repeat on what survives. The IoU from the previous concept is exactly the overlap test used here. The threshold trades errors: too low and it deletes genuinely separate but nearby objects, too high and duplicates leak through. Soft-NMS softens the hard deletion by decaying scores instead, and class-specific NMS only suppresses boxes of the same label so a person standing in front of a car is not erased.
NMS is a greedy algorithm that removes redundant detections. Sort boxes by confidence descending, then iteratively: (1) select the highest-confidence box, (2) remove all boxes with against it, (3) repeat. Time complexity is for computing all pairwise IoUs but typically in practice since most boxes are suppressed early. Soft-NMS replaces the hard threshold with a decay function: , preserving nearby detections with reduced confidence. The IoU threshold (typically 0.5) trades precision vs recall: lower suppresses more aggressively (higher precision, lower recall).
Boxes with scores [0.9, 0.8, 0.7]. IoU(1,2)=0.6, IoU(1,3)=0.3, IoU(2,3)=0.2. Which survive NMS at threshold 0.5?
Anchor Boxes
Objects appear at unpredictable positions, sizes, and aspect ratios, so a network cannot simply regress a fixed number of boxes. Anchor boxes solve this by tiling the image with a predefined menu of reference boxes at every spatial location; the network only predicts small offsets that nudge an anchor toward a real object. The center offset passes through a sigmoid so it stays inside the cell, while width and height are scaled by and , guaranteeing positive sizes. Anchor shapes are usually chosen by k-means clustering on the training boxes. The design's weakness is that most anchors match no object, creating heavy foreground-background imbalance, which is why anchor-free detectors like FCOS and CenterNet were later proposed.
Anchor boxes are a set of predefined reference boxes at each spatial location. For a feature map of size with anchors per cell, the network outputs values: 4 box offsets , 1 objectness score, and class probabilities. The offset parametrization is and , where bounds the center offset and the exponential ensures positive width. The number of candidate boxes scales as — with and , YOLOv3 generates 10,647 boxes per image. Anchor-free detectors like FCOS avoid this by predicting distances from each pixel to the four box edges directly.
Anchor is 64×64. Network predicts , . What's the predicted box size?
Mean Average Precision (mAP)
A detector produces a ranked list of boxes at every confidence level, so no single accuracy number captures its quality; we need a metric that summarizes the whole precision-recall trade-off. Average precision (AP) for one class is the area under its precision-recall curve, obtained by sweeping the confidence threshold from high to low. Mean average precision averages AP across all classes: . Whether a detection counts as a true positive depends on the IoU threshold from the first concept — PASCAL VOC uses [email protected], while COCO averages over ten thresholds from 0.5 to 0.95 to reward tight localization. It is the number leaderboards rank on, and reporting AP separately for small, medium, and large objects exposes where a detector struggles.
mAP averages per-class AP: . For each class, AP is the area under the precision-recall curve: , approximated by interpolation at recall values. COCO mAP averages over 10 IoU thresholds from 0.5 to 0.95 in steps of 0.05: . A true positive requires IoU with the ground truth and highest confidence among matches. The precision-recall curve is computed by sorting all detections by confidence and scanning: precision at rank is and recall is . COCO also reports AP for objects of different sizes (area , -, pixels).
A detector achieves AP of 0.85 for cars, 0.70 for people, 0.60 for bicycles. What's the mAP?
Theory Exercise
Problem:
Two boxes have coordinates A=[10,10,50,50] and B=[30,20,70,60] in [x,y,x2,y2] format. Calculate their IoU.
Hints:
- Find the intersection rectangle coordinates
- Intersection area = width × height (if positive)
- Union = Area_A + Area_B - Intersection
Related Problems on PixelBank
Object detection, the previous topic, draws a box around each object — but a box is a crude approximation of shape, and many tasks need to know precisely which pixels belong to what. A self-driving car must trace the exact boundary of the drivable road, and a radiologist needs the outline of a tumour, not a rectangle loosely containing it. Semantic segmentation delivers this by classifying every single pixel into a category such as road, building, sky, or person. That ambition changes the whole architecture. A classification network throws away spatial resolution as it pools toward one label, but segmentation must recover full resolution to produce a dense map. This topic develops the pieces. Pixel-wise classification defines the task and its loss, the encoder-decoder architecture explains how a network can both understand content and restore spatial detail, transposed convolution provides the learned upsampling that rebuilds resolution, and Dice loss handles the severe class imbalance that ordinary accuracy hides. Together they turn a classifier into a dense predictor.
Definition
Semantic segmentation is the task of assigning a class label to every pixel of an image, producing a dense output map the same spatial size as the input in which each pixel carries the category of the object or region it belongs to.
In this topic
- 1Pixel-wise Classification
- 2Encoder-Decoder Architecture
- 3Transposed Convolution
- 4Dice Loss
Pixel-wise Classification
Classification emits one label per image and detection one label per box, but segmentation asks the harder question: what class is each individual pixel? The output is a full grid of labels, formally where indexes a pixel and ranges over classes. Training minimizes cross-entropy — the same loss from the classification topic — but averaged over every pixel rather than once per image. The dominant failure mode is class imbalance: background pixels can outnumber a thin object like a pole by a hundred to one, so a network can score high accuracy while ignoring the rare class entirely. This is why mean IoU, not accuracy, is the reported metric.
Semantic segmentation assigns each pixel a class label, producing an output tensor where is the number of classes. The loss is pixel-wise cross-entropy averaged over all pixels: . Class imbalance is severe — background pixels can outnumber foreground 100:1. Weighted cross-entropy uses inverse class frequency: . Mean IoU (mIoU) is the standard metric: , where each term counts pixels.
A 512×512 image has 10 classes. What's the shape of the segmentation output?
Encoder-Decoder Architecture
There is a tension at the heart of segmentation: recognizing what an object is requires a large receptive field and abstract features, which pooling provides by shrinking the image, yet labeling pixels requires the full original resolution that pooling destroys. The encoder-decoder resolves this in two halves. The encoder is a classification-style CNN that downsamples, distilling what is present; the decoder then upsamples back to input resolution, reconstructing where each thing is. Skip connections, the U-Net innovation, forward high-resolution encoder features directly to the decoder so fine boundaries lost during downsampling are restored. Without them, masks come out blurry and boundaries smear. The encoder answers 'what', the decoder answers 'where', and skip connections stitch the two answers together.
The encoder reduces spatial resolution while increasing channel depth: from to in a typical ResNet backbone. The decoder recovers spatial resolution through upsampling and concatenation with encoder features (skip connections). U-Net concatenates encoder features at each resolution level: if the encoder has channels at resolution , the decoder receives channels from concatenation. This preserves fine-grained spatial details lost during downsampling. FPN (Feature Pyramid Network) uses lateral connections and top-down pathways to build multi-scale feature maps, processing each scale with the same prediction head — enabling detection of objects at different sizes.
Encoder reduces 256×256 to 16×16. What upsampling factor does the decoder need?
Transposed Convolution
The decoder needs to increase spatial resolution, and while simple interpolation works, we would rather the network learn how to upsample so it can synthesize sharp boundaries. Transposed convolution (sometimes called deconvolution) does this by conceptually inserting zeros between input elements and then convolving, with the output size given by for stride , kernel , and padding . A stride of 2 doubles each dimension. Because the upsampling weights are learned, the layer can produce crisper edges than fixed bilinear interpolation. Its notorious failure is the checkerboard artifact: when the kernel size is not divisible by the stride, output positions receive uneven numbers of contributions, leaving a grid pattern. Practitioners often avoid this with bilinear upsampling followed by an ordinary convolution.
Transposed convolution ("deconvolution") upsamples by inserting zeros between input elements and then convolving. For input size , kernel size , stride , and padding , the output size is . With : , doubling the resolution. The operation is mathematically the transpose (adjoint) of convolution: if forward conv maps , the transposed conv maps via the transposed weight matrix. Checkerboard artifacts arise when the kernel size is not divisible by the stride, causing uneven overlap of output contributions. Bilinear upsampling followed by a regular convolution avoids this.
Input is 32×32. TransConv with kernel=4, stride=2, padding=1. Output size?
Dice Loss
Pixel-wise cross-entropy struggles when a class is tiny, because a network can drive the loss down simply by predicting 'background' everywhere and still be right 99% of the time. Dice loss attacks this directly by optimizing overlap rather than per-pixel correctness: , where is the predicted mask (soft probabilities) and the ground-truth mask. Because it normalizes by the total foreground area of both masks, a small object counts as much as a large one — solving the imbalance that defeats accuracy and plain cross-entropy. It relates directly to IoU from the detection topic; both measure overlap, but Dice weights the intersection twice. In practice it is usually summed with cross-entropy, which supplies smoother early-training gradients.
Dice loss is based on the Dice coefficient: , where and are the predicted and ground truth masks. In the soft (differentiable) formulation: where are predicted probabilities and are labels. Dice loss handles class imbalance naturally because it normalizes by the total area of both sets — a small object contributes equally whether the image has 100 or 100,000 background pixels. Tversky loss generalizes Dice by weighting false positives and false negatives differently: .
Prediction has 80 pixels as foreground, GT has 100. Overlap is 70 pixels. Dice score?
Theory Exercise
Problem:
For a binary segmentation task, the ground truth has 1000 foreground pixels and 9000 background pixels. If the model predicts all pixels as background, what is the accuracy and Dice score?
Hints:
- Accuracy = correct predictions / total predictions
- Dice = 2 × intersection / (pred + gt)
- If predicting all background, intersection with foreground is 0
Related Problems on PixelBank
The recognition tasks so far — classification, detection, segmentation — all share an assumption: the categories are fixed and known at training time. Face recognition breaks it. You cannot train a classifier with one output per person when new people must be recognized after deployment and each may have only a single enrolment photo. The solution reframes the problem as metric learning: instead of predicting a class, the network learns an embedding, a compact vector where distance encodes identity, so two photos of the same person land close together and different people land far apart. Recognition then reduces to comparing distances, and a never-before-seen face works fine because it simply gets its own point in the space. This topic builds that idea in order. Face embedding defines the representation and its unit-norm geometry, triplet loss trains it with relative comparisons, ArcFace improves separation with an angular margin, and the verification-versus-identification distinction shows the two ways the embeddings are used in practice.
Definition
Face recognition is the task of determining identity from a face image by mapping it to a fixed-length embedding vector such that distances between embeddings are small for the same person and large for different people, enabling verification and identification by distance comparison.
In this topic
- 1Face Embedding
- 2Triplet Loss
- 3ArcFace Loss
- 4Verification vs Identification
Face Embedding
A per-person classifier fails the moment a new identity appears, so face recognition instead learns an embedding: a network maps a face image to a vector (or 512) that is L2-normalized to unit length, placing every face on a hypersphere. On that sphere, similar faces cluster and different people separate, so identity becomes a question of distance rather than of a fixed label — exactly the flexibility a fixed-output softmax classifier from the first topic lacks. Normalization matters because it makes Euclidean distance and cosine similarity equivalent, so a threshold learned on one image pair transfers to all others. The embedding is only as good as its training loss, which the next two concepts supply.
A face embedding network maps face images to unit-norm vectors on a hypersphere: where is typically 128 or 512. The Euclidean distance between embeddings corresponds to cosine distance on the hypersphere: where is the angle between them. Two faces are considered the same person when for a threshold . With 512-dimensional embeddings, the capacity to distinguish identities is enormous — the hypersphere has surface area that grows exponentially with dimension, allowing billions of distinct identity clusters.
A 128-dim embedding [0.1, 0.2, ...] has L2 norm of 2.5. How do you normalize it?
Triplet Loss
To shape the embedding we do not tell the network absolute coordinates — only relative facts: this anchor is the same person as that positive and a different one from this negative. Triplet loss encodes that directly as , using the embedding from the previous concept. It stays zero as long as the negative is farther than the positive by at least the margin (typically 0.2), and turns on only when that ordering is violated or too tight. The catch is that most random triplets already satisfy the margin and produce no gradient, so training stalls unless hard negative mining is used to select the difficult, informative triplets that actually teach the network.
Triplet loss enforces a margin between positive and negative pairs: where is anchor, is positive (same identity), is negative (different identity), and is the margin. The loss is zero when the negative is farther than the positive by at least . Hard negative mining selects the closest negative: subject to . Semi-hard negatives satisfy — the training signal is strongest for these. The number of possible triplets grows as , making mining strategy critical for convergence.
d(anchor, positive) = 0.3, d(anchor, negative) = 0.6, margin α = 0.2. What's the triplet loss?
ArcFace Loss
Triplet loss works but is finicky, needing careful triplet mining. ArcFace takes a different route: keep the softmax-style classification over training identities, but impose a geometric margin. It measures the angle between an embedding and its class-center weight vector, adds a fixed margin (about 0.5 radians) to that angle before the cosine, and scales by (30–64). The loss therefore demands the correct class beat the others by a constant angular gap. Because the margin lives in angle space, it corresponds to a fixed geodesic distance on the same hypersphere the embedding concept introduced, producing tighter within-person clusters and cleaner between-person gaps than triplet loss, with far simpler batching.
ArcFace adds an angular margin to softmax: where is the angle between feature and class center , is the angular margin (typically 0.5 radians), and is the scaling factor (typically 64). The margin is additive in angle space, which corresponds to a constant geodesic distance on the hypersphere — geometrically, it pushes the decision boundary closer to each class center by radians. This produces more compact intra-class clusters and larger inter-class separations compared to triplet loss.
Embedding angle to correct class is 20°. ArcFace adds margin m=28.6° (0.5 rad). What's the effective angle?
Verification vs Identification
Once embeddings exist, they are queried in two distinct ways with different costs and error profiles. Verification (1:1) asks 'are these two faces the same person?' — compute one distance and accept if it falls below a threshold ; this is unlocking a phone. Identification (1:N) asks 'who is this?' — compare the query against a gallery of enrolled identities and return the nearest, or 'unknown' if even the closest exceeds ; this is a watchlist search. Verification is per query while brute-force identification is , so large galleries use approximate nearest-neighbour indexes. Both lean on the metric structure from the embedding concept, and the threshold trades false accepts against false rejects along a ROC curve.
Verification (1:1) computes a single distance and thresholds: where is embedding dimension. Identification (1:N) computes distances against a gallery of identities: for brute force, but approximate nearest neighbor methods (FAISS, Annoy) reduce this to using indexing structures like IVF (inverted file) or HNSW (hierarchical navigable small world) graphs. The ROC curve for verification plots true positive rate vs false positive rate as threshold varies. Equal error rate (EER) is where FAR = FRR. The rank- identification rate is the probability that the correct identity appears in the top nearest neighbors. For gallery, achieving 99% rank-1 accuracy requires embeddings with extremely high discriminative power.
Gallery has 1000 identities. Query face has distances [0.3, 0.8, 0.5, ...] to each. Threshold τ=0.4. Result?
Theory Exercise
Problem:
Given face embeddings A=[0.6, 0.8], B=[0.8, 0.6], and C=[-0.6, 0.8], compute the L2 distances. Which pair is most similar?
Hints:
- L2 distance: d = sqrt((x1-x2)² + (y1-y2)²)
- Compute all three pairwise distances
- Note: All embeddings should be normalized (check: ||e|| = 1)