AI from scratch · Clusters and anomalies · Stage 3: classic ML and judging models
Clusters and anomalies
Every model so far learned from labeled answers. Often there are none: a pile of customers, sensor readings or outages, and the questions "what kinds are there?" and "which of these is strange?". The tool behind both is the humblest idea in ML: things that are close together are probably alike. This lesson builds on distance: neighbors that vote, clusters that find themselves, soft clusters, and the odd ones out, on a map of 396 real commuter rail stations and this site's archive of subway elevator outages.
Stations: © OpenStreetMap contributors (ODbL). Positions are in kilometers from Manhattan, so distances mean something.
1. Neighbors vote
Each dot is a station of Metro-North (green), the Long Island Rail Road (blue) or NJ Transit (orange). k-nearest neighbors (kNN) has no training at all: to label a new point, find the k closest known points and let them vote. Tap the map anywhere to see the vote; the shading is what kNN would answer at every spot.
Raise k and the borders between colors smooth out; k = 1 copies whichever station is nearest, noise included. That's chapter 11 again: small k overfits, large k underfits, and k is chosen on validation data. kNN gets 99% of these stations right (with cross-validation). Its few mistakes are exactly where the railroads meet: the big terminals by the Hudson (Grand Central, Hoboken), where lines from every direction arrive, and an NJ Transit station or two in New York's Orange County that sit nearer to Metro-North stations than to their own line's.
The map makes kNN look easy because two coordinates in kilometers are a perfect distance. On a real table, distance needs care: every column must be scaled (features and leakage, section 3), or the column with the biggest numbers decides alone, and with dozens of columns "near" means less and less. Still, kNN is the first baseline to try, and its idea runs modern AI: search engines and chatbots find relevant documents as the nearest neighbors of your question's embedding (stage 6).
Measured on its own training rows, what accuracy does 1-nearest-neighbor get?
- About the base rate
- 100% (unless two identical rows disagree): each row's nearest neighbor is itself
- About 99%, the same as cross-validation
kNN learns no rule: it asks the nearest labeled points and lets them vote, so what "near" means decides everything.
2. k-means: clusters that find themselves
Now forget the colors: no labels at all. k-means looks for k groups with a two-step loop. Start with k centers (random stations). Assign: each point joins its nearest center. Move: each center moves to the average of its points. Repeat until nothing changes. Each step can only lower the total squared distance from points to their centers, the inertia:
\[ \text{inertia} = \sum_i \lVert x_i - \mu_{c(i)} \rVert^2 \qquad \mu_j = \text{the mean of the points in cluster } j \]
Pick k-means above the map, then press Step and watch the two moves alternate. Press New start a few times: different starting centers can end in different clusterings, some worse, which is why libraries run several starts (n_init) and keep the lowest inertia.
k-means clusters customers by yearly spending (dollars, up to 100,000) and age (years, up to 90). What will the clusters mostly reflect?
- Age and spending equally
- Mostly age
- Mostly spending: its distances are thousands of times bigger, so age barely counts unless both are scaled
k-means alternates two moves, join the nearest center and move each center to its points' mean, and each move can only tighten the clusters.
Why k-means always stops (but not always at the best answer)
- Inertia adds up every point's squared distance to its own center, so it's never negative.
- The assign move: each point switches to its nearest center, so its term can only shrink or stay.
- The move move: for a fixed group of points, the center with the smallest sum of squared distances is their mean (probability 2: the mean is the best guess under a squared penalty, one coordinate at a time). So moving each center to its mean can only shrink the sum.
- Every step lowers the inertia or leaves it alone, and there are only finitely many ways to split the points into k groups, so it can't keep falling forever: the loop stops.
- It stops at a split that no single move improves, not necessarily the best split. That's why New start can end somewhere else, and why libraries keep the best of several starts.
3. How many clusters? Be honest
Inertia always falls as k grows (with one cluster per point it's 0), so it can't choose k on its own. Two common aids: the elbow, where adding clusters stops helping much, and the silhouette, which for each point compares how close it sits to its own cluster versus the next one (from −1 to 1, higher is cleaner). And a reality check: does a clustering match anything you care about? Here we have the railroads to compare with, a luxury real problems rarely give you.
No sharp elbow, a silhouette that creeps up slowly, and even at k = 3 the clusters barely match the three railroads (ARI 1 would be perfect, 0 chance). k-means isn't failing: it found groups of nearby stations, which is all the features describe. Railroads are a fact about ownership, not geography. Clusters reflect the features you give them, not the labels you wish for. Often there is no "true" k; choose the one that's useful (a sales team can handle 5 customer segments, not 40).
Clusters describe the features you gave them; a "right k" exists only if the data has one.
4. Soft clusters: Gaussian mixtures
k-means gives every point one cluster and assumes round clusters of similar size. A Gaussian mixture (GMM) models the data as several bell-shaped blobs (probability 2's multivariate bell), each with its own center, shape and tilt, and gives every point a probability of belonging to each. It's fitted by EM, which is k-means with probabilities: compute each point's membership probabilities (E step), then refit each blob to its weighted points (M step), and repeat. Choosing the number of blobs can use BIC: the fit's log-likelihood minus a penalty for every parameter, so extra blobs must earn their keep.
The least certain stations sit between blobs, split nearly evenly. And BIC keeps falling as blobs are added: stations lie along rail lines, not in round clouds, so a mixture of bells needs many of them to trace the lines. That's a useful verdict too: the model's shape doesn't suit this data, which is why there are many clustering methods (scikit-learn's DBSCAN follows dense chains of points, for one).
A Gaussian mixture is k-means with probabilities and shapes: every point belongs a little to every blob.
5. Anomalies: what doesn't fit
Once you have a picture of "normal", the odd ones are the points it explains badly: far from their neighbors (the distance to the k-th nearest neighbor), unlikely under a mixture (a low GMM density), or easy to isolate. That last one is an isolation forest: random trees that cut the data at random places, where an unusual point ends up alone after only a few cuts while normal points sit in crowds.
This site keeps an archive of NYC subway elevator and escalator outages. Each one has how long it lasted and the MTA's estimate. On a log scale (probability 2: durations are skewed), most outages form one cloud. The estimate is longer than the real outage in 98.5% of them, so the MTA plans for the worst. Which outages don't fit?
The two most unusual are planned maintenance that took a whole month (711 and 712 hours): rare, but right. Next, an elevator "outage" of 0.04 hours, two and a half minutes, which smells like a glitch in the feed, and an escalator repair estimated at 73 hours that took 3. An anomaly detector finds the unusual; a person decides whether it's an error, a fraud, an emergency or simply rare. In practice the threshold is set by how many cases someone can look at each day, and the detector is judged by how many of those turn out to matter (precision among the top flagged, chapter 12).
You flag the 1% least likely transactions under a GMM fitted on last year's data. After a holiday sale, flags jump to 8%. What's the first thing to check?
- Whether normal behavior changed (the sale), so the model of "normal" is out of date
- That fraud rose eightfold
- That the GMM broke
An anomaly is a point the picture of normal explains badly; a person decides what it means.
Where it breaks: when "close" stops meaning "alike"
- Many columns. Take 1,000 random points in a cube and one more point: in 2 dimensions its nearest neighbor is 0.7% as far as its farthest; in 100 dimensions, 72%; in 1,000, 90%. When everything is about equally far, the nearest neighbors are barely nearer. Use fewer, better columns (PCA, from linear algebra 2), or embeddings trained so that distance means something (stages 5 and 6).
- Shapes that aren't round blobs. k-means cuts space into straight-edged regions around centers. On two interlocking half-moons its two clusters match the moons with ARI 0.26; on a ring around a disk, ARI 0.00, pure chance. DBSCAN and spectral clustering follow such shapes.
- Anomalies in a crowd. A fraud ring making 50 similar payments forms its own little cluster: each one has close neighbors, so distance to the nearest neighbor calls them normal. A larger k, or a picture of normal fitted on older, clean data, catches them.
6. What to carry forward
| Method | What it does | Watch out for |
|---|---|---|
| k-nearest neighbors | Labels a point by its k nearest labeled points; no training | Scaling; small k overfits; slow and weak with many columns |
| k-means | k round groups: assign to the nearest center, move centers to the mean, repeat | Scaling, several starts, choosing k (there may be no true k) |
| Gaussian mixture | Soft clusters with shapes; a density, fitted by EM | Starts and number of blobs (BIC) |
| Anomaly scores | Distance to neighbors, low density, isolation forest | "Unusual" isn't "wrong"; normal drifts; set the threshold by review capacity |
- Distance is the shared idea: scale features, or the biggest numbers decide.
- Clusters describe the features you gave them; judge them by usefulness, not by a magic k.
- Anomaly detection ranks; people (or labels you collect later) decide what the top ranks mean.
All lessons: AI from scratch. scikit-learn's user guide on clustering compares many more methods on the same toy shapes.
Last updated