How does a computer turn pixels into the label "cat"?
A cat walks into your phone's camera. The phone decides: this is a cat. Between those two moments runs a chain of specific decisions, each one repairing a failure in the step before it. This tutorial walks that whole chain the way the AIAA3201 Week 5 deck builds it: filters read structure out of a grid of numbers, Canny turns fuzzy bands into clean lines, Harris and SIFT make those lines survive the camera moving, and a learned classifier finally converts all of that structure into a decision. By the end you will be able to tell the story of the cat, step by step, in terms of numbers and gradients instead of magic.
1. What does a computer actually receive when it "looks at" a picture?
A filter is a small patch of weights slid across the image
The deck opens where the previous week left off: image filtering. The idea is deceptively simple. Take a small patch of weights, a filter or kernel, lay it on top of a region of the image, multiply the two grids entry by entry, and add everything up. Then slide the patch one pixel, repeat, and write each result into a response map. That is the whole operation, and the same operation will reappear later as convolution inside neural networks.
To see what a filter actually does, the deck works one example by hand. Here is a 10×10 image whose pixels are either 0 (dark) or 90 (bright), with a bright blob sitting on a dark background:
| c0 | c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8 | c9 | |
|---|---|---|---|---|---|---|---|---|---|---|
| r0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| r1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| r2 | 0 | 0 | 0 | 90 | 90 | 90 | 90 | 90 | 0 | 0 |
| r3 | 0 | 0 | 0 | 90 | 90 | 90 | 90 | 90 | 0 | 0 |
| r4 | 0 | 0 | 0 | 90 | 90 | 90 | 90 | 90 | 0 | 0 |
| r5 | 0 | 0 | 0 | 90 | 0 | 90 | 90 | 90 | 0 | 0 |
| r6 | 0 | 0 | 0 | 90 | 90 | 90 | 90 | 90 | 0 | 0 |
| r7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| r8 | 0 | 0 | 90 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| r9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
Slide a 3×3 box filter (all ones, divided by 9, although the scaling does not matter for the argument) across this grid and watch the response matrix fill in frame by frame. The first cell reads 0. Then 0 10. Then 0 10 20. Then 0 10 20 30. Eventually, at row 4, column 4, a 50 appears. Here is the observation the whole course is built on: in flat regions the response stays 0, and it becomes non-zero only where intensity changes, along the boundary of the blob. The magnitude grows, 10, 20, 30, 50, as more of the bright region slides into the 3×3 window. The filter does not care about constant areas at all; it responds to change. This is the same operation CS231n describes when it says we slide each filter across the input and compute dot products between the filter and the input at every position, producing a 2D activation map of that filter's responses.CS231n Filtering
Averaging and differencing: two ways to read the same grid
Once you see filters as "small patches that respond to change," the rest of the filter family is just different patches.
Gaussian smoothing is an averaging filter whose weights follow a bell shape: the pixel in the middle of the patch matters most, and pixels further away matter less and less. Its purpose is low-pass filtering, averaging away high-frequency noise (single-pixel speckles) while preserving the overall structure, exactly the way a blurry photo still shows you what the picture is of. The deck shows the kernel's shape visually:

Caption:A single diffuse white glow, brightest at its center and fading smoothly to darkness. This is the shape of a smoothing kernel's energy distribution: the center dominates, the contributions fall off smoothly with distance, nothing jumps discontinuously.
The Sobel filters are the opposite instinct: instead of averaging, they compute differences, first derivatives of the intensity field. The Sobel X kernel detects brightness changes left to right (vertical edges, shown as the absolute value of the response):
| -1 | 0 | 1 |
|---|---|---|
| -2 | 0 | 2 |
| -1 | 0 | 1 |
The Sobel Y kernel detects brightness changes top to bottom (horizontal edges):
| -1 | -2 | -1 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 2 | 1 |
Run either kernel over a whole image and the response map is a picture of everywhere the intensity is changing, which is to say an edge map:

Caption:A portrait reduced to its outlines, with facial features, hair texture and clothing traced as bright lines on a black background. This is the look of a gradient response map: it keeps only the high-frequency changes, and everything flat has gone dark.
Template matching, and what happens when you get greedy
The same machinery becomes template matching the moment the filter is not a generic edge detector but a picture of something you want to find. The deck's running example: find an eye in a portrait by filtering with the eye patch itself. This fails in an instructive way. When the template has a non-zero mean brightness, the raw correlation response is dominated by the template's mean rather than by local structure; bright patches everywhere look like an eye. Subtract the mean from the filter first (zero-mean correlation), and the response lights up only where the local structure actually matches the patch, yielding mostly true detections. The third option, SSD (sum of squared differences), measures how different two patches are, and the deck uses 1 − sqrt(SSD) as the similarity score: small SSD means the window looks like the template.
Filters compose into surprisingly sophisticated results. The deck's hybrid images example (Oliva, Torralba & Schyns, SIGGRAPH 2006) takes two photos, low-passes one with a Gaussian and high-passes the other with a Laplacian, then adds them:

Caption:The hybrid images construction. The elephant is low-pass filtered into a blur (top path), the leopard is high-pass filtered into a gray silhouette of edges (bottom path), and the two are added. Close up you read the leopard; step back a few meters the coarse elephant outline takes over. Low-pass and high-pass are choices about which frequencies to keep.
Two forward glances close the chapter. The first: filters do not have to be hand-designed. The 96 small patches below are edge and color filters that a neural net learned on its own from data, and they live under exactly the same "slide a patch, compute a dot product" formula as the Sobel kernels. The second: stack many filter responses on top of each other and you have a deep network, each column of activations being one layer's response map.CS231n Filtering
(filter response maps stacked layer by layer) = a convolutional network
That is the horizon. But first the deck has a narrower problem to solve. Look at any filter response and you will see it: an edge comes back as a fuzzy band five to ten pixels wide, not a clean line. The next chapter is about turning that band into a single-pixel-thin edge.
2. How do you turn a fuzzy thick band into a clean one-pixel line?
Canny is not one operator, it is five decisions
The deck introduces Canny as "the gold standard (40+ years)" of edge detection, and the way to understand it is not as a single magic operator but as a pipeline of five steps, each of which exists because the naive version of that step failed:
| Step | Operation | Purpose |
|---|---|---|
| 1 | Gaussian smoothing | Remove noise |
| 2 | Gradient computation | Find candidate edges (the Sobel of the previous chapter) |
| 3 | Non-maximum suppression | Thin edges to a single pixel |
| 4 | Dual threshold | Classify strong vs weak edges |
| 5 | Edge tracking by hysteresis | Connect valid weak edges |
Steps 1 and 2 are already built from the last chapter's parts, so the new work, and the deck's real emphasis, is steps 3 through 5. Canny's own paper frames the whole design around three goals: don't miss real edges, mark edges at the true location, and produce only one response per edge.Canny
Non-maximum suppression: keep the ridge, thin the band
Why is the gradient output a band at all? Because the intensity does not jump in one pixel; it ramps over several, so the gradient magnitude is large across the whole ramp. The response is a ridge with a peak in the middle and sloping sides. We want the ridge line, not the whole hill:

Caption:Gradient magnitude plotted against position: a bell curve. The peak at the top is marked "Keep (local maximum)"; the points on both descending sides are marked "Suppress (not maximum)". Non-maximum suppression is precisely this: walk along the gradient direction and keep only the local maximum.
The subtlety is the direction to walk along. The gradient points across the edge, so the comparison must happen along the gradient direction, not along rows or columns. The deck handles this with quantization: snap the continuous gradient angle to one of four directions, and compare the current pixel only with its two neighbours lying along that direction:
| Angle range | Quantized direction | Compare with |
|---|---|---|
| −22.5° to 22.5° | 0° | Left & right |
| 22.5° to 67.5° | 45° | Diagonal (↖ & ↘) |
| 67.5° to 112.5° | 90° | Top & bottom |
| 112.5° to 157.5° | 135° | Diagonal (↗ & ↙) |

Caption:The four quantized directions, each drawn on a 3×3 grid around the central pixel P. For 0° P is compared with its left and right neighbours, for 45° with the upper-left and lower-right, for 90° with top and bottom, for 135° with upper-right and lower-left. The highlighted cells are the neighbours that decide whether P survives.
The rule is one line: if the current pixel is at least as large as both neighbours along its quantized direction, keep it; otherwise suppress it. The band collapses to the ridge, and edges become single-pixel thin.
One threshold cannot win, so use two
The next question is which pixels to keep at all, and here the deck sets up a trap. A single threshold is an impossible trade-off:
| τ too high | τ too low | |
|---|---|---|
| Noise | suppressed | false edges appear |
| Continuity | real edges break into pieces | edges stay complete |
Set the threshold high and noise dies but contours fragment. Set it low and contours stay whole but the response fills with junk. Canny's answer is to stop asking one question and ask two. The deck's figure shows the resulting three-class system:

Caption:Two thresholds split every pixel into three classes, read off the magnitude bar on the right: above T_high is a strong edge, always kept as an anchor (red); between T_low and T_high is weak, kept only if connected to a strong edge (green checkmark) and discarded if isolated (red X); below T_low is a non-edge. "Strength alone isn't enough, connectivity decides."
The three classes: strong (magnitude ≥ T_high), always kept, these are the anchors; non-edge (magnitude < T_low), always discarded; and weak (in between), kept provisionally. Canny's own recommendation for the ratio between the two thresholds is 2:1 to 3:1, with 3:1 being what OpenCV uses by default.Canny
Hysteresis: weak edges live or die by their neighbours
The third class, weak, needs a verdict, and the verdict is not about strength at all. It is about connectivity. The algorithm starts from every strong pixel as a seed, searches the 8-connected neighbourhood for weak pixels, promotes any weak pixel that touches a strong one, and discards isolated weak pixels as noise. The deck's own mnemonic: "Strong edges are seeds. Weak edges near seeds grow. Isolated weak edges die!" The propagation picture makes the mechanism concrete:

Caption:Edge tracking by hysteresis on a pixel grid. Red cells are strong-edge seeds. Yellow cells adjacent to red are promoted to strong and kept ("Connected Weak → Keep"); the separate cluster of yellow cells on the right has no strong neighbour and is discarded ("Isolated Weak → Discard").
This is what turns a fragmented binary ridge map into continuous contours. A faint segment of a real edge is rescued because it touches a strong segment; a speck of noise is killed because nothing touches it. The final step of the chapter is purely mechanical: walk each connected contour from start to finish. The deck pictures it as raster scanning the binary image, tracing each boundary pixel by pixel until you return to the start, one complete contour per trip, in the way a blind person touches a wall and follows it with a hand back to where they began.Canny

Caption:Contour tracing on a grid. The teal arrows numbered 1 to 10 walk the boundary of the white shape, starting at the red "Start" marker and returning to it, closing one complete contour ("✓ Complete contour!"). The white arrows at the top show the left-to-right, top-to-bottom raster scan that finds each boundary in the first place.
So Canny is five decisions in a row: smooth, differentiate, thin to the ridge, threshold twice, connect by neighbourhood. Each decision repairs the failure of a naive approach, which is why it has survived four decades as the default edge detector. But the chapter closes with a catch spelled out in the deck: these clean edges are still bound to one viewpoint. Move the camera and they stop lining up. The next chapter hunts for anchors that survive the camera moving.
3. Why do corners beat edges once the camera moves?
The matching challenge as a design brief
Your brain does it effortlessly: look at two photos of the same building and you line up the windows, the balcony, the door. The computer-vision version of that act is finding correspondences, pairs of points in the two views that are the same physical point. The deck sets the problem with two photos of the same brick facade:

Caption:The same brick facade twice: flat cool light on the left, warm golden-hour light on the right. Every pixel value differs between the views, and geometry shifts with the viewpoint, yet the windows, balcony, posters and door still line up to the eye. The job is to make a computer find those same anchors automatically.
The problem statement reduces to two sentences: pixels change (intensity, color) and geometry changes (perspective), so the goal is to find invariants, anchors that persist across both. Here is the design brief the rest of the chapter works against. Flat regions are useless (nothing to lock on to), and a single edge is nearly useless too, because an edge only constrains location in one direction: slide a window along the edge and nothing changes. What constrains location in two directions at once is a corner.
Harris: the corner as a mathematical quantity
The Harris detector quantifies "corner-ness" by asking what happens to a small window around each point when you shift it a little. Slide the window in every direction at once and measure the intensity change between the original window and the shifted one. In a flat region nothing changes in any direction. Along an edge nothing changes in the along-edge direction. At a corner, every direction changes a lot. The mathematics wraps this intuition into a matrix, the structure tensor M, which collects the gradient energy inside the window. The neat part is that the response never requires computing eigenvalues explicitly:
$$R = \det(M) - k \cdot \operatorname{tr}(M)^2$$
where the determinant and trace of M equal the product and sum of its eigenvalues, so the corner reply is read off directly from the matrix entries. Large positive R means both eigenvalues large, a corner; |R| small means both small, flat; large negative R means one large and one small, an edge. The deck's picture makes the three shapes tangible:

Caption:The three neighbourhood types and their structure-tensor shapes. A flat patch has small gradients in all directions, a tiny circle of eigenvalues. An edge has gradient mostly in one direction, a thin ellipse. A corner has strong gradients in two directions, a large round ellipse. Classifying a pixel is classifying which of these three shapes its window produces.
One honest footnote belongs here. The widely quoted default k ≈ 0.04–0.06 is a community convention adopted by later implementations (OpenCV, MATLAB); the 1988 Harris and Stephens paper writes the formula symbolically and never fixes a numerical value.Harris
SIFT: three problems, three engineering fixes
Harris tells you where a keypoint is. It does not tell you what it looks like, and for matching across views you need a description that stays the same when the camera zooms, rotates, or the light changes. The deck frames SIFT as three problems, each with one engineered solution.
Problem one: scale. The same corner looks different from two meters and from twenty. The answer is the Difference of Gaussians (DoG) scale space. Build a Gaussian pyramid, images blurred at increasing σ, subtract adjacent layers, and hunt for 3-D extrema in the resulting volume, points that are extreme in space and in scale simultaneously. A candidate must beat all 26 neighbours: 8 in its own layer, 9 in the layer above, 9 below:

Caption:DoG scale space. Blurred images at increasing σ (left stack) are subtracted layer by layer into the DoG pyramid (right stack). A keypoint is a 3-D extremum in this volume: it must be larger or smaller than all 26 neighbours, 8 spatial plus 9 above and 9 below, which the orange cube encloses.
Each surviving keypoint records its σ, and the descriptor patch size is proportional to it, so the same corner found at different distances gets described at its natural scale.SIFT
Problem two: rotation. If the camera rotates, the patch around a keypoint rotates with it. The fix is to measure the prevailing direction first: collect all gradient orientations in the neighbourhood into a 36-bin histogram and take the tallest peak as the dominant orientation:

Caption:Rotation invariance in three steps. Left: the gradient arrows inside the keypoint neighbourhood. Middle: their orientations accumulated into a 36-bin histogram, with one bar towering above the rest. Right: the tallest peak becomes the dominant orientation, and the coordinate system is rotated to align with it, so "up" is always relative to the feature's own structure, never to the camera's.
After this alignment, a rotated camera produces the same oriented patch as an unrotated one. Problem three: lighting. Raw pixel values swing with brightness, so the descriptor stores not pixels but gradient orientation histograms: divide the aligned, scale-normalized 16×16 neighbourhood into a 4×4 grid of cells, make an 8-bin orientation histogram per cell, and concatenate, giving 16 × 8 = 128 numbers. Normalize the vector to unit length, clip each entry at 0.2, and normalize again, which caps the influence of any single large gradient and makes the descriptor robust to brightness shifts:SIFT

Caption:The 128-D descriptor pipeline: the 16×16 raw patch, its local gradient vectors, the 4×4 spatial pooling grid, and the final 128-bin histogram vector. By this point the patch is scale-normalized and orientation-aligned, so the vector describes the feature rather than the camera geometry.
From candidate matches to verified ones
With a 128-D descriptor per keypoint, matching is a nearest-neighbour problem: for each descriptor in image A, find its closest descriptor in image B. Run that naively and you get many false matches, because repetitive texture produces many look-alike descriptors. The deck's first filter is Lowe's ratio test. Find the two nearest neighbours and look at the distance ratio:

Caption:The ratio test, in the deck's own framing. A query descriptor q finds its nearest neighbour m1 at distance d1 and its second-nearest m2 at distance d2. If d1/d2 < 0.75, the best match is clearly best, so keep it. If both distances are similar, the query is ambiguous or repetitive texture, and the match is discarded.
The intuition: a unique match stands far apart from the runner-up; a repetitive patch has two equally plausible matches and should not be trusted. Distances that are large and similar mean no real correspondence at all.
The surviving matches are still only candidate matches based on appearance. The final arbiter is geometric. The deck's second filter is RANSAC, which assumes the two views of a planar scene are related by a homography, a projective transform with 8 degrees of freedom (a 3×3 matrix minus scale ambiguity), solvable from 4 point correspondences. RANSAC does not trust the matches; it tests them:

Caption:RANSAC as a loop. Sample 4 pairs of matches, solve the homography H from them, count how many other matches agree with H within a small tolerance ε, and repeat. Keep the H with the most inliers and re-fit on the whole inlier set. Green solid lines are inlier matches, red dashed lines are outliers the current H rejects.
The beauty of RANSAC is that it tolerates a shocking amount of garbage. Fischler and Bolles showed it keeps working even when fewer than half the data points are correct, precisely the regime that destroys least-squares fitting; their recipe is to use the smallest data set that instantiates the model and then enlarge it with consistent data. A quick calculation makes the cost visible: if half the candidate matches are wrong (w = 0.5) and each trial needs 4 samples, reaching a 90% confidence of at least one all-correct sample takes about 36 trials.RANSAC
The chapter's payoff picture shows the two facade photos again, now stitched across by the matches that survived the entire ladder:

Caption:The payoff: the same two views, now connected by thin green lines whose endpoints are matched keypoints. The title of the deck's own figure names the recipe: "Final: SIFT + Ratio + RANSAC". What you see is the small set of correspondences that survived scale-space detection, the ratio test, and geometric verification.
The chain from Chapter 1 to here has produced structure: anchors that persist across scale, rotation, lighting and viewpoint. But finding structure is not the same as making a decision. Nothing so far answers the question that heads Part 4 of the deck: which label does an image deserve?
4. The machine can find structure now, so how does it decide "this is a cat"?
The problem as the computer sees it
Here is the deck's running example, as you see it:

Caption:The gray tabby. This is the version of the input a person sees, and it is precisely not what the computer receives.
What the computer receives is a tensor of integers in [0, 255], an 800×600 grid with three color channels per cell making 800×600×3 numbers. A 4×4 slice of such a grid looks like this:
| c0 | c1 | c2 | c3 | |
|---|---|---|---|---|
| r0 | 118 | 121 | 102 | 96 |
| r1 | 124 | 110 | 88 | 70 |
| r2 | 130 | 96 | 71 | 58 |
| r3 | 121 | 84 | 66 | 63 |
(Toy values for illustration; the real grid is a wall of numbers like these, 26 rows of them in the deck.) There is no cat in the grid, only brightness readings. The deck is emphatic: the computer never "sees" a cat, it sees a grid of numbers. Then comes the uncomfortable part, the challenge list of why those numbers are an unstable representation of content: background clutter (a cat among leaves vs a cat in snow), illumination (the same cat lit from different sides), occlusion (a cat under a blanket, a cat behind grass), deformation (a cat sprawled, a cat standing), and intra-class variation (five kittens that all look different). And the bluntest one of all: every single pixel changes when the camera moves one step. A single pixel value is a very unstable representation of content.
So how do we even hope to classify? The deck's recipe has four steps: collect a dataset of images and labels, extract discriminative features, train a classifier with machine learning, evaluate it on new images. This is the pipeline skeleton [Feature Extraction] → [Machine Learning] that the rest of the course hangs on. The chapter now fills in the first, simplest classifier ever proposed for it: nearest neighbors.
k-NN: memory plus voting
The nearest-neighbor classifier is almost embarrassingly honest. Training is just memorization: store every training image and its label. Testing, for each new image, finds the closest stored image under some distance metric and copies its label. The deck implements it in a few lines, and the essence is two assignments:

Caption:A NearestNeighbor classifier in full. train() contains exactly
self.Xtr = Xandself.ytr = y, storing every training example and its label. predict() loops over the test rows, computes the L1 distance from each test row to every stored example withnp.sum(np.abs(...)), takes the index of the smallest distance, and copies that stored label. Training is memorization, testing is a nearest-neighbour lookup.
The distance metric matters. L1 (Manhattan) distance sums the absolute pixel differences; the deck works one example by hand to show what the computation looks like:

Caption:The L1 distance computed by hand on two 4×4 pixel grids. Subtract the test image and training image pixel by pixel, take absolute values (middle matrix), add everything up: the two grids sit 456 apart. Every pixel contributes equally, which is exactly the problem to come.
Because every training point stores its label and the prediction is a vote, k-NN cuts the feature space into ownership regions. With k = 1 each training point owns the region of space closer to it than to any other point, a Voronoi region, and the query takes whatever label it lands in. The canonical illustration of why that is fragile is CS231n's side-by-side:

Caption:The same point cloud classified twice, once with 1-NN (left) and once with 5-NN (right). With 1-NN an isolated outlier creates a small island of likely incorrect predictions of its own color. With 5-NN those irregularities are smoothed away by majority vote. The white regions are not "untrained" areas; they are explicit tie zones where votes are split.CS231n
Hyperparameters, chosen honestly
k and the distance metric are hyperparameters, choices about the algorithm itself, and they need to be chosen without cheating. The deck walks through three ideas, two of them bad. Idea 1, pick the hyperparameters that work best on the training data: bad, because k = 1 always scores perfectly on the training data it has memorized. Idea 2, pick the ones that work best on the test data: bad, because then the test set is no longer a test; the hyperparameters have been fitted to it and its score no longer predicts performance on new data. Idea 3 is the honest protocol: split the data into train, validation and test; tune hyperparameters on the validation set; evaluate exactly once on the test set at the very end. Idea 4, cross-validation, is the version for small datasets: split the training data into folds, hold out one fold at a time for validation, average the results.
The deck runs 5-fold cross-validation over k on CIFAR-10, the course's staple dataset (10 classes, 50,000 training images, 10,000 test images):

Caption:5-fold cross-validation over k. Each dot is one fold's outcome, the line is the mean across folds, the bars are the spread. The curve climbs steeply from k=1 to a peak around k=7, then gently declines as k grows. For this data, k≈7 is the honest winner. (The transcribed values are approximate.)
The honest summary of k-NN as a classifier: on CIFAR-10, nearest-neighbor under L1 reaches about 38.6% accuracy, and L2 does slightly worse at 35.4%, because L2 prefers many medium disagreements to one big one. Memorization plus voting, done honestly, beats guessing by a wide margin but is nowhere near useful. Worse, k-NN is very slow at test time: there is no learned model, so every query must scan all 50,000 stored images.CS231n
Why pixel distance fails, visibly
The deck saves its most damaging evidence for last. Retrieve the nearest training images to a set of queries, purely by pixel distance, and look at what comes back:

Caption:Nearest-neighbour retrieval under pixel distance, ten queries with nine retrieved images each. A ship query returns dogs and deer; a frog returns cats and what look like planes. The "nearest" image is often not even the right class, because pixel distance tracks background and color, not meaning.
The occlusion pair lands the point with brutal clarity. The same face, once original and once with the eyes and mouth covered:


Caption:The same face twice: the original portrait, and the same portrait with the eyes and mouth covered by black rectangles. To the eye these are the same person; in L1 pixel distance they are enormously far apart. Raw pixels measure appearance at fixed positions, which is why a two-centimeter shift of the camera rewrites everything.
Distance metrics on raw pixels are not informative for semantics, full stop. That is why the course's recipe never feeds raw pixels to the classifier: it runs [Feature Extraction] → [Machine Learning], and the SIFT features of the previous chapter fit naturally into the first box. What is still missing is the second box, a classifier that turns features into a decision as a mathematical object. Chapter 5 builds it.
5. What makes a set of class scores "good"?
From memory to parameters
k-NN's failure has one root: it compares pixels, never ideas. The parametric linear classifier replaces the entire memory bank with a single matrix. The decision is computed as scores = W·x: multiply the pixel vector x by a weight matrix W, and out come 10 numbers, one per class, with the prediction being the class with the largest score. The deck absorbs the bias term into W by appending a constant dimension to x (the bias trick), so everything collapses into one matrix multiply. The only linear algebra actually needed is the shape rule: an A×B matrix times a B×C matrix gives an A×C matrix. If W is C×D (one row per class, one column per pixel), then W·x is a vector of class scores.
There is a wonderfully concrete reading of W. Each row of W is a template for one class: the score for class c is the dot product of the image with the "cat template" row, a measure of how much the image looks like that class. Training now means choosing the numbers in W, not storing images. But choosing them requires a definition of what "good" means, and that is what a loss function is: a single number that scores the current W against the training data.
The SVM loss: demand a margin
Start with the geometry. Draw two classes of points and a separating line. Many lines separate them perfectly, but they are not equal: the line squeezed against the data leaves no room for error, while a line with a wide gap on both sides has room to be wrong and still be right. That gap is the margin:

Caption:The margin as geometry. Two classes, a separating line through the middle, two parallel margin boundaries, and the "Gap" between them marked with a double arrow. The SVM family of losses asks for the widest such gap.
The multiclass SVM hinge loss translates "demand a margin" into numbers. For one training example with true class yᵢ, sum over every wrong class j:
$$L_i = \sum_{j \neq y_i} \max(0,; s_j - s_{y_i} + 1)$$
Read it in plain words. A wrong class contributes nothing if its score is at least 1 below the correct class's score (the margin, conventionally set to Δ = 1). It contributes the shortfall, the amount by which it invaded the margin, otherwise. The deck works the formula by hand on three examples with these class scores:
| Example (true class) | cat score | car score | frog score |
|---|---|---|---|
| cat | 3.2 | 5.1 | −1.7 |
| car | 1.3 | 4.9 | 2.0 |
| frog | 2.2 | 2.5 | −3.1 |
For the cat example: max(0, 5.1 − 3.2 + 1) = 2.9 from the car, plus max(0, −1.7 − 3.2 + 1) = 0 from the frog, so 2.9. For the car example, both wrong-class scores sit below the margin, so the loss is 0. For the frog example, both car and cat crush the wrong margin, 6.3 plus 6.6, so 12.9. The per-example losses are 2.9, 0 and 12.9, and the full data loss is their mean, about 5.27. The deck shows how the whole formula collapses into one vectorized line:

Caption:The entire hinge loss in one vectorized function: compute
scores = W.dot(x), threshold each margin at zero withnp.maximum(0, scores - scores[y] + 1), set the correct class's entry to zero so it contributes nothing, and sum. This is the formula wearing a NumPy costume, exactly the shape of L_i above.CS231n
The family history is worth one line: the 1995 binary soft-margin SVM of Cortes and Vapnik is the ancestor this multiclass formula generalizes, and its core idea is exactly the one drawn above, maximize the margin while tolerating a few mistakes.Cortes & Vapnik
The softmax loss: demand calibrated confidence
The hinge loss has a quirk: once the margin is satisfied, it stops caring. Scores of [10, 9, 9] and [10, −100, −100] both give it zero loss, because both clear the margin by the same amount. The softmax classifier refuses to be so easily satisfied. First squash the scores into probabilities: exponentiate each score so everything is positive, then normalize so everything sums to 1:
$$p(\text{class} = k \mid x) = \frac{e^{s_k}}{\sum_j e^{s_j}}$$
Then take the negative log of the probability of the correct class as the loss. The deck's worked example, with scores cat 3.2, car 5.1, frog −1.7:
| step | cat | car | frog |
|---|---|---|---|
| scores s | 3.2 | 5.1 | −1.7 |
| exp(s) | 24.5 | 164.0 | 0.18 |
| normalized | 0.13 | 0.87 | 0.00 |
If the model is confident and right, p ≈ 1 and the loss is near 0; if the correct class has tiny probability, the loss is huge. The softmax loss treats the scores as relative confidences and keeps pushing the correct class's probability toward 1, even after the classifier is already correct, because a bigger margin always lowers the loss a little more.CS231n
The deck then does the comparison that makes both losses click: same classifier, same scores, two different definitions of good. On the score vector [−2.85, 0.86, 0.28] with class 2 correct, the hinge path computes 1.58 while the cross-entropy path (exp, normalize, −log of the correct class) computes 0.452 (the deck's figure works in log base 10; the same probabilities under the natural log give 1.04, matching the CS231n figure below):

Caption:Same scores, two losses, drawn by the deck: one matrix multiply produces the score vector [−2.85, 0.86, 0.28], which splits into the hinge path (1.58) and the cross-entropy path (exp → normalize → −log of the correct class, 0.452). The two numbers are not comparable to each other; what the picture shows is the mechanism.
CS231n's canonical figure is the same story one level up, and it is worth seeing precisely because it carries the same message with different toy numbers:

Caption:The canonical version of the same idea: one score vector f routed into two loss heads, the SVM margin head on the left (1.58) and the Softmax exp-normalize-log head on the right (1.04, natural log). Those are CS231n's own toy values and are not the deck's numbers; the figure exists to make the mechanism visible, not to compare the losses with each other.CS231n
Why the best W is not unique, and what regularization does
Now a genuinely unsettling observation. Suppose we find a W with zero loss. Is it unique? No. Scale W by any positive factor and every score scales by the same factor, so every margin grows or shrinks proportionally and well-classified points keep their zero loss. Any multiple of a zero-loss W is also zero-loss. But the multiples are not equivalent: as the scale grows, the margins shrink relative to the data, and the decision boundary can end up hugging the training points, which is the classic path to overfitting.
The fix is to stop minimizing the data loss alone and minimize data loss plus a preference over models:
$$L = \frac{1}{N} \sum_i L_i + \lambda R(W)$$
The regularization term R(W) is the numerical form of Occam's razor, the deck's own framing (it even quotes William of Ockham, 1285–1347): among models that explain the data equally well, prefer the simpler one. The standard choice is L2, which penalizes large weights, encoding the preference that no single input dimension should dominate the scores by itself.CS231n
Regularization is a whole design space, and the deck names the descendants in one breath each: dropout (randomly switch off units during training), batch normalization, and mixup (train on convex combinations of examples). All of them are preferences over models expressed in different currencies. The chapter's takeaway is compact: a classifier is a score function (W·x) plus a definition of good (a loss), and "good" is a choice before it is a computation. But the chapter has left one hole open, and the deck is careful to point at it: the loss defines what good looks like, yet nothing so far says how to actually find the W that achieves it.
6. How is the right W actually found, and how do the losses behave in practice?
Guessing doesn't scale
One naive answer deserves a look before being dismissed: search. Generate random weight matrices, keep the one with the lowest loss, repeat. The deck shows the loop as code, including its telltale output lines:

Caption:Random search as code: start with loss at infinity, draw a thousand random weight matrices scaled to stay small, evaluate the loss of each on the whole training set, and keep the best seen so far. The printed lines show the best loss barely edging downward, attempt after attempt: 9.40, 8.96, 9.04, 9.28, 8.86, 8.94, 8.61.
The deck's verdict is withering: on CIFAR-10 this tops out at about 15.5% accuracy, barely better than the 10% a coin flip across ten classes would give, and the state of the art when the deck was written was around 99.7%. The weight space is 30,730-dimensional, and random search is throwing darts in a haystack.CS231n
Gradient descent: follow the slope downhill
What if, instead of guessing, we let the loss surface point the way? At any W, the gradient of the loss is a vector that points in the direction of steepest increase, uphill. So walk the other way:
$$W \leftarrow W - \text{step} \cdot \nabla L$$
The step size is the one dial that matters most. The deck's picture says it in one glance:

Caption:The step-size intuition straight from the deck: hikers descending a U-shaped loss valley. On the steep upper slope the annotation reads "steep slope, value of D is high, so take large steps"; near the bottom the slope is gentler, "so take small steps". The goal marker sits at the valley floor. Gradient descent is this walk, repeated: always step opposite the local slope, with step size tuned to the terrain.
How do you get the gradient? Two ways exist. The numeric gradient approximates it with finite differences, nudging each weight and measuring the loss change, which is exact in spirit but brutally slow for 30,730 weights and useful mainly to check the other method. The analytic gradient works out the derivative formula directly, exact and fast. The deck's own linear-regression example shows the pattern: the mean-squared-error loss over slope m and intercept c, its derivatives D_m and D_c, and the updates m ← m − L·D_m, c ← c − L·D_c, the same update rule wearing smaller clothes.
Making the gradient computable: computation graphs and backprop
Real classifiers are not a straight line from W to loss; they are arbitrary chains of operations. The general machinery is the computation graph, a directed acyclic graph of primitive operations. Forward pass: evaluate the graph node by node, storing intermediate results. Backward pass: evaluate the graph in reverse order, applying the chain rule, and reading the stored forward values. Paths not needed for the gradients of interest are eliminated. That four-step recipe is reverse accumulation, better known as backpropagation:

Caption:The training information flow in one diagram: the fixed dataset (x,y) and the moving weights feed the score function f, the loss combines the data loss with the regularization loss, and during gradient descent the gradient is computed on the weights and used for the parameter update. The forward pass computes scores and loss; the backward pass explains how to change them.CS231n
The insight that makes it tractable is locality. Every gate in the graph can compute two things on its own: its output value, and the local gradient of its output with respect to its inputs. The chain rule then says each gate takes the gradient flowing back from above and multiplies it into its local gradients. The information flows like a message: each gate learns how strongly its output should increase or decrease, and the message propagates backward layer by layer.
One historical note, because the deck's computation-graph slide is the modern restatement of a 1986 result. Rumelhart, Hinton and Williams published the two-pass learning rule, forward to compute unit states, backward to propagate errors, in a four-page Nature letter, and demonstrated it on a tiny network that learns to detect mirror symmetry:Backprop 1986

Caption:The 1986 guest star: a three-layer network with six input units, two hidden units and one output unit, drawn with the arc weights and unit states it settled into while learning to detect mirror symmetry in its 6-bit inputs. It is the same forward-backward machine, on a scale small enough to draw by hand. (The bias digits are not legible in the scan.)
One practical upgrade closes the machinery. Full-batch gradient descent is expensive when the dataset is large, since every update touches all N examples. Stochastic gradient descent (SGD) instead computes the gradient on a random minibatch of, say, a few hundred examples per update, and the minibatch gradient is an unbiased estimate of the full gradient, so the walk still heads downhill on average, just noisier and far cheaper.CS231n
Three behavior stories that check your mental model
The deck closes Part 6 with three worked scenarios that check whether the machinery above runs correctly in your head. Here they are as stories rather than questions.
Story one, the noise island. Consider a binary classification problem using 1-nearest-neighbor, with one mislabeled training sample added far away from everything else. In 1-NN every training point owns its Voronoi region, the patch of space closer to it than to any other stored point. Even the isolated mistake owns its own small island, and any query landing on that island receives the wrong label. The worst part is how local the damage is: one stray point changes predictions only in its own little territory, which is precisely why it is easy to miss and why the previous chapter's 5-NN vote exists, voting smears the island away.
Story two, the margin violators. A linear classifier has been trained until it hits 100% training accuracy, and the test accuracy still drops. Training with the SVM loss helps precisely because perfect accuracy says nothing about margin. The boundary could be squeezing right against the training points, so small input changes flip predictions. The SVM loss only reacts to margin violators, examples that are misclassified or correctly classified but too close to the boundary; examples classified correctly with a wide margin contribute exactly zero loss and zero gradient, and therefore zero update. Training with it actively pushes the boundary away from the data, and a boundary with room to spare on both sides generalizes better than one glued to the training points.
Story three, the rising confidence that changes nothing. A model trained with softmax loss shows the loss falling steadily while accuracy stays flat. Training is not broken. Softmax loss tracks the relative confidence of the correct class, so the model can keep increasing the correct class's probability and decreasing everyone else's; the loss keeps falling, and accuracy does not move at all, because accuracy only changes when the ranking of the scores changes. This is the flip side of the Chapter 5 observation: the softmax is never satisfied, it pushes even after it is right.
The whole chain, answered
Put all of it together and the answer to the title question is a pipeline, not a moment:
Caption:The full arc of the course in one column. Each stage consumes the output of the previous one: pixels to filter responses, to Canny lines, to scale- and rotation-invariant keypoints, to geometrically verified matches, to learned class scores, to a decision. Every stage exists because the naive version of the previous stage failed.
The computer never "sees" a cat. It reads a grid of integers, applies filters that respond to change, thins the responses into lines, finds anchors that survive the camera moving, verifies them geometrically, multiplies them by weights it learned by walking downhill, and concludes that this particular grid of numbers is best explained by the word "cat". That is the whole trick, and now you can say it in terms of gradients instead of magic.
References
The core sources cited in this tutorial are listed below. Read the originals for deeper study:
- CS231n: Deep Learning for Computer Vision — Lecture Notes (KNN, linear classification, SVM/Softmax, optimization, backprop) — https://cs231n.github.io/
- CS231n: Image Filtering — Convolutional Networks Lecture Notes — https://cs231n.github.io/convolutional-networks/
- Canny, J. (1986) "A Computational Approach to Edge Detection", IEEE Trans. PAMI 8(6):679–698 — https://doi.org/10.1109/TPAMI.1986.4767851
- Harris, C. & Stephens, M. (1988) "A Combined Corner and Edge Detector", Alvey Vision Conference, pp. 147–151 — https://web.stanford.edu/class/cs231m/references/harris-stephens.pdf
- Lowe, D.G. (2004) "Distinctive Image Features from Scale-Invariant Keypoints", IJCV 60(2):91–110 — https://robots.ox.ac.uk/~vgg/research/affine/det_eval_files/lowe_ijcv2004.pdf
- Fischler, M.A. & Bolles, R.C. (1981) "Random Sample Consensus: A Paradigm for Model Fitting", CACM 24(6):381–395 — https://www.sri.com/wp-content/uploads/2021/12/ransac-publication.pdf
- Cortes, C. & Vapnik, V. (1995) "Support-Vector Networks", Machine Learning 20(3):273–297 — https://homepages.math.uic.edu/~lreyzin/papers/cortes95.pdf
- Rumelhart, D.E., Hinton, G.E. & Williams, R.J. (1986) "Learning representations by back-propagating errors", Nature 323:533–536 — https://www.nature.com/articles/323533a0