DEEP LEARNING AND COMPUTER VISION
DEEP LEARNING AND COMPUTER VISION

DEEP LEARNING AND COMPUTER VISION

Foundations of Computer Vision & Deep Learning

From Pixels to Neural Networks: Complete Visual Recognition Guide

A self-contained, derivation-first handbook building modern visual recognition from scratch—from raw RGB pixel grids, nearest neighbours, and linear classifiers to regularization, AdamW optimization, and backpropagation through multi-layer networks.

Chapters 1–2 included · All derivations worked out · Python + NumPy
Notation. Vectors are column vectors. N is the number of training examples, D the number of input features per example, and C the number of classes. The i-th training pair is (x_i, y_i) with x_i \in \mathbb{R}^D and y_i \in \{1, \dots, C\}. Logarithms are natural.
Part 1

From Pixels to Linear Predictions

How machines represent images, why hand-crafted rules fail, k-NN baselines, validation hygiene, linear decision boundaries, and the Softmax loss.

1.1 What a computer actually sees

Ask a person to spot a car in a photo and the answer is instant. Ask a computer and you discover that “obvious” is a human illusion. To a machine, a colour image with height H and width W is a tensor of shape H \times W \times 3, each entry an integer intensity in [0, 255] across red, green, and blue channels. A 32 \times 32 colour image contains 32 \cdot 32 \cdot 3 = 3{,}072 numbers. A video adds a time axis: a T-frame clip is a T \times H \times W \times 3 tensor.

The core obstacle is the semantic gap: the same physical object yields completely different pixel grids whenever viewing conditions shift:

  • Illumination: Brightness and colour cast alter every pixel intensity.
  • Background clutter: Objects blend into busy surroundings.
  • Scale & viewpoint: Moving or rotating the camera rearranges every coordinate without changing the label.
  • Deformation & occlusion: Non-rigid poses or hidden parts remove expected visual cues.
  • Intra-class variation: “Car” spans hatchbacks, pickup trucks, and sports cars alike.

No brittle list of hand-written rules (“two circles under a box”) survives all five variations simultaneously.

1.2 The data-driven approach

Instead of hard-coding visual rules, we let labelled examples define each category:

  1. Collect a large dataset of images paired with ground-truth labels.
  2. Use a learning algorithm to fit a parameterized model on the training set.
  3. Evaluate the trained model on unseen test images.

Every classifier in this guide follows two interfaces: train(images, labels) to produce a model, and predict(model, test_images) to output predicted class labels.

1.3 The simplest classifier: nearest neighbour

In Nearest Neighbour, train simply memorizes the training data, and predict assigns each query image the label of its closest training image under a chosen distance metric. For two flattened images a, b \in \mathbb{R}^D, the two standard norms are Manhattan (L_1) and Euclidean (L_2) distance:

d_1(a, b) = \sum_{p=1}^{D} |a_p - b_p|, \qquad d_2(a, b) = \sqrt{\sum_{p=1}^{D} (a_p - b_p)^2}

Here is L_1 distance on a tiny 4 \times 4 grayscale patch—subtract element-wise, take absolute values, and sum:

56321018
9023128133
2426178200
20255220
Test patch
10202417
81089100
1216178170
432233112
Training patch
4612141
82133933
1210030
23222108
|Diff| row sums: 73 + 167 + 52 + 164 = 456
nearest_neighbour.py · Python / NumPy
import numpy as np

class NearestNeighbour:
    def train(self, X, y):
        # X: (N, D) flattened images; y: (N,) integer labels
        self.Xtr = X
        self.ytr = y

    def predict(self, X):
        num_test = X.shape[0]
        Ypred = np.zeros(num_test, dtype=self.ytr.dtype)
        for i in range(num_test):
            distances = np.sum(np.abs(self.Xtr - X[i, :]), axis=1)
            Ypred[i] = self.ytr[np.argmin(distances)]
        return Ypred
Derivation: Broadcasting shapes & fast L2 matrix trick

In self.Xtr - X[i, :], self.Xtr has shape (N, D) while X[i, :] has shape (D,). NumPy aligns trailing dimensions and broadcasts the query row across all N training rows, yielding an (N, D) difference matrix before summing across axis=1 into shape (N,), where entry n is \sum_p |X^{\text{tr}}_{np} - x_p| = d_1(X^{\text{tr}}_n, x).

Memory warning: Never broadcast all test and train images at once via X_test[:, None, :] - X_train[None, :, :]—on CIFAR-10 (10{,}000 \times 50{,}000 \times 3{,}072 floats) that allocates ~6 TB of RAM. For L_2 distances, expand \|a - b\|_2^2 = \|a\|_2^2 + \|b\|_2^2 - 2a^\top b using a single matrix multiplication X_test @ X_train.T.

Backwards computational trade-off

Nearest Neighbour takes O(1) time to train, but O(ND) operations per test image (\approx 1.5 \times 10^8 operations per CIFAR-10 image). In production we want fast inference even if training takes longer.

L1 vs. L2 Geometry and k-Nearest Neighbours

L1 unit ball: diamond (axis-aligned) L2 unit ball: circle (rotation-invariant)
Figure 1.1. Points at unit distance from the origin. L_2 is invariant to coordinate rotations (\|Rv\|_2^2 = v^\top R^\top R v = \|v\|_2^2) and penalizes one large pixel spike (4^2 = 16) more heavily than four small shifts (1^2+1^2+1^2+1^2 = 4). Extending 1-NN to k-NN takes a majority vote among the k closest neighbours, smoothing noisy boundaries.

1.4 Choosing hyperparameters honestly

Choices like k and the distance metric are hyperparameters—settings chosen before or outside parameter optimization. Never tune them on the training set (1-NN achieves 100% training accuracy on every dataset because d(x_n, x_n) = 0) and never tune them on the test set (which leaks test information into model selection). Split data into train, validation, and test, or use F-fold cross-validation when data is small:

\mathrm{CV}(h) = \frac{1}{F}\sum_{f=1}^{F}\mathrm{acc}_f(h), \qquad h^* = \arg\max_h \mathrm{CV}(h)
Fold 1Fold 2Fold 3Fold 4 traintraintrainval Held-out Test Set Amber = validation fold rotated each round; test set evaluated once at the end.

1.5 Linear classifiers & geometry

Rather than storing every training image, a parametric linear classifier compresses the training set into a weight matrix W \in \mathbb{R}^{C \times D} and bias vector b \in \mathbb{R}^C, scoring each class via a weighted sum of pixel values:

s = f(x; W, b) = Wx + b, \qquad s_k = w_k^\top x + b_k = \sum_{j=1}^{D} W_{kj}x_j + b_k

For CIFAR-10 (D = 3{,}072,\; C = 10), the entire model takes just 10 \cdot 3{,}072 + 10 = 30{,}730 numbers. Using the bias trick—appending a constant 1 to x as x' = [x^\top, 1]^\top \in \mathbb{R}^{D+1} and appending b as an extra column W' = [W \;\; b] \in \mathbb{R}^{C \times (D+1)}—gives W'x' = Wx + b \cdot 1 = Wx + b.

Convex polyhedral regions Linear failures: XOR & rings
Figure 1.2. Left: Each class region R_c = \bigcap_{j \neq c}\{x : (w_c - w_j)^\top x + (b_c - b_j) \ge 0\} is an intersection of half-spaces, so boundaries are flat hyperplanes. Right: Non-convex patterns like XOR quadrants (g(1,1)+g(-1,-1)=2c \gt 0 vs. g(1,-1)+g(-1,1)=2c \lt 0) and concentric rings cannot be separated by any straight line.

1.6 Learning the weights: Softmax loss & cross-entropy

The Softmax function interprets raw class scores s as unnormalized log-probabilities, exponentiating and normalizing them into a valid probability distribution:

p_k = P(Y = k \mid X = x_i) = \frac{e^{s_k}}{\sum_{j=1}^{C} e^{s_j}} = \frac{e^{s_k - \max_j s_j}}{\sum_{j=1}^{C} e^{s_j - \max_m s_m}}

Subtracting \max_j s_j leaves every probability identical (shift invariance) while keeping all exponents \le 0 so e^s never overflows in floating-point arithmetic. Maximizing dataset log-likelihood \sum_i \log p_{y_i} is equivalent to minimizing the average cross-entropy loss:

L_i = -\log p_{y_i} = -s_{y_i} + \log\sum_{j=1}^{C} e^{s_j}, \qquad L(W) = \frac{1}{N}\sum_{i=1}^{N} L_i
ClassRaw Score sShifted s - 5.1e^{\text{shifted}}Probability p_k
cat (true)3.2-1.90.1500.130 \rightarrow L_i = -\log(0.130) = 2.04
car5.10.01.0000.869
frog-1.7-6.80.0010.001
Derivation: Loss bounds, initialization sanity check & exact gradient

1. Bounds & initialization: Since \sum_j e^{s_j} \gt e^{s_y} for finite scores, L_i \in (0, +\infty). At random initialization with small weights, s_j \approx 0, so p_k \approx 1/C and L_i \approx \log C (e.g., \log 10 \approx 2.30). Checking that your first loss sits near \log C catches wiring and label bugs immediately.

2. Gradient: Differentiating L_i = -s_{y_i} + \log\sum_j e^{s_j} with respect to score s_k gives \partial L_i / \partial s_k = p_k - \mathbb{1}[k = y_i]. Across a minibatch X \in \mathbb{R}^{N \times D} with probability matrix P and one-hot target matrix Y:

\nabla_W L = \frac{1}{N}(P - Y)^\top X \in \mathbb{R}^{C \times D}, \qquad \nabla_b L = \frac{1}{N}(P - Y)^\top \mathbf{1}

3. Information-theoretic view: For one-hot target distribution P (H(P) = 0) and predicted Softmax distribution Q, cross-entropy equals KL divergence: H(P, Q) = H(P) + D_{\mathrm{KL}}(P \,\|\, Q) = -\log Q(y_i). For C = 2, Softmax reduces directly to binary logistic regression p_1 = \sigma(s_1 - s_0).

1.7 Beyond single-image classification

These exact building blocks extend directly to video classification (sequences of H \times W \times 3 frames), multimodal vision-language models (pairing image tensors with text embeddings), and model interpretability (visualizing which input pixels drive a class score). ↑ Back to Table of Contents

Part 2

Margins, Regularization, Optimization & Backpropagation

Multiclass SVM vs. Softmax, preventing overfitting with L1/L2 penalties, SGD, Momentum & AdamW, non-linear layers, and computational-graph backprop.

2.1 Margin vs. Probability: Multiclass SVM & Softmax

Softmax is not the only way to judge raw class scores s = Wx_i + b. The Multiclass Support Vector Machine (Hinge) Loss asks a geometric question: does the true class score exceed every wrong class score by at least a safety margin \Delta?

L_i^{\mathrm{SVM}} = \sum_{j \neq y_i} \max\!\big(0,\; s_j - s_{y_i} + \Delta\big)

Setting \Delta = 1, test a three-class score vector s = [2.1,\; 1.8,\; -0.5] where the true class is y_i = 0:

  • Against class 1: \max(0,\; 1.8 - 2.1 + 1.0) = 0.7 (class 0 leads by 0.3, short of the 1.0 margin).
  • Against class 2: \max(0,\; -0.5 - 2.1 + 1.0) = 0 (margin already satisfied).
  • Total SVM loss: L_i^{\mathrm{SVM}} = 0.7.

Once an update lifts s_0 to 3.5 (s = [3.5,\; 1.8,\; -0.5]), every wrong class trails by more than 1.0, so L_i^{\mathrm{SVM}} = 0.0 and the example’s gradient vanishes. Softmax at the same scores assigns p_0 \approx 0.833 (L_i \approx 0.183) and keeps nudging p_0 \to 1.

PropertyMulticlass SVM (Hinge)Softmax (Cross-Entropy)
Output meaningUnnormalized margin scoresCalibrated probabilities p \in (0, 1)^C
Confidently right exampleLoss hits exactly 0; stops updating weightsLoss approaches 0 asymptotically; keeps refining
Vision usage todayRare in end-to-end deep networksStandard across classification, detection & VLMs

2.2 Regularization: Why Simpler Weights Generalize

Unregularized weights are never unique—doubling W doubles every margin—and high-capacity networks can memorize dataset noise instead of visual structure. Regularization adds a penalty \lambda\, R(W) directly to the training objective:

L(W) = \frac{1}{N}\sum_{i=1}^{N} L_i\big(f(x_i; W), y_i\big) + \lambda\, R(W)

L2 Regularization (Weight Decay)

R_2(W) = \frac{1}{2}\sum_{k,l} W_{k,l}^2. Penalizes large squared weights, spreading influence smoothly across many pixels rather than relying on one feature.

L1 Regularization (Sparsity)

R_1(W) = \sum_{k,l} |W_{k,l}|. Drives weak weights to exact zero, performing automatic feature selection.

For input x = [1, 1, 1, 1]^\top, both w_A = [1, 0, 0, 0]^\top and w_B = [0.25, 0.25, 0.25, 0.25]^\top give w^\top x = 1, yet \|w_B\|_2^2 = 0.25 vs. \|w_A\|_2^2 = 1.00—so L2 strongly prefers distributed, occlusion-resilient weights. Note: exclude biases b and normalization scales from weight decay.

L2 Regularization (Dense & Smooth) Contours touch circle at non-zero (w₁, w₂) L1 Regularization (Sparse Corners) Contours hit axis corner (w₁ = 0)
Figure 2.1. Expanding loss contours (orange) around the unregularized minimum meet the L1 diamond at sharp axis corners, zeroing out coordinates.

2.3 Optimization: SGD, Momentum, AdamW & Schedules

In minibatch Stochastic Gradient Descent (SGD), we sample a random batch \mathcal{B} of images and step opposite the batch gradient with learning rate \eta: \theta_{t+1} = \theta_t - \eta\,\nabla_\theta L_{\mathcal{B}}(\theta_t). Because neural loss surfaces form narrow ravines (steep across walls, flat along the valley floor), vanilla SGD oscillates across the steep walls. AdamW combines momentum (m_t) with per-parameter adaptive step scaling (v_t) and decoupled weight decay:

m_t = \beta_1 m_{t-1} + (1 - \beta_1)\,g_t, \qquad \hat{m}_t = \frac{m_t}{1 - \beta_1^t} v_t = \beta_2 v_{t-1} + (1 - \beta_2)\,(g_t \odot g_t), \qquad \hat{v}_t = \frac{v_t}{1 - \beta_2^t} \theta_t = (1 - \eta\lambda)\,\theta_{t-1} - \eta\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}
Minimum Vanilla SGD (oscillates on walls) Momentum / AdamW (damped, fast)
Figure 2.2. Pair AdamW (\beta_1=0.9,\; \beta_2=0.999,\; \epsilon=10^{-8}) with a short linear warmup followed by cosine decay \eta_t = \frac{1}{2}\eta_{\max}\!\left(1 + \cos\frac{\pi t}{T}\right).

2.4 Beyond Lines: Hidden Layers & Activations

A linear classifier gives each class only one template row w_c—averaging left-facing and right-facing horses into a blur. Stacking two linear layers without a non-linearity collapses back into one matrix (W_2 W_1 x). Inserting a non-linear activation \phi(\cdot) unlocks multi-template feature hierarchies:

h = \phi(W_1 x + b_1), \qquad s = W_2 h + b_2
ActivationFormula \phi(z)Behavior
Sigmoid\frac{1}{1 + e^{-z}}Saturates for |z| \gg 0 (vanishing gradients); not zero-centered.
Tanh\frac{e^z - e^{-z}}{e^z + e^{-z}}Zero-centered (-1, 1), still saturates at extremes.
ReLU\max(0, z)Fast and non-saturating for z \gt 0; watch for dead units when z \le 0.
GELU / SiLUz\,\Phi(z) or z\,\sigma(z)Smooth around zero; standard in Vision Transformers and modern ConvNets.

2.5 Backpropagation on Computational Graphs

Backpropagation applies the multivariable chain rule locally at every node of a computational graph. Each gate receives an upstream gradient \frac{\partial L}{\partial z} and multiplies by its local gradients (\frac{\partial z}{\partial u}, \frac{\partial z}{\partial v}) to send downstream gradients backward:

\frac{\partial L}{\partial u} = \frac{\partial L}{\partial z}\cdot\frac{\partial z}{\partial u}, \qquad \frac{\partial L}{\partial v} = \frac{\partial L}{\partial z}\cdot\frac{\partial z}{\partial v}

Here is f(x, y, z) = (xy + z)^2 evaluated at x = 2,\; y = -3,\; z = 4:

x y z × + (·)² 2 −3 a = −6 4 b = −2 f = 4 +12 −8 −4 −4 −4 1 Top: forward values Bottom: ∂f / ∂(edge)
Figure 2.3. Gate patterns: add copies upstream gradients equally; multiply swaps inputs and scales by the upstream gradient; max routes gradient only to the larger branch; and fork sums gradients from all outgoing branches.
Derivation: Vectorized Matrix-Multiply Backward Pass (Shape-Checking Rule)

For a minibatch linear layer Y = XW + b with X \in \mathbb{R}^{N \times D}, W \in \mathbb{R}^{D \times H}, and upstream gradient G = \frac{\partial L}{\partial Y} \in \mathbb{R}^{N \times H}, matching tensor dimensions uniquely determines every backward matrix product:

\frac{\partial L}{\partial X} = G W^\top \;(N \times D), \qquad \frac{\partial L}{\partial W} = X^\top G \;(D \times H), \qquad \frac{\partial L}{\partial b} = \sum_{i=1}^{N} G_{i,:} \;(H,)

2.6 A Complete Two-Layer Network in NumPy

Below is a full two-layer network (X \to \mathrm{Linear} \to \mathrm{ReLU} \to \mathrm{Linear} \to \mathrm{Softmax} + L_2) verified against centered finite-difference gradient checking:

two_layer_net.py · Python / NumPy
import numpy as np

def two_layer_loss_and_grads(X, y, params, reg=1e-3):
    W1, b1 = params["W1"], params["b1"]
    W2, b2 = params["W2"], params["b2"]
    N = X.shape[0]

    # Forward pass
    z1 = X @ W1 + b1
    h1 = np.maximum(0.0, z1)
    scores = h1 @ W2 + b2

    shifted = scores - np.max(scores, axis=1, keepdims=True)
    probs = np.exp(shifted)
    probs /= np.sum(probs, axis=1, keepdims=True)

    loss = -np.mean(np.log(probs[np.arange(N), y] + 1e-12))
    loss += 0.5 * reg * (np.sum(W1 * W1) + np.sum(W2 * W2))

    # Backward pass
    dscores = probs.copy()
    dscores[np.arange(N), y] -= 1.0
    dscores /= N

    dW2 = h1.T @ dscores + reg * W2
    db2 = np.sum(dscores, axis=0)
    dh1 = dscores @ W2.T
    dz1 = dh1 * (z1 > 0)
    dW1 = X.T @ dz1 + reg * W1
    db1 = np.sum(dz1, axis=0)

    return loss, {"W1": dW1, "b1": db1, "W2": dW2, "b2": db2}


def numeric_grad_check(f, x, eps=1e-5):
    grad = np.zeros_like(x)
    it = np.nditer(x, flags=["multi_index"], op_flags=["readwrite"])
    while not it.finished:
        idx = it.multi_index
        old = x[idx]
        x[idx] = old + eps; fx_pos = f()
        x[idx] = old - eps; fx_neg = f()
        x[idx] = old
        grad[idx] = (fx_pos - fx_neg) / (2.0 * eps)
        it.iternext()
    return grad


rng = np.random.default_rng(42)
X = rng.normal(size=(8, 5))
y = rng.integers(0, 3, size=8)
params = {
    "W1": rng.normal(scale=0.1, size=(5, 6)), "b1": np.zeros(6),
    "W2": rng.normal(scale=0.1, size=(6, 3)), "b2": np.zeros(3),
}
loss, grads = two_layer_loss_and_grads(X, y, params)
num_dW1 = numeric_grad_check(lambda: two_layer_loss_and_grads(X, y, params)[0], params["W1"])
rel_err = np.max(np.abs(grads["W1"] - num_dW1) / np.maximum(1e-8, np.abs(grads["W1"]) + np.abs(num_dW1)))
print(f"Loss: {loss:.4f} | Max relative error on W1: {rel_err:.2e}")