3. Classification: Supervised

Nearest neighbour, linear classifiers, Haar features, SVM, kernels, AdaBoost, sliding window detection

Contents
1. Supervised Classification 2. The Semantic Gap 3. Nearest Neighbour Classifier 4. K-Nearest Neighbour (K-NN) 5. Linear Classifiers 6. Haar-like Features 7. Dataset Splitting 8. Support Vector Classifier (Linear) 9. SVM — Non-Linear Kernels 10. AdaBoost 11. Object Detection (Sliding Window) Interactive: AdaBoost Walkthrough Interactive: SVM Walkthrough Interactive: K-NN Classifier Interactive: Linear Classifier Interactive: SVM Kernel Trick Interactive: AdaBoost Step-Through Flashcards

1. Supervised Classification

In supervised learning, every training example has both an input vector (image) and a target label. The algorithm learns a mapping from inputs to labels that generalizes to unseen examples.

Supervised vs unsupervised learning
Supervised learning: labeled data, direct feedback, goal is to predict outputs. Unsupervised: no labels, find hidden structure.
AspectSupervisedUnsupervised
Training dataInputs and labelsInputs only
FeedbackDirect (knows correct answer)None
GoalClassify inputs into discrete categoriesFind hidden groups (clustering)

Data-Driven Approach Pipeline

  1. Collect a dataset of images and assign labels.
  2. Train a classifier using machine learning.
  3. Evaluate on a new, unseen set of images.

There is no hardcoded function that can classify images — visual concepts are too variable and complex to specify with simple rules. Machine learning is essential.

Example training set with labeled images
Example training set: labeled images from multiple categories. Each image is manually annotated.

2. The Semantic Gap and Classification Challenges

Semantic Gap
A human sees an image and perceives "cat." A computer sees only a grid of numbers (pixel intensity values in [0, 255]). This disconnect between human semantic understanding and raw numerical representation is the semantic gap.
Semantic gap: human sees a cat, computer sees pixel values
A 600x400 color image is stored as 600x400x3 integers. The computer has no built-in notion of "cat-ness."

Why Pixel-Level Matching Fails

ChallengeEffect on Pixels
Viewpoint variationCamera angle/zoom changes all pixel values
IlluminationLighting and shadows change all pixel values
DeformationObject shape changes (e.g., cat stretching)
OcclusionObjects may be partially hidden
Background clutterComplex backgrounds interfere with object pixels
Intra-class variationSame category can look very different (different cat breeds)

3. Nearest Neighbour Classifier

The simplest possible classifier: memorize all training images, then classify a test image by finding the most similar training image.

PhaseOperationCost
TrainingStore all training images and labelsO(1) — no computation
TestingCompare test image to every training image, return label of nearestO(N × k) per query

Distance Metrics

Manhattan Distance (L1 norm)
$$d_{L1}(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^{k} |x_i - y_i|$$

Sum of absolute pixel differences. No square root needed — computationally cheaper.

Euclidean Distance (L2 norm)
$$d_{L2}(\mathbf{x}, \mathbf{y}) = \sqrt{\sum_{i=1}^{k} (x_i - y_i)^2}$$

Standard straight-line distance in high-dimensional space.

Manhattan L1 distance formula
L1 Manhattan distance computation between two pixel vectors.
Pixel-wise absolute difference computation
L1 distance: compute absolute difference at each pixel position and sum. Example yields L1 = 456.

Decision Regions: Voronoi Diagram

NN Voronoi decision regions
Nearest Neighbour creates a Voronoi diagram: each region is assigned the label of the nearest training point.

CIFAR-10 Results

CIFAR-10 has 10 classes, 50,000 training images, and 10,000 test images (32×32 color).

CIFAR-10 dataset overview
CIFAR-10: 10 classes (airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck).
NN results on CIFAR-10
NN on CIFAR-10: each row shows a test image (left) and its 10 nearest training neighbors. Many neighbors come from wrong classes — pixel similarity does not capture semantic meaning.
Key limitation
NN is essentially free at training time but extremely slow at test time: every test image requires comparing against all $N$ training images. With 50,000 training images and 3,072 pixels each, this is $\sim$150 million operations per test image.

4. K-Nearest Neighbour (K-NN) Classifier

Instead of using the single nearest neighbor, find the K closest training points and use majority voting:

K-NN Prediction Rule
$\hat{y} = \text{mode}\{y_1, y_2, \ldots, y_K\}$ where $y_1, \ldots, y_K$ are labels of the K nearest training points.
K-NN decision boundaries for K=1, K=3, K=5
Decision boundaries for K=1 (jagged Voronoi), K=3 (smoother), and K=5 (smoothest). White regions = no majority class.
K ValueBoundaryBiasVariance
K = 1Jagged, complexLow (fits training data)High (overfits to noise)
K = 3SmootherMediumMedium
K = 5Smoothest, may have undecided regionsHigherLower (generalizes better)
K-NN strengths and limitations

Strengths: Simple, no explicit training, non-parametric (no distribution assumptions), naturally multi-class.

Limitations: Low accuracy for pixel-based image comparison; O(N×k) test cost; high memory (stores all training data); distance metrics are uninformative for raw pixels.

Conclusion: Rarely used in practice for image classification, but introduces the key concepts of data-driven and distance-based classification.

K-NN Classifier Interactive
Click canvas to place a test point
Press "Generate Data" to create training points, then click to classify.

5. Linear Classifiers

Instead of comparing images by distance, linear classifiers use a parametric model — a mathematical function with learnable parameters.

Linear Classifier
$$f(\mathbf{x}, \mathbf{W}) = \mathbf{W}\mathbf{x} + \mathbf{b}$$

$\mathbf{x}$ = input vector ($n \times 1$); $\mathbf{W}$ = weight matrix ($C \times n$, where $C$ = number of classes); $\mathbf{b}$ = bias vector ($C \times 1$); output = $C$ class scores.

Linear classifier equation for real images
For a 32x32x3 CIFAR-10 image: x is 3072x1, W is 10x3072, output is 10 class scores.

Multi-Class Example

Multi-class weight matrix W
Weight matrix W with 3 rows (cat, dog, ship) and 4 columns (one weight per pixel).
Output class scores: Cat, Dog, Ship
Class scores for a 4-pixel input: Cat = -96.8, Dog = 437.9, Ship = 61.95. Prediction: Dog (highest score).
Training vs Testing
Training finds the optimal weights $\mathbf{W}$ and biases $\mathbf{b}$ (e.g., via gradient descent). Testing is a single matrix multiplication — very fast at $O(C \times n)$ per image. This is the key advantage over NN/K-NN.
Linear Classifier Interactive

6. Haar-like Features

Raw pixel values change with viewpoint and lighting. Haar-like features encode local structural patterns (edges, lines, rectangles) that are more robust to such variations.

Types of Haar-like Features

Haar-like feature types: edge, line, four-rectangle
(a) Edge features: adjacent white/black rectangles. (b) Line features: 3 alternating rectangles. (c) Four-rectangle features: 2x2 checkerboard.

Computing Haar Features

  1. Assign weight +1 to white pixels in the mask, -1 to black pixels.
  2. Slide the mask over the image at every possible position.
  3. At each position, compute the weighted sum (white sum − black sum).
  4. If $|\text{white sum} - \text{black sum}| > \tau$ (threshold), a Haar feature is detected.
Worked example: Haar feature computation

For the horizontal edge mask (top 2 rows = +1, bottom 2 rows = -1) applied to a 4x4 patch:

Image patch:        Mask:
 2  3  2  3        +1 +1 +1 +1
 2  2  3  3        +1 +1 +1 +1
 8  9  8  7        -1 -1 -1 -1
 7  8  9  8        -1 -1 -1 -1

White sum = 2+3+2+3+2+2+3+3 = 20
Black sum = 8+9+8+7+7+8+9+8 = 64
Response = |20 - 64| = 44 > threshold (5) --> Feature DETECTED

This makes intuitive sense: there is a strong horizontal edge between rows 2 and 3.

Haar Features in a Linear Classifier

Each Haar feature type becomes one dimension of the feature vector. The linear classifier learns weights $W_{C,i}$ for each feature $x_i$ per class $C$:

$$\text{Score}_C = \sum_i W_{C,i} \cdot x_i$$
Haar features for face detection in stages
AdaBoost selects Haar features in stages: Stage 0 uses the 3 most powerful, Stage 1 adds ~10 more, Stage 21 uses 200+.
StrengthsLimitations
Computationally cheapWeak classifiers individually
Available at any scaleNot invariant to rotation/scale
Good for binary tasks (face/no-face)Too many features — costs in analysis
Simple and intuitivePoor for multi-class problems

7. Dataset Splitting for Machine Learning

Dataset three-way split: training, validation, test
Three-way split: training set (fit parameters), validation set (tune hyperparameters), test set (final evaluation, used once).
SetPurposeWhen Used
TrainingFit model parameters (W, b)During every training run
ValidationTune hyperparameters (K, OO, kernel)After each training run
TestFinal unbiased evaluationOnce, at the very end
Cross-Validation
Split data into $k$ folds. For each fold $i$: train on remaining $k-1$ folds, validate on fold $i$. Average performance across all folds. More robust estimate, especially for small datasets.
Critical rule
The test set must never be used during training or hyperparameter tuning. If you look at test set performance to make decisions, you have contaminated the evaluation and your test accuracy is no longer an unbiased estimate.

8. Support Vector Classifier (Linear)

The SVC finds the optimal separating hyperplane between two classes by maximizing the margin — the distance between the hyperplane and the nearest data points of each class.

1D Case: Hard vs Soft Margins

For binary classification on a 1D feature: a naive threshold at the midpoint between nearest opposite-class samples fits the training data perfectly (low bias) but may generalize poorly (high variance) because outliers can pull it off.

SVC soft margins in 1D
Soft margins: allow omission of $n$ outliers closest to the boundary. Wider margins = better generalization.
Bias-Variance Tradeoff in SVC
More outliers omitted: higher bias (ignores some training data), lower variance (generalizes better).
Fewer outliers omitted: lower bias (fits training data better), higher variance (sensitive to noise).

Hyperplane Mathematics

Hyperplane Equation
$$\mathbf{w}^T\mathbf{x} - b = 0$$

$\mathbf{w}$ = normal vector (perpendicular to hyperplane); $b$ = bias (offset from origin).

A point $\mathbf{x}_i$ is on the positive side if $\mathbf{w}^T\mathbf{x}_i - b > 0$, negative side if $< 0$.

Classification Constraint
Assign $y_i = +1$ to class A, $y_i = -1$ to class B. A correctly classified sample satisfies: $$y_i(\mathbf{w}^T\mathbf{x}_i - b) \geq 0$$ This unifies both classes: if $y_i$ and $\mathbf{w}^T\mathbf{x}_i - b$ have the same sign (correct side), the product is positive.
Worked example: hyperplane side check

Given: $\mathbf{w} = [-2, 1]$, $b = -6$.

  • Point $\mathbf{x}_7 = (5, 1)$: $(-2)(5) + (1)(1) - (-6) = -10 + 1 + 6 = -3 < 0$ (negative side)
  • Point $\mathbf{x}_2 = (1, 1)$: $(-2)(1) + (1)(1) - (-6) = -2 + 1 + 6 = 5 > 0$ (positive side)

If $y = +1$ should be on the positive side, $\mathbf{x}_2$ is correctly classified and $\mathbf{x}_7$ is not.

Multi-Dimensional SVC

SVC in 2D extended to 3D with age
In 2D (mass, height), the boundary is a line. Adding a 3rd feature (age) extends it to a plane.
SVC 3D hyperplane separating classes
In 3D, the SVC finds a plane separating the classes. In n dimensions, it finds an (n-1)-dimensional hyperplane.

Multi-Class SVM

Multi-class SVM decision boundaries
Multi-class SVM: multiple hyperplanes partition the feature space. One-vs-Rest trains C binary classifiers; One-vs-One trains C(C-1)/2 classifiers.

9. SVM — Non-Linear Kernels

Linear SVC fails when data is not linearly separable. The kernel trick maps data to a higher-dimensional space where linear separation is possible.

SVM Kernel Trick Interactive
1D Original Space
2D Feature Space $\phi(x)=(x, x^2)$
Showing linearly separable data. Toggle to see the kernel trick in action.
1D data not separable by a single threshold
1D dosage data: "cured" patients in [3,7], "not cured" at [0,2] and [8,10]. No single threshold can separate them.

Kernel Types

SVM kernel types overview
Different kernels produce different decision boundary shapes: linear (flat), polynomial (curved), RBF (circular/elliptical), sigmoid.
KernelMappingDecision BoundaryUse When
LinearNo transformationFlat hyperplaneData is linearly separable
PolynomialPolynomial feature spaceCurved (degree $d$)Polynomial relationships suspected
RBF / GaussianInfinite-dimensional spaceCircular/elliptical regionsMost common non-linear choice
SigmoidSimilar to neural networkS-shapedLess commonly used

Polynomial Kernel: 1D to 2D

Map each sample $x$ to $(x, x^2)$. Mid-range "cured" values (moderate $x^2$) separate from extreme "not cured" values.

Polynomial kernel: adding x-squared axis
Step 1: Add a $x^2$ axis. 1D samples become 2D points $(x, x^2)$.
Polynomial kernel: linear separation in 2D
Step 2: In 2D space, a linear SVC can now separate the two classes with a straight line.

Polynomial Kernel: 2D to 3D

For circular boundaries in 2D: map $(x_1, x_2) \to (x_1^2, x_2^2, \sqrt{2}x_1x_2)$. In this 3D space, a flat hyperplane separates the classes. Projected back to 2D: circular boundary.

Polynomial kernel: flat plane in 3D space
The circular 2D boundary becomes a flat separating plane in the 3D polynomial feature space.

10. AdaBoost Classifier

Naive Haar classifiers use all 100,000+ features — too slow and most are individually weak. AdaBoost (Adaptive Boosting) selects only the most powerful features and combines them into a strong classifier.

AdaBoost Step-Through Interactive
Round: 0 / not started
Press "Step" to begin the first round of AdaBoost.

Initialization

Assign equal weights to all training images (faces and non-faces):

Initial Sample Weights
$$w_{1,i} = \begin{cases} \frac{1}{2m} & \text{if } y_i = 0 \text{ (non-face)} \\ \frac{1}{2l} & \text{if } y_i = 1 \text{ (face)} \end{cases}$$

$m$ = number of negative examples, $l$ = number of positive examples.

For Each of T Rounds

Step 1: Normalize weights to form a probability distribution: $w_{t,i} \leftarrow w_{t,i} / \sum_j w_{t,j}$

Step 2: Select best weak classifier. For each Haar feature $j$, compute weighted error:

Weighted Error
$$\epsilon_j = \sum_{i=1}^{n} w_{t,i} \cdot |h_j(x_i) - y_i|$$

$h_j(x_i) = 1$ if Haar feature $j$ is found in image $i$ (else 0). Select feature $h_t$ with minimum $\epsilon_t$.

Step 3: Update weights. Misclassified images get higher relative weights — the next round focuses on hard cases:

Weight Update
$$w_{t+1,i} = w_{t,i} \cdot \beta_t^{e_i}, \quad \beta_t = \frac{\epsilon_t}{1 - \epsilon_t}$$

$e_i = 0$ if image $i$ is correctly classified (weight decreases by factor $\beta_t$); $e_i = 1$ if incorrectly classified (weight unchanged). After re-normalization, hard examples get higher relative weight.

Final Strong Classifier

AdaBoost Strong Classifier
$$H(x) = \begin{cases} 1 & \text{if } \sum_{t=1}^{T} \alpha_t \cdot h_t(x) \geq \frac{1}{2}\sum_{t=1}^{T}\alpha_t \\ 0 & \text{otherwise} \end{cases}$$

where $\alpha_t = \log\!\left(\frac{1-\epsilon_t}{\epsilon_t}\right) = \log\!\left(\frac{1}{\beta_t}\right)$.

Features with lower error get higher weight $\alpha_t$. For a test image: extract only the $T$ selected features, compute weighted sum, compare to threshold.

AdaBoost / Viola-Jones algorithm paper
Viola-Jones AdaBoost face detector: selected Haar features and the attentional cascade structure.
AdvantagesDisadvantages
Only uses powerful featuresNeeds many training examples
Training complexity linear in training set sizeSometimes outperformed by SVM (multi-class)
Extremely fast testing ($O(T)$, $T$ typically small)Sensitive to noisy data (high-weighted outliers)
Flexible: any weak learnerBest for binary classification

11. Object Detection (Sliding Window)

Image Pyramid

Objects can appear at any scale. An image pyramid handles this: create copies of the image at decreasing resolutions (1/2, 1/4, 1/8, ...). The fixed-size detector can then find objects of any size.

Image pyramid at multiple scales
Image pyramid: the original is repeatedly blurred and subsampled. A fixed-size sliding window can now detect objects of any original size.

Cascaded Detection (Attentional Cascade)

Sliding a classifier over every position at every scale is slow. Key insight: most windows contain no object — reject them early.

Cascade Principle
Arrange classifiers from most to least powerful. At each window position, apply Stage 1 first. If it fails, immediately reject and move on. Only windows passing all stages are declared detections. Most non-object windows are rejected after just 1–2 feature evaluations.
Cascaded detection flowchart
Cascade: sub-windows pass through increasingly complex stages. Non-face windows are rejected early; only true detections pass all stages.
Why cascading is fast
The vast majority of sub-windows are rejected after only 1–2 feature evaluations (microseconds each). Only a tiny fraction of "promising" windows proceed to the expensive later stages. This achieves real-time detection speeds.

Classifier Comparison Summary

ClassifierTrain CostTest CostAccuracyKey Idea
NNO(1)O(N×k)LowMemorize; nearest example
K-NNO(1)O(N×k)Low-MedMajority vote of K nearest
Linear (pixels)MediumO(C×n)LowLearn weights for each pixel
Linear (Haar)MediumO(C×n)MediumLearn weights for Haar features
SVC (linear)Med-HighO(C×n)Med-HighMaximize margin
SVM (kernel)HighO(C×n)HighNon-linear boundaries via kernels
AdaBoostHighO(T) (very fast)High (binary)Select T best features, weighted vote

Flashcards