v9.1.1
Menu

Chapter 6: Recognition

Week 5-6

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

Explainer videoInteractive demo
1
Image Classification

Feature extraction, softmax, and cross-entropy — assigning a single category label to an entire image.

Feature ExtractionSoftmax ClassificationCross-Entropy LossTop-k Accuracy
Adding localization to classification

Where are objects? What label per pixel?

2
Object Detection

IoU, anchor boxes, NMS, and mAP — localizing and classifying multiple objects with bounding boxes.

Intersection over Union (IoU)Non-Maximum Suppression (NMS)Anchor BoxesMean Average Precision (mAP)
3
Semantic Segmentation

Pixel-wise classification with encoder-decoder networks — assigning a class label to every pixel in the image.

Pixel-wise ClassificationEncoder-Decoder ArchitectureTransposed ConvolutionDice Loss
Specialized recognition domain
4
Face Recognition

Embeddings, triplet loss, and ArcFace — mapping faces to a metric space for verification and identification.

Face EmbeddingTriplet LossArcFace LossVerification vs 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

  1. 1Feature Extraction
  2. 2Softmax Classification
  3. 3Cross-Entropy Loss
  4. 4Top-k Accuracy
1 of 4
Feature Extraction

f=ϕ(x)∈Rd\mathbf{f} = \phi(\mathbf{x}) \in \mathbb{R}^d

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 ϕ\phi that sends an image x\mathbf{x} (say 224×224×3224 \times 224 \times 3) to a compact vector f∈Rd\mathbf{f} \in \mathbb{R}^d with dd 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.

Mathematical Intuition

A CNN backbone maps input x∈RH×W×3\mathbf{x} \in \mathbb{R}^{H \times W \times 3} to features f=ϕ(x)∈Rd\mathbf{f} = \phi(\mathbf{x}) \in \mathbb{R}^d 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 ϕ\phi 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 ϕ\phi with a small learning rate (typically 10−410^{-4} to 10−510^{-5}) to shift features toward the new task distribution without destroying the learned representations.

Example:

A ResNet-50 takes 224×224×3 images and outputs 2048-dim features. What's the compression ratio?

2 of 4
Softmax Classification

P(y=k∣x)=ewkTf+bk∑j=1KewjTf+bjP(y=k|\mathbf{x}) = \frac{e^{\mathbf{w}_k^T \mathbf{f} + b_k}}{\sum_{j=1}^{K} e^{\mathbf{w}_j^T \mathbf{f} + b_j}}

A feature vector is not yet a decision — we need class scores that behave like probabilities. Softmax converts a vector of raw logits zk=wkTf+bkz_k = \mathbf{w}_k^T \mathbf{f} + b_k into a distribution: exponentiate each logit and divide by the sum over all classes. Here wk\mathbf{w}_k is the weight vector for class kk, bkb_k its bias, and KK 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 arg⁡max⁡kP(y=k∣x)\arg\max_k P(y=k \mid \mathbf{x}). It can overflow when logits grow huge, so stable implementations subtract the maximum logit before exponentiating.

Mathematical Intuition

Softmax produces a valid probability distribution on the KK-simplex: P(y=k∣x)=ezk/∑jezjP(y=k|\mathbf{x}) = e^{z_k}/\sum_j e^{z_j} where zk=wkTf+bkz_k = \mathbf{w}_k^T \mathbf{f} + b_k are the logits. The decision boundary between classes ii and jj is the hyperplane where zi=zjz_i = z_j, i.e., (wi−wj)Tf+(bi−bj)=0(\mathbf{w}_i - \mathbf{w}_j)^T\mathbf{f} + (b_i - b_j) = 0. Temperature scaling Pτ(k)=ezk/τ/∑jezj/τP_\tau(k) = e^{z_k/\tau}/\sum_j e^{z_j/\tau} controls confidence: as τ→0\tau \to 0 the distribution becomes one-hot (argmax), as τ→∞\tau \to \infty it becomes uniform. Label smoothing replaces the one-hot target with (1−α)δy,k+α/K(1-\alpha)\delta_{y,k} + \alpha/K, preventing the model from becoming overconfident and improving calibration.

Example:

Logits are [3, 1, 1]. Compute softmax probabilities.

3 of 4
Cross-Entropy Loss

L=−∑k=1Kyklog⁡(y^k)=−log⁡(y^c)\mathcal{L} = -\sum_{k=1}^{K} y_k \log(\hat{y}_k) = -\log(\hat{y}_c)

Softmax gives probabilities, but training needs a scalar to minimize. Cross-entropy measures the mismatch between the predicted distribution y^\hat{y} and the true one yy. With one-hot labels — yk=1y_k = 1 for the correct class cc and 0 elsewhere — the sum collapses to −log⁡(y^c)-\log(\hat{y}_c), 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 y^k−yk\hat{y}_k - y_k, bounded and well-conditioned, which is why it pairs so cleanly with the softmax from the previous concept.

Mathematical Intuition

Cross-entropy H(p,q)=−∑kpklog⁡qkH(p, q) = -\sum_k p_k \log q_k equals the KL divergence DKL(p∥q)+H(p)D_{KL}(p \| q) + H(p) where H(p)H(p) is the entropy of the true distribution. For one-hot labels, H(p)=0H(p) = 0 so minimizing cross-entropy is equivalent to minimizing KL divergence. The gradient with respect to logits zkz_k before softmax is simply ∇zkL=y^k−yk\nabla_{z_k} \mathcal{L} = \hat{y}_k - y_k — bounded in [−1,1][-1, 1], well-conditioned regardless of how wrong the prediction is. Focal loss LFL=−(1−y^c)γlog⁡(y^c)\mathcal{L}_{FL} = -(1-\hat{y}_c)^\gamma \log(\hat{y}_c) down-weights easy examples by the factor (1−y^c)γ(1-\hat{y}_c)^\gamma, focusing training on hard examples. With γ=2\gamma = 2, a well-classified example with y^c=0.9\hat{y}_c = 0.9 has its loss reduced by factor (1−0.9)2=0.01(1-0.9)^2 = 0.01 compared to standard cross-entropy.

Example:

Model predicts 90% for true class, 10% for wrong class. What's the cross-entropy loss?

4 of 4
Top-k Accuracy

Top-k=1N∑i=1N1[yi∈top-k(y^i)]\text{Top-}k = \frac{1}{N}\sum_{i=1}^{N} \mathbf{1}[y_i \in \text{top-}k(\hat{y}_i)]

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 kk 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 1[⋅]\mathbf{1}[\cdot] scores a hit, and averaging over NN 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.

Mathematical Intuition

Top-kk accuracy is the empirical probability that the true label falls within the kk largest predicted scores: Top-k=1N∑i=1N1[yi∈argsortdesc(y^i)1:k]\text{Top-}k = \frac{1}{N}\sum_{i=1}^N \mathbf{1}[y_i \in \text{argsort}_{\text{desc}}(\hat{y}_i)_{1:k}]. 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 P(y=k)=0.8P(y=k) = 0.8, the class is correct roughly 80% of the time. Expected calibration error (ECE) bins predictions by confidence and measures ∑b∣Bb∣N∣acc(Bb)−conf(Bb)∣\sum_b \frac{|B_b|}{N}|\text{acc}(B_b) - \text{conf}(B_b)|.

Example:

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))