Part II ยท Ch. 7 โ€” The Classical Toolbox

Part II ยท Chapter 7 of 13

The Classical Toolbox

kNN, decision trees, forests, boosting, SVMs, k-means, PCA


The tools that still win

Deep learning gets the headlines, but walk into most companies solving most real problems โ€” fraud on a spreadsheet, churn from a customer table, a diagnosis from lab values โ€” and you will find, quietly winning, methods that predate deep learning by decades. This chapter is the field guide to those workhorses, and the honest case for when to reach for one instead of a neural network.

The methods split into the two jobs you already met in learning from data. Supervised methods learn from labeled examples โ€” kNN, decision trees, forests, boosting, and support vector machines. Unsupervised methods find structure with no labels โ€” k-means and PCA. And here is the thesis this whole chapter defends: on tabular data โ€” rows and columns, like a spreadsheet โ€” a good tree ensemble is usually the first thing to try and often the last, because neural networks need the kind of shaped data (images, text) a spreadsheet does not have.

To keep a survey of seven tools from turning into a shopping list, each gets three things and only three: its geometry (the picture of what it does to the space of data), its one key idea (usually a single equation), and its when (where it beats the alternatives).

k-Nearest Neighbors: ask your neighbors

Start with the tool that barely deserves the word "algorithm." To classify a new point, find the $k$ labeled points closest to it and take a majority vote. That is the whole thing โ€” no training, no equation to fit; it just remembers every example and looks up the nearest ones when asked. Name it: k-nearest neighbors (kNN).

The geometry is nothing but distance. "Closest" means the straight-line distance between two points โ€” the length of the vector between them, as in the math toolkit:

$$d(\mathbf{x}, \mathbf{x}_i) = \lVert \mathbf{x} - \mathbf{x}_i \rVert = \sqrt{(x_1 - x_{i1})^2 + (x_2 - x_{i2})^2}$$

In words: subtract the two points coordinate by coordinate, square each difference, add them, and take the square root โ€” the ordinary ruler distance.

Worked example โ€” one vote

Our query sits at $\mathbf{x} = (4, 5)$ (the violet diamond in the figure). Measure its distance to the two nearest stored points fully:

$$d\big((4,5),\,(5,5)\big) = \sqrt{1^2 + 0^2} = 1.0 \;\;(\text{B}) \qquad d\big((4,5),\,(2,4)\big) = \sqrt{2^2 + 1^2} = \sqrt{5} \approx 2.24 \;\;(\text{A})$$

The third-closest is a class-B square at $(6,5)$, a distance $\sqrt{2^2+0^2}=2.0$ away.

In words: the nearest stored point is $1.0$ away and belongs to class B; the next is $2.0$ away, also B; the third is $2.24$ away and belongs to class A. So the $k = 3$ nearest are two B's and one A โ€” a show of hands of 2 to 1 โ€” and the query is called B. No model was fit; three distances settled it.

A square coordinate plane from 0 to 8 on both axes, equal aspect. Three mint filled circles (class A) sit lower-left at (2,4), (2,2), (1,1); three amber filled squares (class B) sit upper-right at (5,5), (6,5), (7,6). A larger violet diamond marks the query at (4,5), labeled 'new point?' in violet above it. A thin muted dashed circle centered on the query encloses exactly three points โ€” the amber squares at (5,5) and (6,5) and the mint circle at (2,4). Thin muted lines run from the query to each of those three, labeled with distances 1.0, 2.0 and 2.24. An annotation box upper-left reads 'k = 3 nearest: 2 B, 1 A โ†’ vote: B'.
k-nearest neighbors, deciding. To label the violet query, we find its three closest stored points (inside the dashed circle) and let them vote: two are class B, one is class A, so the query is called B. There is no model here โ€” just distances and a show of hands. Shrink $k$ to 1 and a single noisy neighbor could flip the answer.

The one knob that matters is $k$. Small $k$ (say $k = 1$) trusts the single nearest point, so the boundary turns jagged and chases every noisy outlier โ€” an overfitting echo of the last chapter. Large $k$ averages over many neighbors, smoothing the boundary but blurring genuine detail. It is the same underfit-versus-overfit dial from last chapter in new clothes โ€” the field's name for that trade-off is the bias-variance trade-off, which has nothing to do with a neuron's bias $b$ โ€” and you set it on a validation set.

When does kNN win? On tiny datasets, boundaries with weird local shape, and as a dead-simple baseline you can write in five minutes. Its two curses, stated honestly: it must store and search all the training data at prediction time (slow and heavy at scale), and it falls apart in very high dimensions, where "nearest" stops meaning much because everything becomes roughly equidistant. Hold that second curse โ€” PCA, at the end of the chapter, is one cure.

Decision trees: a game of twenty questions

The next tool plays twenty questions with the data. Ask a yes/no question about one feature โ€” "is income > 50k?" โ€” split the data into two groups, then ask another question of each group, and keep splitting until each group is nearly all one class. To predict, walk a new point down the questions to a leaf and read off that leaf's majority label. Name it: a decision tree.

The geometry is the payoff picture. Each question is a straight cut perpendicular to one axis: "income > 50k" is a vertical line, "age > 40" a horizontal one. So a tree chops the feature space into axis-aligned rectangular boxes, each carrying a single prediction. Unlike a neuron's single slanted line from the neuron, a tree can carve an intricate staircase of boxes.

Two panels side by side. Left panel titled 'the tree': a top-down binary tree of rounded boxes. The root asks 'x1 > 4 ?'; a branch labeled 'no' goes left to a box 'x2 > 3 ?', a branch labeled 'yes' goes right to a leaf 'B' tinted amber. The left box 'x2 > 3 ?' splits into a mint-tinted leaf 'A' (no) and an amber-tinted leaf 'B' (yes). Right panel titled 'the same model as boxes': a square coordinate plane with axes x1 and x2. A violet vertical line at x1 = 4 crosses the whole plane; a violet horizontal line at x2 = 3 runs only on the left side (x1 < 4). This makes three regions: lower-left tinted faint mint labeled A, upper-left tinted faint amber labeled B, and the whole right side tinted faint amber labeled B. A few mint circles and amber squares sit in their correct regions. An italic muted caption under both reads 'each question is one straight cut; the tree carves the plane into boxes'.
A decision tree, seen twice. Left: a sequence of yes/no questions about single features, ending in leaves that predict a class. Right: the very same model as geometry โ€” each question is one axis-aligned cut, chopping the plane into rectangular boxes, one prediction per box. You can read a tree's reasoning aloud, which is why it is the most interpretable tool in this chapter.

The one idea that makes a tree work is how it chooses each split: it picks the question that best purifies the two groups โ€” makes each side as close to single-class as possible. The common purity ruler is Gini impurity:

$$\text{impurity} = 1 - \sum_k p_k^2$$

In words: $p_k$ is the fraction of class $k$ in a group, and the sum runs over the classes rather than over examples โ€” same "add these up" sigma, new thing being counted. A group is pure (impurity 0) when one class fills it, and higher when it is more mixed. The tree greedily asks the question that makes its two child groups as pure as it can.

Why the squares? Because squaring rewards concentration: check it on two groups. A 50/50 group scores $1 - (0.5^2 + 0.5^2) = 1 - 0.5 = 0.5$, the most mixed two classes can be. A group that is all one class scores $1 - 1^2 = 0$, perfectly pure. Any lopsided group lands between them, so "smaller is purer" holds all the way down.

When does a tree win? It is the most interpretable model in the book โ€” you can print the questions and a human can follow the reasoning, which matters enormously in medicine, credit, and law โ€” and it handles mixed numeric-and-categorical features without fuss. But a single deep tree overfits ferociously: keep asking questions and every training point ends up alone in its own tiny box, which is memorization wearing a flowchart. The fix is not one tree but many โ€” the next two methods.

Forests and boosting: many trees beat one

One tree overfits, but a crowd of trees, combined well, does not. There are two ways to build the crowd, and the difference matters, because one of them is, on tabular data, the champion of the whole field.

The first is the random forest โ€” the parallel crowd. Grow hundreds of trees, each on a random subset of the data and a random subset of the features, so every tree overfits in its own direction. Then let them vote: the individual errors, being random and roughly independent, cancel out, and the shared signal survives. Name it: a random forest. It is an ensemble โ€” the same averaging that made dropout work in teaching the network, done with whole trees.

The second is boosting โ€” the sequential crowd, and the champion. Build the trees one after another, each new tree trained specifically to fix the mistakes the current crowd still makes. Tree one makes errors; tree two focuses on those; tree three on what is still wrong โ€” each a small correction added to the running total. Name it: gradient boosting. The honest fact, plainly: gradient-boosted trees โ€” the family behind XGBoost, LightGBM, and friends โ€” win a large share of real-world tabular competitions and production systems.

Two panels split by a vertical hairline. Left panel 'random forest โ€” vote in parallel': three small mint tree glyphs side by side, each tagged 'random data + features', each with a verdict chip below reading B, B and A. Arrows from all three converge down into a tally box 'majority vote โ†’ B'. A muted note reads 'errors cancel; independent trees'. Right panel 'boosting โ€” correct in sequence': three mint tree glyphs in a left-to-right chain connected by amber arrows; a small red label 'fix the errors so far' sits over each gap; labels under the trees read 'first guess', 'correct residual', 'correct what's left'; an arrow from the chain's end leads to a box 'sum of corrections โ†’ prediction'. A muted note reads 'each tree depends on the last'. A centered italic caption at the bottom reads 'forests average independent guesses ยท boosting adds tiny corrections โ€” both beat one tree'.
Two ways to turn many weak trees into one strong model. A random forest (left) grows hundreds of independent trees on random slices of the data and lets them vote, so their scattered errors cancel. Boosting (right) grows trees in sequence, each patching the mistakes the running total still makes. Boosting's corrective chain is why gradient-boosted trees win most tabular problems in the wild.

The one distinction to carry away: a forest averages many independent guesses, taming the wild variance of single trees; boosting adds up many tiny corrections, chipping away at systematic error. Both generalize far better than one tree, and both keep more interpretability than a neural network โ€” you can still ask which features the trees leaned on. When do they win? On tabular data, almost always, especially when you want strong accuracy without the data-hunger and tuning pain of a deep net.

Support vector machines: the widest street

When two classes can be separated by a straight boundary, there are infinitely many lines that do it โ€” so which is best? The support vector machine picks the one that leaves the widest empty street between the classes: the boundary with the most breathing room on both sides. Name it: a support vector machine (SVM).

The geometry, and its one idea, is the margin. Draw the boundary, then push two parallel lines out from it, one toward each class, until they touch the nearest points; the gap between those touching lines is the margin, and the SVM maximizes it. The handful of points that touch the edges are the only ones that matter โ€” the support vectors; move any other point and the boundary does not budge. For a boundary written $\mathbf{w} \cdot \mathbf{x} + b = 0$ โ€” where $\mathbf{w}$ is the weight vector, drawn violet in the figure because it is a learned parameter โ€” the street width is:

$$\text{margin} = \frac{2}{\lVert \mathbf{w} \rVert}$$

In words: the width of the street is two divided by the length of the weight vector, so maximizing the margin means making $\lVert \mathbf{w} \rVert$ small โ€” the fewer, gentler the weights, the wider the street.

A square coordinate plane from 0 to 8, equal aspect. Class A is mint filled circles clustered lower-left at (1,2), (2,1), (2,3), (3,2); class B is amber filled squares upper-right at (5,6), (6,5), (6,7), (7,6). A solid violet line runs diagonally through the middle at 45 degrees: the SVM boundary. Two muted dashed lines parallel to it sit equidistant on either side, each just touching the nearest points; the gap between them is shaded faint violet โ€” the street. The one or two points of each class touching the dashed lines are circled with a bold light ring and one is labeled 'support vector' with a small arrow. A double-headed arrow across the street perpendicular to the boundary is labeled 'margin (maximized)'. A muted note reads 'only the circled points set the boundary โ€” move any other point and nothing changes'.
The widest street. Of the infinitely many lines that separate these two classes, the SVM picks the one with the most empty room on both sides โ€” the maximum margin. Only the few points touching the margin's edges, the support vectors (ringed), determine the boundary; every other point is irrelevant. That economy is why SVMs shine in high dimensions.

And if the classes are not linearly separable โ€” a circle of one class inside a ring of the other? An SVM can secretly lift the points into a higher-dimensional space where they do separate by a plane, and the "kernel" computes distances in that space without ever building it. That is how a straight-line method draws curved boundaries โ€” a different route to the curvature the neuron got from stacking hidden layers.

When does an SVM win? On medium-sized datasets with a clear margin, especially in high dimensions where the "only the support vectors matter" economy shines; text classification was an SVM stronghold for years. Its limits: it does not scale gracefully to millions of points, and its predictions are less interpretable than a tree's.

k-means: finding groups no one labeled

Now switch jobs โ€” no labels at all (unsupervised). Given a cloud of points and no idea what the groups are, can we discover natural clusters? k-means says: guess there are $k$ clusters, and find them by a back-and-forth so simple you can run it by hand. Name it: k-means clustering.

The algorithm is Lloyd's two-step dance, and the widget below lets you drive it. Start: drop $k$ center points anywhere. Assign: color each data point by whichever center is nearest โ€” the same distance ruler as kNN. Update: move each center to the average position of the points now assigned to it. Repeat, and the centers slide into the hearts of the clusters and stop. What it is secretly minimizing is the total within-cluster squared distance:

$$L = \sum \lVert \mathbf{x} - \mathbf{c} \rVert^2$$

In words: add up, over every point $\mathbf{x}$ and its assigned center $\mathbf{c}$, the squared distance between them โ€” make every point as close as possible to its own cluster's center.

Worked example โ€” one turn of the dance

Six points in two blobs. Near the origin: $A(1,1)$, $B(1,2)$, $C(2,1)$. Far out: $D(5,5)$, $E(6,5)$, $F(5,6)$. Start the two centers at $\mathbf{c}_1 = (0,0)$ and $\mathbf{c}_2 = (5,0)$.

Assign. $A$, $B$, $C$ are all nearer $\mathbf{c}_1$; $D$, $E$, $F$ are all nearer $\mathbf{c}_2$. Check $D$: its distance to $\mathbf{c}_2$ is $\sqrt{0^2 + 5^2} = 5$, but to $\mathbf{c}_1$ it is $\sqrt{5^2 + 5^2} \approx 7.07$ โ€” so $D$ picks $\mathbf{c}_2$.

Update. Each center moves to the average of its points:

$$\mathbf{c}_1 \to \left(\tfrac{1+1+2}{3}, \tfrac{1+2+1}{3}\right) = (1.33,\, 1.33) \qquad \mathbf{c}_2 \to \left(\tfrac{5+6+5}{3}, \tfrac{5+5+6}{3}\right) = (5.33,\, 5.33)$$

In words: average the three points that chose each center โ€” their $x$'s and their $y$'s separately โ€” and the centers jump from $(0,0)$ and $(5,0)$ to $(1.33, 1.33)$ and $(5.33, 5.33)$. One dance and the centers have already found the two clusters.

The honest caveats, because k-means is easy to misuse. You must choose $k$ in advance โ€” the algorithm will not tell you how many groups exist. The result depends on where you drop the initial centers, so bad luck gives a bad grouping (which is why it is run several times and the best kept). And it only finds roughly round, similar-sized blobs; it fails on long stringy or nested clusters. When does it win? On quick exploratory grouping, customer segmentation, and compressing the colors in an image โ€” anywhere "find me some natural groups" is the whole ask.

PCA: squashing dimensions by shadow

The last tool, still unsupervised, answers a different need: data often has too many features (columns), most of them redundant or correlated. Can we describe it with fewer numbers without losing much? Name it: principal component analysis (PCA).

The geometry reuses the dot-product-as-shadow idea from the math toolkit โ€” this is its big payoff. Picture a cloud of 2D points stretched into a long thin ellipse. Most of the spread runs along the ellipse's long axis; the short axis barely varies. PCA finds that long axis โ€” the principal component โ€” and describes each point by its shadow, its dot-product projection, onto that axis. Throw away the short-axis coordinate and you have turned 2D into 1D, losing almost nothing, because the short axis held almost no information.

A square plane roughly from -4 to 4 on both axes, equal aspect. About forty blue data points form a long thin ellipse tilted at 45 degrees. A mint arrow runs through the cloud's center along its long axis, labeled 'principal component (most spread)'. A shorter amber arrow perpendicular to it is labeled 'second (little spread)'. One data point out along the cloud is drawn larger in white; a thin muted dashed line drops from it perpendicular onto the mint axis, meeting it at a violet dot labeled 'x ยท u โ€” its shadow'. A muted note reads 'keep the long-axis shadow, drop the short axis โ†’ 2D becomes 1D, almost nothing lost'.
PCA squashes dimensions with shadows. The data cloud spreads far along one direction (the mint principal component) and barely along the perpendicular one (amber). Describe each point by its shadow โ€” its dot-product projection โ€” onto the long axis, throw away the short-axis coordinate, and two dimensions collapse to one while keeping nearly all the information. The dot product from the math toolkit, doing real work.

The one idea, without heavy machinery: PCA seeks the direction of maximum variance โ€” the most spread-out direction โ€” then the most-spread direction perpendicular to that, and so on, ranked axes of the data's own shape. Keep the top few, drop the rest. The coordinate of a point along a component is exactly the dot product you already own:

$$\text{coordinate of } \mathbf{x} \text{ along component } \mathbf{u} = \mathbf{x} \cdot \mathbf{u}$$

In words: a point's position along a component is just its shadow on that direction โ€” the dot product from the math toolkit, doing dimension-reduction.

One clause of honesty about where the axes come from: the components are computed from the data's covariance, and that machinery (eigenvectors of the covariance matrix) is beyond us here โ€” but the picture, long axis and short axis, is exact. When does PCA win? On squashing hundreds of correlated features down to a handful before feeding another model (curing kNN's high-dimension curse), on visualizing high-dimensional data in 2D, and on compression. Its honest limit: it only finds straight axes of variation, so genuinely curved structure escapes it โ€” for which nonlinear cousins like t-SNE and UMAP exist, mostly for visualization.

Where you'll meet this

Pull the whole survey into a single decision. Do you have labels? No โ€” reach for k-means or PCA to explore. Yes โ€” then is the data a spreadsheet of rows and columns? Then start with gradient-boosted trees; they will likely win, train in minutes, and tell you which features mattered. Is the data an image, a sentence, or a graph โ€” data with shape? Then, and mostly only then, reach for the deep networks the next part builds.

State the engineering truth this chapter defends, once and cleanly: a neural network is not the best tool โ€” it is the best tool for data with structure a network can exploit. On a mid-sized tabular dataset, a boosted-tree ensemble usually beats a neural net on accuracy, training time, and interpretability, which is why it remains the professional's default there. Choosing deep learning where a tree would win is one of the most common and expensive mistakes in the field.

Here is precisely why images and text change that answer. Their structure โ€” a pixel's neighbors, a word's order, a node's links โ€” carries the signal, and a plain network (or a classical method) throws that structure away by treating every feature as unrelated. The next chapters wire networks that preserve and exploit shape: convolution for grids, recurrence and attention for sequences, message-passing for graphs. That is where deep learning earns its headline. You now hold a genuine toolbox โ€” and, more valuable than any one tool, the judgement to choose; the capstone chapter, choosing your tool, turns that judgement into a full field guide.

What you now know

  • k-nearest neighbors learns nothing โ€” it stores every example and labels a new point by a majority vote of its $k$ closest stored points (Euclidean distance); simple and strong on small data, but slow at scale and lost in high dimensions.
  • A decision tree asks a sequence of yes/no questions about single features, carving the space into axis-aligned boxes; it is the most interpretable model here, but a single deep tree overfits badly.
  • Ensembles fix that: a random forest averages hundreds of independent trees so their errors cancel, while gradient boosting adds trees in sequence, each correcting the last โ€” and boosted trees are the usual champion on tabular data.
  • A support vector machine picks the separating line with the widest margin, determined only by the few support vectors that touch the street's edges; the kernel trick lets it draw curved boundaries by lifting points into higher dimensions.
  • k-means finds unlabeled clusters by alternating assign-to-nearest-center and move-center-to-average (minimizing within-cluster distance) โ€” but you must choose $k$, and the result depends on the starting centers.
  • PCA reduces dimensions by finding the axes of maximum variance and describing each point by its shadow (dot-product projection) onto the top few โ€” curing high-dimension curses and enabling visualization, as long as the structure is roughly straight.

Where we're headed. You now hold a real toolbox and, more importantly, the judgement to choose from it: no labels means k-means or PCA; a spreadsheet of rows and columns means start with boosted trees and expect to win; and only data with genuine shape โ€” a grid of pixels, a stream of words, a web of contacts โ€” sends you to a neural network. That last clause is the door into Part III. The reason images and language change the answer is that their structure carries the meaning: a pixel is defined by its neighbors, a word by its order, a node by its links โ€” and every method in this chapter, like a plain stack of neurons, throws that structure away by treating each feature as unrelated to the rest. Next, we stop throwing it away. We wire the network to match the shape of the data, starting with the most visual case of all: how a machine learns to see.