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?

kNN stores the training set, so training accuracy says nothing. Only held-out rows are a fair test, as always.

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?

k-means is all distances, so it inherits every scaling problem kNN has. Standardize first.

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)
  1. Inertia adds up every point's squared distance to its own center, so it's never negative.
  2. The assign move: each point switches to its nearest center, so its term can only shrink or stay.
  3. 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.
  4. 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.
  5. 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?

"Unusual" is relative to the data the detector learned from. When the world shifts (features and leakage, section 6), normal looks strange: refit on recent data, or model the season.

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"

6. What to carry forward

MethodWhat it doesWatch out for
k-nearest neighborsLabels a point by its k nearest labeled points; no trainingScaling; small k overfits; slow and weak with many columns
k-meansk round groups: assign to the nearest center, move centers to the mean, repeatScaling, several starts, choosing k (there may be no true k)
Gaussian mixtureSoft clusters with shapes; a density, fitted by EMStarts and number of blobs (BIC)
Anomaly scoresDistance to neighbors, low density, isolation forest"Unusual" isn't "wrong"; normal drifts; set the threshold by review capacity

All lessons: AI from scratch. scikit-learn's user guide on clustering compares many more methods on the same toy shapes.

Last updated