EVERYTHING AIAI engineering, made visual
0/18 complete
LESSON 07 · MACHINE LEARNING × AI · BUILD

No labels.
Just structure.

inertia = Σ ‖xᵢ − μ_c(i)‖² is a clustering algorithm’s report card. K-means lowers it with two moves: every point claims its nearest centroid, then every centroid moves to the mean of its claimants.

90 MIN · 8 CHAPTERSPREREQ · PHASE 1 · DISTANCES
FIG. 07 / ASSIGN → MOVE → SETTLE
INERTIA = · CLUSTER SIZES = cluster 1 cluster 2 centroid
LESSON 07TYPE · BUILD~90 MINPREREQ · PHASE 1 · LESSONS 06, 14, 15; PHASE 2 · LESSONS 01–06ORIGINAL LESSON ↗
THE 60-SECOND VERSIONThen show me the shape ↓
01 / SIMILARITY IS THE ONLY TEACHER

With no labels, “similar” is a choice.

Clustering partitions points so that within-group similarity beats between-group similarity — and similarity is a distance metric you pick. Euclidean distance over standardized features, cosine over embeddings: the same rows, a different map. There is no accuracy to print, only internal evidence.

similar = small distance
02 / TWO MOVES, REPEATED

Assign, then move — until nothing changes.

K-means needs one number, k. Assign every point to its nearest centroid; move every centroid to the mean of its points. Inertia — the total squared distance to the assigned centroid — falls on both moves, so the loop always ends. A different start can end somewhere else.

inertia = Σ ‖xᵢ − μ‖²
03 / EVALUATE WITHOUT ANSWERS

Elbow for k, silhouette for separation.

Inertia always falls as k grows, so compare the shape of the fall: the elbow where extra clusters stop paying. The silhouette scores each point, (b − a)/max(a, b), against its nearest rival cluster. Above zero the grouping is defensible; below zero the point is in the wrong group.

elbow + silhouette, never raw inertia
MENTAL MODEL IN ONE SENTENCE

Clustering never tells you the right answer — it tells you the structure implied by one definition of similar (a distance), one number of groups (k, eps, or a cut height), and one dataset; change any of the three and the clusters change with it.

By the end you will be able to run k-means by hand and by stepper, choose k from an elbow and a silhouette, explain why moons and rings break k-means, read a dendrogram, classify points as core, border or noise in DBSCAN, and pick a sensible first method for an unlabeled table.

NO LABELS, JUST SHAPE

Structure is what is left
when the answers are gone.

Every lesson so far had an answer key. Unsupervised learning does not: it groups similar data, compresses it, or flags what refuses to fit — without ever being told what is right.

Labels are expensive. A hospital has millions of patient records and nobody has hand-tagged each one with a condition; an e-commerce site has millions of sessions and no one has written down which ones belong to the same kind of shopper; a security team has network logs and no complete list of past intrusions. Unsupervised learning is what you do when the data is plentiful and the answers are not.

Clustering assigns each point to a group so that points in the same group are more similar to each other than to points in other groups. The loaded word is similar. It is not a fact about the data — it is a distance metric you choose. Euclidean distance over standardized features, cosine similarity over embedding vectors, edit distance over strings: each one redraws the groups. Everything else in this lesson is machinery for optimizing or judging a choice that starts right there.

SUPERVISED · LABELS GIVENUNSUPERVISED · STRUCTURE FOUND+++no labels — two groups are a choice
The same six coordinates, two different questions. Supervised learning asks “which side?” and needs the +/− tags. Unsupervised learning asks “who belongs together?” and has to answer with geometry alone — which is why the grouping on the right is one defensible answer, not the answer.

The catch the source states plainly: without labels you cannot measure “right” or “wrong”. There is no accuracy to print. Instead you get internal evidence — how tight the clusters are, how separated they are, whether the result survives a change of initialization — and you stay honest about what that evidence can and cannot prove.

Quick check

You have 10,000 customer sessions and no labels. What does a clustering algorithm need before it can group them?

TWO MOVES, REPEATED

Guess the centers.
Let the points correct you.

K-Means is the workhorse: give it a number of clusters k and it alternates two moves until nothing changes. No gradients, no labels — just means and distances.

The algorithm starts with k centroids — one guess per cluster. Then it repeats two moves:

  1. Assign. Every point joins the cluster of its nearest centroid.
  2. Move. Every centroid jumps to the mean of the points that just joined it.

The loop stops — provably, in a finite number of steps — when the assignments stop changing. Both moves only ever decrease the same objective, the total spread of the clusters:

inertia = Σᵢ ‖ xᵢ − μ_{c(i)} ‖² plain English: add up the squared distance from every point to the centroid it was assigned to. Tight clusters, small number; loose clusters, big number. K-Means is the algorithm that minimizes it. note: it minimizes the squared distance, not the Euclidean distance — squaring keeps the arithmetic differentiable and punishes far points.

Assigning a point to its nearest centroid can only lower its distance to its centroid; moving a centroid to the mean of its members can only lower the total squared distance of those members. So inertia slides downhill on both moves — which also guarantees it cannot cycle forever. What it does not guarantee is the global minimum: different starting centroids can settle in different valleys.

Worked check: one full iteration on six points
Points: A(1,1) B(2,1) C(1,2) D(8,8) E(9,8) F(8,9) Start: μ1 = (1,1) μ2 = (8,8) (two of the points, chosen by hand) ASSIGN — squared distance to each centroid to μ1 to μ2 winner A (1,1) 0 98 μ1 B (2,1) 1 85 μ1 C (1,2) 1 85 μ1 D (8,8) 98 0 μ2 E (9,8) 113 1 μ2 F (8,9) 113 1 μ2 inertia = 0 + 1 + 1 + 0 + 1 + 1 = 4 MOVE — each centroid to the mean of its three points μ1 = ((1+2+1)/3, (1+1+2)/3) = (4/3, 4/3) ≈ (1.333, 1.333) μ2 = ((8+9+8)/3, (8+8+9)/3) = (25/3, 25/3) ≈ (8.333, 8.333) RE-ASSIGN — A is now 2/9 from μ1; D is 2/9 from μ2 inertia = 2/9 + 5/9 + 5/9 + 2/9 + 5/9 + 5/9 = 24/9 ≈ 2.667 no point changed → converged after one full round

Two things to notice. First, the move nearly halved the inertia before any re-assignment happened — the “tightening” is real arithmetic, not vibes. Second, the six points split into the two obvious triples even though the starting centroids were data points, not cluster means. K-Means does not need a clever start here because the blobs are far apart; make them overlap and the start matters (see the trap below).

The stepper: assign, then move

Six points, two centroids — the same data as the hand-worked iteration above. Click the plot to move the nearest centroid, then step.

rounds 0 inertia — assign first cluster sizes 0 / 0 μ1 (1.00, 1.00) μ2 (8.00, 8.00) unassigned: step 1 is assign

The inertia never needs to say “converged” on its own — it decreases at assign, decreases again at move, and the first time the colors stop changing you are done.

Quick check

After the assign step, every point has a cluster. What does the update step do?

HOW MANY CLUSTERS?

Inertia can’t pick k.
The shape of the fall can.

K-Means answers “what are the best k clusters?” but never “how many should there be?”. Two honest tools for that question: where inertia bends, and how separated the groups are.

Inertia is not a score you can optimize, because it always falls as k grows. With one centroid per point it reaches exactly 0 — a perfect “score” and a useless clustering. The signal is not the height but the shape of the curve: the elbow method plots inertia against k and looks for the point where each extra cluster stops paying for itself. Before the elbow, splitting a merged group removes a lot of spread; after it, the algorithm is just carving up real clusters.

The silhouette score attacks the same question from the other side — not “how tight?” but “how much better is this point’s own cluster than the next best one?” For a single point:

s = (b − a) / max(a, b) a = mean distance from the point to the OTHER members of its own cluster b = mean distance from the point to the members of the NEAREST other cluster plain English: how far the point has to travel to its neighbours of the same color, compared to its neighbours of the other color. s = +1 → huddled with its own group and far from every other group s = 0 → right on the border between two groups s = −1 → closer to another group than to its own — it is in the wrong cluster

Average s over all points and you have one number for a whole clustering, comparable across values of k. (Points in single-member clusters are conventionally scored 0, since there is no “own” group to compare against.)

The elbow and the silhouette, live

Three blobs, k = 1 through 6. Move k: the scatter recolors, and the two curves on the right come from the same nearest-centroid math.

k=1 inertia 361.58 silhouette n/a k=2 inertia 224.19 silhouette 0.3789 k=3 ← inertia 18.08 silhouette 0.8043 k=4 inertia 15.70 silhouette 0.6202 k=5 inertia 13.32 silhouette 0.4411 k=6 inertia 11.14 silhouette 0.2551 the elbow: 3 → 4 shaves only 2.38 off inertia, and the silhouette falls from 0.804 to 0.620 — the extra centroid splits a real blob.

Inertia always falls as k grows — with one centroid per point it reaches 0. That is why the choice is made by the size of the drop (elbow) or by a separation score (silhouette), never by raw inertia.

Worked check: two ways to split the same eight points
The eight points: (1,1) (2,1) (1,2) (2,2) and (8,1) (9,1) (8,2) (9,2) Candidate A — {left four} and {right four} For P1 (1,1): a = mean(1, 1, 1.414) = 1.138 (three neighbours in its group) b = mean(7, 8, 7.071, 8.062) = 7.533 (the four points of the other group) s = (7.533 − 1.138) / 7.533 = +0.849 mean s over all eight points = 0.8374 Candidate B — {bottom row} and {top row} For the same P1 (1,1): a = mean(1, 7, 8) = 5.333 b = mean(1, 1.414, 7.071, 8.062) = 4.387 s = (4.387 − 5.333) / 5.333 = −0.177 mean s over all eight points = −0.1717 The formula never saw a picture. It only saw pair distances and group labels — and it preferred A by more than a full unit.

The console above prints every row of this table for whichever candidate you pick; P1 is the first line. On real data you rarely get such a clean answer, but the direction is always the same: compare the mean s of several candidate clusterings and distrust the negative points first.

Quick check

A point's silhouette is −0.4. What does that mean?

WHERE K-MEANS BREAKS

Every algorithm is a set
of assumptions in disguise.

K-Means is fast, simple and deterministic once started — and wrong the moment its geometry does not match your data. Recognizing the four assumptions tells you when to reach for a different method.

1 · Clusters are convex and roughly equal in size. Nearest-centroid boundaries are straight lines (in higher dimensions, flat planes). That partition carves space into convex cells, so it cannot wrap a crescent, a ring, or any shape with a bend. When one true cluster is twice as large as another, the small one often gets split in two because both centroids find room inside it.

2 · Every point belongs to exactly one cluster. Assignments are hard: a point on the boundary is flung to one side or the other, even when it genuinely sits between two groups. There is no “60% A, 40% B” in k-means.

3 · Distance is meaningful at the scale you measured. Change a column from metres to millimetres and the clusters change. Feature scaling is not optional here — it is part of the model.

4 · No point deserves to be ignored. Because the center is a mean, a single far-away point drags it:

100four points: 1, 2, 3, 4μ = 22true centre 2.5
One outlier is enough. The mean of 1, 2, 3, 4, 100 is 22 — the centroid abandons the cluster and splits the difference with the outlier (22 − 2.5 = 19.5 units away). The median, 3, never moves. Mean = squared-error thinking; that is the price of the tidy inertia formula.

And one assumption that is not about geometry at all: k must be chosen before the algorithm runs. The next two methods drop that requirement in two different ways.

Same points, two definitions of a cluster

Pick a shape and a method. K-means can only ask “which centroid is nearest?”; DBSCAN asks “who is crowded around whom?”

two moons · 64 points k-means k=2 inertia 26.64 silhouette 0.4650 the nearest-centroid split is a straight-ish boundary that cuts both crescents in half DBSCAN eps=0.35 minPts=4 clusters 2 noise 1 each crescent is one connected dense ribbon, so density walks the whole shape showing k-means: every point must pick one centroid.

Neither answer is wrong on its own terms — they are answers to different questions. Match the method to the shape you expect, or just to the shape you can see.

A TREE OF CLUSTERS

Merge the closest pair.
Repeat until everything is one.

Hierarchical clustering does not commit to k upfront. It builds a tree of every possible merge, and choosing k becomes choosing where to cut the tree.

Agglomerative (bottom-up) clustering starts with every point as its own cluster and repeatedly merges the two closest clusters. The result is a dendrogram: a tree whose branches merge at a height equal to the distance between the two clusters at that moment. Cut the tree with a horizontal line and its intersections are your clusters; slide the line down and clusters split, slide it up and they merge. One run gives you every k at once.

The one design decision is what “closest clusters” means. The source lists four standard answers:

  • Single linkage — the minimum distance between any point of one cluster and any point of the other. It chains through the nearest neighbours and can connect a long string of points into one sprawling cluster.
  • Complete linkage — the maximum distance. It keeps clusters compact at the price of never merging two long shapes.
  • Average linkage — the mean over all cross pairs: a compromise between the two extremes.
  • Ward’s method — merge the pair that causes the smallest increase in total within-cluster variance. It is the closest thing in this family to k-means’ objective, and it usually produces the most even-sized clusters.

The cost is the trade-off. Comparing every pair at every merge is O(n²) time and memory, so this is a small-data tool: a few thousand points at most. In exchange you get a complete picture of structure — which is why it is the standard method in phylogenetics, document taxonomies, and any setting where the hierarchy itself is the answer.

Worked check: four points, two linkages, one tree shape
Points on a line: x = 1, 2, 4, 8 SINGLE LINKAGE — merge by minimum pairwise distance merge {1} {2} at 1.0 merge {1,2} {4} at 2.0 (closest cross pair is 2 ↔ 4) merge {1,2,4} {8} at 4.0 (closest cross pair is 4 ↔ 8) heights: 1.0 → 2.0 → 4.0 WARD'S METHOD — Δ = (n₁n₂ / (n₁+n₂)) · ‖c₁ − c₂‖² merge {1} {2} Δ = (1·1/2)(1−2)² = 0.5000 merge {1,2} {4} Δ = (2·1/3)(4−1.5)² = 4.1667 merge {1,2,4} {8} Δ = (3·1/4)(8−2.3333)² = 24.0833 heights: 0.50 → 4.17 → 24.08 cut at height 5 → {1, 2, 4} and {8} cut at height 30 → one cluster {1, 2, 4, 8} K-Means with k=2 on the same points (farthest-first start) also returns {1,2,4} and {8}: the gap between 4 and 8 is where the tree says to cut.

Both linkages produce the same merge order here, but the heights tell different stories. Single linkage calls the last merge 4 — the distance between the two closest survivors. Ward calls it 24.08, because welding two compact groups into one bag costs an enormous amount of variance. That is how a dendrogram encodes not justwhat merged but how much it hurt.

Build the family tree, then cut it

Six points on a line. Merge the closest pair again and again — then slide the cut to choose how many clusters survive.

0.01.02.03.04.0cut 2.20P1x=1P2x=2P3x=4.5P4x=5P5x=9P6x=10
linkage single — nearest pair merge order @0.50 → @1.00 → @1.00 → @2.50 → @4.00 cut 2.20 of 4.00 max clusters [P1 P2] [P3 P4] [P5 P6] P3 P4 merged at 0.500 P1 P2 merged at 1.000 P5 P6 merged at 1.000 P3 P4 P1 P2 merged at 2.500 P5 P6 P3 P4 P1 P2 merged at 4.000

Changing the linkage changes the heights, not the points. Ward merges compact groups first and makes the big gaps look huge; single linkage chains through the nearest neighbour and makes the tree look deceptively shallow.

DENSITY DRAWS THE LINE

A cluster is a crowd,
and a crowd can bend.

DBSCAN asks a different question: not “which centroid is nearest?” but “is there a dense enough path from here to there?” The answer can be any shape, and some points get no cluster at all.

DBSCAN has exactly two dials. eps is the radius of a point’s neighborhood. minPts is how many neighbors (counting the point itself, as scikit-learn does) make that neighborhood crowded. Those two numbers sort every point into one of three kinds:

  • Core — at least minPts points sit within eps. These are the seeds.
  • Border — not crowded enough to be core, but within eps of a core point. It joins that core’s cluster.
  • Noise — neither. No cluster claims it; it is an outlier by construction.

Then clusters grow by connectivity: start from any unvisited core, absorb every core within eps, absorb their borders, and repeat until the crowd runs out. Because the cluster is a connected chain of dense neighborhoods, it can curve, spiral or ring — shapes that no straight boundary can capture. And because you never told it how many clusters to find, it reports however many the density supports, which may be zero.

The weakness is the flip side of the two dials: a single eps has to serve every cluster, so DBSCAN struggles when one cluster is dense and another is sparse — the same eps is too small for one and too large for the other. Very high dimensions hurt too, for the same reason distance-based methods do: distances concentrate and “near” stops meaning much.

core point ⇔ |neighborhood(x, eps)| ≥ minPts border ⇔ not core, but within eps of a core point noise ⇔ neither — label −1 plain English: eps says how far a neighbor can be; minPts says how many neighbors make a place busy. Busy places seed clusters; anyone standing near a busy place gets pulled in; everyone else is noise. connecting rule: core points within eps of each other share a cluster.

Density dials: eps and minPts

Ten points with one straggler and one far outlier. Turn the two dials and watch core, border and noise change labels.

clusters 2 core 8 border 1 noise 1 P1 (1.0,1.0) core n=4 c0 P2 (2.0,1.0) core n=5 c0 P3 (1.5,2.0) core n=4 c0 P4 (2.0,2.0) core n=4 c0 P5 (3.2,1.0) border n=2 c0 P6 (5.0,5.0) noise n=1 — P7 (8.0,8.0) core n=4 c1 P8 (9.0,8.0) core n=4 c1 P9 (8.5,9.0) core n=4 c1 P10 (9.0,9.0) core n=4 c1 core points seed clusters; border points join a nearby core; noise stays alone.

DBSCAN never asks for k. It finds as many clusters as the density supports — and it is allowed to call a point noise.

Worked check: ten points, eps = 1.5, minPts = 3
Left blob P1(1,1) P2(2,1) P3(1.5,2) P4(2,2) Straggler P5(3.2,1) Outlier P6(5,5) Right blob P7(8,8) P8(9,8) P9(8.5,9) P10(9,9) P1's neighborhood within 1.5: P1, P2 (d=1), P3 (d=1.118), P4 (d=1.414) → 4 ≥ 3 → CORE P2's neighborhood: P2, P1, P3, P4, P5 (d=1.2) → 5 → CORE P5's neighborhood: P5, P2 → 2 → not core but P2 is core and within 1.5 → BORDER of cluster 0 P6's neighborhood: P6 alone → 1 → NOISE (−1) P7–P10 mirror P1–P4 → all CORE connectivity: P1–P2–P3–P4 are mutually reachable through core points → cluster 0; P7–P8–P9–P10 → cluster 1 result: 2 clusters · 8 core · 1 border · 1 noise

Now leave the points alone and turn one dial:

eps = 1.0, minPts = 3 P2 and P4 have exactly 3 neighbors each (self + 2) → they stay core P1 and P3 have only 2 → they become border points of cluster 0 P5 is 1.2 from P2, outside eps → it becomes NOISE result: 2 clusters · 4 core · 4 border · 2 noise eps = 1.5, minPts = 5 only P2 has 5 neighbors; it seeds cluster 0 all by itself every point of the right blob has 4 neighbors → no seed → all NOISE result: 1 cluster · 1 core · 4 border · 5 noise

Both moves make the same point: DBSCAN’s output is a function of the dataset and the two dials, and the dials have no universal right answer. Plot eps against the number of clusters and noise points, pick the plateau, and let the domain — not just the chart — break the tie.

Quick check

In this lesson's DBSCAN lab (eps = 1.5, minPts = 3, neighborhoods count the point itself), the point P5 at (3.2, 1) has exactly one other point within eps: the core point P2 at (2, 1). What is P5?

THE WIDER TOOLBOX

Clustering was
the doorway, not the house.

The same “no labels” setting supports soft clustering, anomaly detection, association rules and dimensionality reduction. Knowing which family answers which question is most of the skill.

GMM — soft clustering. K-means gives each point one hard label. A Gaussian Mixture Model assumes the data came from k overlapping bell curves, each with its own center, spread and weight, and fits them with the EM algorithm: the E-step computes each point’s probability of belonging to each component, the M-step updates the components from those probabilities. The result is a probability vector per point and — unlike k-means — elliptical clusters that may overlap.

Worked check: halfway between two Gaussians
Two equal-weight 1D components, both standard deviation 1: component 1: μ = 0 component 2: μ = 5 At x = 2.5 the point is exactly halfway: p₁ = 0.3989 · e^(−2.5²/2) = 0.3989 · e^(−3.125) = 0.01753 p₂ = 0.3989 · e^((2.5−5)²/2) = 0.3989 · e^(−3.125) = 0.01753 responsibilities = (0.5, 0.5) K-means on the same two centers also ties, but it must break the tie: the point lands 100% in one cluster. The GMM answer — "50/50, and genuinely uncertain" — is information the hard assignment threw away.

Anomaly detection for free. Each method has a built-in “this does not fit” signal: the distance from a point to its nearest k-means centroid, a DBSCAN noise label, or a low probability under every GMM component. Combine the signals and keep the agreements — a point that all three methods single out is a much safer alert than one that only one of them dislikes.

Association rules. Instead of grouping rows, market basket analysis looks for items that co-occur. For itemset A → B in n baskets: support = P(A and B), confidence = P(B | A), and lift = confidence / P(B) — how much more often B appears with A than it would alone. Lift above 1 means an association worth investigating; below 1 means the two items avoid each other. Same unsupervised setting, rows and columns swapped.

Dimensionality reduction. With hundreds of noisy features, distances concentrate and every cluster looks equally far away (the curse of dimensionality). PCA and t-SNE find a smaller set of directions that preserve most of the structure, and clustering then runs on two or ten dimensions instead of a thousand. That is a whole lesson of its own — Phase 1, Lesson 10 — and the natural next step after this one.

raw unlabeled datachoose a methodK-MEANSflat, round-ishclustersevery point assignedDBSCANany shape,noise allowedHIERARCHICALa tree of nestedclustersGMMsoft, ellipticaloverlappingthe same unlabeled points, four different definitions of “together”
Clustering is one family in the unsupervised toolbox. Dimensionality reduction compresses features instead of grouping rows; anomaly detection ranks points by how badly they fit; association mining finds rules between co-occurring items. The method map applies within each family.
MethodBest forAvoid when
K-MeansLarge datasets, compact spherical clusters, a k you can defendIrregular shapes, outliers, features on different scales
DBSCANUnknown k, arbitrary shapes, outlier detectionVarying densities, very high dimensions
HierarchicalSmall datasets, a dendrogram, exploring many k at onceLarge datasets (O(n²) time and memory)
GMMOverlapping clusters, soft assignments, elliptical shapesVery large datasets, too many dimensions
CHECK YOURSELF

Six questions.
Then the terms worth keeping.

Answer before you look. The moons question and the DBSCAN classification question are exactly the ones that separate a memorized definition from a working model.

0 / 6 answered · 0 correct

01What distinguishes unsupervised learning from supervised learning?

02What does K-Means require you to specify before training?

03K-Means fails on two interlocking half-moon shapes but DBSCAN succeeds. Why?

04What is the silhouette score measuring?

05How does a Gaussian Mixture Model differ from K-Means in its cluster assignments?

06In this lesson's DBSCAN lab (eps = 1.5, minPts = 3, neighborhoods count the point itself), the point P5 at (3.2, 1) has exactly one other point within eps: the core point P2 at (2, 1). What is P5?

Key terms, demystified

Click a card to swap the lazy description for what it actually means.

Exercises from the lesson

Four short problems with exact numbers. Try first; a worked answer is one click away.

  1. Implement K-Means++ initialization: pick the first centroid at random, then each next centroid with probability proportional to its squared distance from the nearest existing centroid. Work through one step by hand on the points (0,0), (1,0), (0,1), (10,0), (10,1), (11,0) with the first centroid at (0,0), and compare with uniform random initialization.
    Show one worked answer

    Squared distances to (0,0): (1,0) → 1; (0,1) → 1; (10,0) → 100; (10,1) → 101; (11,0) → 121. Total = 324. K-Means++ picks the next centroid with probabilities 1/324 ≈ 0.003, 1/324 ≈ 0.003, 100/324 ≈ 0.309, 101/324 ≈ 0.312, 121/324 ≈ 0.373 — a 99.4% chance of landing in the right-hand blob, so the two centroids nearly always start in different clusters. Uniform random initialization draws two distinct points from all six: the chance both land in the right blob is (3/6)·(2/5) = 0.2, and the chance both land in the left blob is also 0.2. In those 40% of runs the first assign step puts nothing on one side, an entire iteration is wasted, and the final inertia can be worse. Same algorithm, better start.

  2. Add hierarchical agglomerative clustering with Ward's linkage to the from-scratch code, returning a nested list of merges. Run it on the four points x = 1, 2, 4, 8 and report every merge height. Cut the dendrogram at heights 5 and 30 and compare the clusters with K-Means at k = 2.
    Show one worked answer

    Ward's merge cost is Δ = (n₁n₂ / (n₁ + n₂)) · ‖c₁ − c₂‖², where c is each cluster's centroid. Merge (1, 2): cost = (1·1/2)(1 − 2)² = 0.5, centroid 1.5. Merge ({1,2}, {4}): cost = (2·1/3)(4 − 1.5)² = 4.1667, centroid 7/3 ≈ 2.3333. Merge ({1,2,4}, {8}): cost = (3·1/4)(8 − 7/3)² = 0.75 × 32.1111 = 24.0833. Heights: 0.5, 4.17, 24.08. Cut at 5: the first two merges are below 5, the third is above, so the clusters are {1, 2, 4} and {8}. Cut at 30: all three merges are below, one cluster {1, 2, 4, 8}. For comparison, K-Means with k = 2 and farthest-first initialization also returns {1, 2, 4} and {8}, with the split falling inside the 4-wide gap — exactly where the tallest dendrogram bar says it should.

  3. Build a simple anomaly-detection pipeline: run DBSCAN and a 1D two-component GMM on the same data and flag points that both call unusual. Use components N(0, 1) and N(5, 1) with equal weights, and evaluate x = 3 and x = −4 by hand.
    Show one worked answer

    Gaussian density: p(x) = (1/√(2π))·e^(−(x−μ)²/2), so the shared constant is 0.3989. At x = 3: component 1 gives 0.3989·e^(−4.5) = 0.00443; component 2 gives 0.3989·e^(−2) = 0.05399; the weighted responsibilities are 0.5·0.00443 / (0.5·0.00443 + 0.5·0.05399) = 0.0758 and 0.9242. The point clearly belongs to component 2, so it is not an anomaly. At x = −4: component 1 gives 0.3989·e^(−8) = 1.338×10⁻⁴ and component 2 gives 0.3989·e^(−40.5) ≈ 1.0×10⁻¹⁸; the best (largest) weighted density is 6.69×10⁻⁵, far below any sensible threshold such as 10⁻³, so GMM flags it. DBSCAN flags a point as noise when its eps-neighborhood has fewer than minPts members — for x = −4 with eps = 1.5 and minPts = 3, it has no neighbours at all, so both methods agree. Where they disagree is the interesting case: a point between two Gaussians can have a decent likelihood (not an anomaly statistically) but still be sparse in DBSCAN's local sense, or vice versa for a tight far-away cluster of two points. Agreement-based pipelines keep the confident flags and hand the disagreements to a human.

  4. Run one full K-Means iteration by hand on the six points (1,1), (2,1), (1,2), (8,8), (9,8), (8,9) starting from centroids (2,1) and (9,9). Report the assignment, the inertia of that assignment, the new centroids, and the assignments and inertia after the next step.
    Show one worked answer

    Assign by squared distance. (1,1): to (2,1) is 1, to (9,9) is 128 → cluster 1. (2,1): 0 vs 113 → cluster 1. (1,2): 2 vs 113 → cluster 1. (8,8): 85 vs 2 → cluster 2. (9,8): 98 vs 1 → cluster 2. (8,9): 100 vs 1 → cluster 2. Assignment clusters keep the two triples, and inertia = 1 + 0 + 2 + 2 + 1 + 1 = 7. Move: cluster 1 mean is ((1+2+1)/3, (1+1+2)/3) = (4/3, 4/3); cluster 2 mean is ((8+9+8)/3, (8+8+9)/3) = (25/3, 25/3) ≈ (8.333, 8.333). Re-assign: (1,1) is 2/9 from the new first centroid; (2,1) and (1,2) are 5/9; (8,8) is 2/9 from the second; (9,8) and (8,9) are 5/9. Same triples, so inertia becomes 2/9 + 5/9 + 5/9 + 2/9 + 5/9 + 5/9 = 24/9 = 8/3 ≈ 2.667 and the algorithm settles. The init (2,1) is not a data point's centroid convention — any point works — and the iteration still lands on the same partition because the two blobs are far apart relative to their spread.

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • distance metricThe rule that turns two points into a number (usually Euclidean: √Σ(xᵢ − yᵢ)²). Clustering is only as meaningful as this choice — change the metric and the clusters change. (Phase 1, Lesson 14)
  • Gaussian distributionThe bell curve N(μ, σ²). A GMM models the whole dataset as a weighted mixture of these, one per cluster, which is what makes soft assignments possible. (Phase 1, Lesson 06)
  • varianceThe average squared distance from the mean — the number Ward's linkage tries to keep small when it merges clusters. (Phase 1, Lesson 15)
  • local minimumA state no single step improves even though better states exist elsewhere. K-Means converges to one: the final inertia depends on where the centroids started. (Phase 1, Lesson 08)
  • standardizationRescaling each feature to mean 0 and standard deviation 1. Distance-based clustering is not scale-invariant: an age column in years would drown a salary column in millions. (Phase 2, Lesson 02)
  • curse of dimensionalityIn high dimensions, distances concentrate and the nearest neighbour stops being meaningfully nearer than the farthest. Density-based and distance-based clustering both degrade; dimensionality reduction comes first. (Phase 1, Lesson 10)
  • maximum likelihoodChoosing parameters that make the observed data most probable. The M-step of a GMM is maximum likelihood with the E-step's soft assignments frozen. (Phase 1, Lessons 09 & 15)
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Lesson text adapted from AI Engineering from Scratch (Phase 02, Lesson 07) and the Math Foundations Notebook reference build. The k-means stepper, choose-k chart, shape comparison, dendrogram builder, DBSCAN explorer, silhouette console, both worked iterations, the DBSCAN classification walkthrough and every numeric check are original to this page. Every lab runs in your browser.