Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

3.3 Fitting a line, finding groups

🖥️ Lecture slides — Session 13 (Wed Oct 28). The slides use figures made by this notebook.

Learning outcomes. By the end of this notebook you can:

  1. write a straight-line model y=β1x+β0+εy = \beta_1 x + \beta_0 + \varepsilon and name its data, parameters and error;

  2. find the parameters that make the sum of squared errors smallest in three ways: a grid search, one matrix inversion, and small steps downhill;

  3. say how sure you are of the parameters, from the covariance matrix and from the bootstrap;

  4. fit a model with many inputs (rock density from seven oxides) with the same matrix equation y=Xβ+ε\mathbf{y} = X\boldsymbol{\beta} + \boldsymbol{\varepsilon};

  5. write the two steps of k-means (assign each sample to the nearest center, move each center to the mean of its samples) and watch them on Old Faithful for KK = 1 to 4;

  6. explain why the choice of KK is part of the result;

  7. reduce seven oxides to two principal components and cluster rocks without their labels;

  8. score clusters against known labels with homogeneity, completeness and the V-measure, and say what each one misses.

Two kinds of learning. Part 1 is supervised: every sample comes with the answer we want to predict (a weight, a density). Part 2 is unsupervised: there is no answer column, and the algorithm looks for structure (groups, directions) in the inputs alone.

To run it. From the repository root, pixi run jupyter lab, then open this notebook and run the cells from the top. Two downloads happen in Part 2: a small table of Old Faithful eruptions (3 KB) and four tables of seismic waveform features from Zenodo (about 3 MB, section 15). Without network the notebook prints a line that starts with FALLBACK and uses a synthetic substitute, so every cell still runs (the numbers in the text then no longer match). The people and the rocks are synthetic, made with a known rule so that we can check every answer.

Each Try it cell asks for one or two lines of code. The worked solution sits in the collapsed cell below it (click ⋯ to open). If you leave a Try-it cell unfinished, the solution cell fills in the answer so that the rest of the notebook runs.

How this notebook is organized

The first code cell imports every package the notebook uses, so a missing package fails at the top rather than halfway through. Code that draws a figure is written as a named function defined just before it is first needed, so that each analysis cell shows only the steps of the analysis. The function finish shows a figure; you can ignore its second argument, a file name used only when the lecture slides are built.

The values below are used in several places, so they are defined once.

Figure style: Arial, large type for the projector, and colors that stay distinct for color-blind readers (the Okabe-Ito palette). Groups also differ by marker shape, so that the figures read in black and white.

Part 1. Regression: learning a rule from examples

1. Height and weight: is there a rule?

We start far from the geosciences, with a question everyone has an intuition for: how does a person’s weight depend on their height? The 50 people below are synthetic. We made them with the rule weight = 68 kg + 0.8 kg per cm above 170 cm, plus a random scatter of 7 kg, so we know the right answer and can check how well each method recovers it.

Loading...
<Figure size 720x450 with 1 Axes>

Taller people tend to be heavier, but no single line passes through every point. Regression asks for the line that is closest to all the points at once, and then for how far off that line is.

2. The model: data, parameters, error

yi=β1xi+β0+εiy_i = \beta_1 x_i + \beta_0 + \varepsilon_i
  • Data (xi,yi)(x_i, y_i): what we measured, one pair per person. Here xix_i is the height above 170 cm and yiy_i the weight.

  • Parameters β0,β1\beta_0, \beta_1: what we solve for. β1\beta_1 is the slope (kg per cm); β0\beta_0 is the weight of a 170 cm person. (We measure height from 170 cm so that β0\beta_0 means something: the weight of a person 0 cm tall would not.)

  • Error εi\varepsilon_i: what the line misses for person ii, εi=yi−(β1xi+β0)\varepsilon_i = y_i - (\beta_1 x_i + \beta_0).

Below, a first guess of the line, with the error of every person drawn as a vertical segment.

findfont: Font family ['cursive'] not found. Falling back to DejaVu Sans.
findfont: Generic family 'cursive' not found because none of the following families were found: Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
<Figure size 720x450 with 1 Axes>

Try it 1: the errors of the guess. Compute eps_guess, the error of every person for the guessed line (B0_GUESS, B1_GUESS), and sse_guess, the sum of the squared errors. x and y are NumPy arrays.

Worked solution below (click ⋯ to open).

Notebook Cell
eps_guess: not filled in yet, so the worked solution is used.
sse_guess: not filled in yet, so the worked solution is used.
guessed line: sum of squared errors 1,927 kg^2; typical error (root mean square) 6.2 kg

3. The objective: make the sum of squared errors small

A good line has small errors for everyone at once. We add up the squared errors,

J(β0,β1)=∑iεi2=∑i(yi−β1xi−β0)2,J(\beta_0, \beta_1) = \sum_i \varepsilon_i^2 = \sum_i \left(y_i - \beta_1 x_i - \beta_0\right)^2,

and look for the (β0,β1)(\beta_0, \beta_1) that make JJ smallest. Squaring does two things: an error above the line and one below cannot cancel, and one large miss counts more than several small ones. JJ is called the objective, cost or misfit function.

The figure holds β0\beta_0 at the mean weight and tries three slopes. JJ as a function of the slope is a bowl, and the best slope is at its bottom.

with beta0 held at the mean weight (67.3 kg), the bottom of the bowl is at beta1 = 0.76 kg/cm
<Figure size 1200x430 with 2 Axes>

4. Three ways to find the bottom of the bowl

With two parameters, JJ is a bowl over the plane of (β0,β1)(\beta_0, \beta_1). Its bottom can be found in three ways, which are worth knowing because every method of this course uses one of them.

(a) Grid search. Try every combination on a grid and keep the best. Simple and safe, but the answer is only as fine as the grid, and the number of trials grows very fast with the number of parameters (21 values for each of 7 parameters is 1.8 billion trials).

grid search: 546 trials; best beta0 = 67.0 kg, beta1 = 0.80 kg/cm

(b) Matrix inversion. Write the 50 equations yi=β0+β1xi+εiy_i = \beta_0 + \beta_1 x_i + \varepsilon_i as one matrix equation,

y=Xβ+ε,X=[1x11x2⋮⋮1x50],β=[β0β1].\mathbf{y} = X\boldsymbol{\beta} + \boldsymbol{\varepsilon}, \qquad X = \begin{bmatrix} 1 & x_1 \\ 1 & x_2 \\ \vdots & \vdots \\ 1 & x_{50} \end{bmatrix}, \quad \boldsymbol{\beta} = \begin{bmatrix} \beta_0 \\ \beta_1 \end{bmatrix}.

The column of ones multiplies β0\beta_0, the column of heights multiplies β1\beta_1. Setting the slope of JJ to zero gives the normal equations XTXβ=XTyX^\mathsf{T} X \boldsymbol{\beta} = X^\mathsf{T} \mathbf{y}, whose solution is

β^=(XTX)−1XTy.\hat{\boldsymbol{\beta}} = (X^\mathsf{T} X)^{-1} X^\mathsf{T} \mathbf{y}.

One step, exact, and no grid. It works because the model is linear in its parameters; most machine-learning models are not.

Try it 2: the normal equations. X is given. Compute beta_hat, the array [β^0,β^1][\hat\beta_0, \hat\beta_1]. In NumPy, A @ B is the matrix product, A.T the transpose and np.linalg.inv(A) the inverse.

first rows of X:
 [[ 1.   2.7]
 [ 1.  -9.4]
 [ 1.   6.8]]

Worked solution below (click ⋯ to open).

Notebook Cell
beta_hat: not filled in yet, so the worked solution is used.

(c) Iterative: walk downhill. Start anywhere, compute which way JJ goes down fastest (minus its gradient), take a small step, repeat. This is gradient descent. It needs many steps, but it works for any model whose slope we can compute, which is how neural networks are trained (Chapter 4). k-means, later today, is also an iterative method.

Loading...
<Figure size 1200x400 with 3 Axes>

The gray curves are contours of JJ, like the contours of a topographic map: the bottom of the bowl is inside the smallest one. All three methods arrive at the same place. The grid search lands on the nearest grid point; the inversion lands exactly on the bottom; gradient descent first slides down the steep walls (the slope adjusts quickly) and then walks slowly along the flat valley floor (the intercept adjusts slowly).

5. The fit

The best line and its errors. A good model leaves errors that look like random scatter around zero, with no trend left in them.

best line: weight = 66.7 kg + 0.77 kg/cm x (height - 170 cm); typical error 5.3 kg (the rule that made the data: 68.0 kg + 0.8 kg/cm, scatter 7.0 kg)
<Figure size 1200x450 with 2 Axes>

The estimates (about 67 kg at 170 cm and 0.8 kg per cm) are close to, but not exactly, the rule that made the data. With another 50 people they would come out a little different. How different?

6. How sure are we?

The covariance matrix

If the errors are independent with the same spread σ\sigma, the parameters have the covariance matrix

C=σ2(XTX)−1,σ2≈∑iε^i2n−2.C = \sigma^2 (X^\mathsf{T} X)^{-1}, \qquad \sigma^2 \approx \frac{\sum_i \hat\varepsilon_i^2}{n - 2}.

The diagonal holds the variance of each parameter, so C00\sqrt{C_{00}} and C11\sqrt{C_{11}} are their standard errors. The estimate plus or minus two standard errors is about a 95% confidence interval. The off-diagonal term says whether the two parameters trade off against each other. (n−2n - 2 because two parameters were fitted.)

Try it 3: the covariance matrix. Compute cov_beta, the 2 x 2 matrix CC.

Worked solution below (click ⋯ to open).

Notebook Cell
cov_beta: not filled in yet, so the worked solution is used.
sigma = 5.42 kg (spread of the errors, from n - 2 = 48)
covariance matrix C:
 [[ 0.595  -0.0103]
 [-0.0103  0.0125]]
beta0 = 66.7 +/- 0.8 kg;  beta1 = 0.77 +/- 0.11 kg/cm (one standard error)
about 95% confidence interval for beta1 (two standard errors): 0.55 to 0.99 kg/cm
<Figure size 740x450 with 2 Axes>

Left: the shaded band holds the lines within two standard errors; it is narrowest near the middle of the data and widens at the ends. Right: the same uncertainty in the plane of the parameters.

The bootstrap

The formula above rests on assumptions about the errors. The bootstrap makes no formula: draw 50 people with replacement from our 50 (some appear twice, some not at all), refit, and repeat 1,000 times. The spread of the 1,000 fitted lines is the uncertainty. It is a brute-force method that works for almost any estimate, including ones without a formula. One resample of our 50 people looks like this:

rows in one resample: [ 0  1  1  3  4  5  6  6  6  7 10 12 12 13 13 14 15 15 16 19 20 20 21 22
 22 23 24 24 25 25 26 27 32 37 37 37 37 39 40 41 41 41 43 43 45 47 47 48
 48 49]
32 different people of 50; the others are left out, and some are drawn twice or more

Try it 4: bootstrap the line. Fill boot, an array of shape (N_BOOT, 2): for each resample, draw n row numbers with rng.integers(0, n, n), take those rows of X and y, and solve the normal equations as in Try it 2.

Worked solution below (click ⋯ to open).

Notebook Cell
boot (its spread): not filled in yet, so the worked solution is used.
standard error of beta0: covariance matrix 0.77 kg, bootstrap 0.76 kg
standard error of beta1: covariance matrix 0.112 kg/cm, bootstrap 0.106 kg/cm
<Figure size 740x450 with 2 Axes>

The two ways agree: the cloud of bootstrap estimates fills the ellipses of the covariance matrix. Both say that the slope is known to about ±0.1 kg/cm from 50 people.

7. Many inputs: rock density from major-element chemistry

Back to the geosciences. The rock table of notebook 3.2 holds 5,000 synthetic rocks (granite, basalt and andesite) with seven major-element oxides (wt%) and the bulk density (g/cm³). Mafic rocks such as basalt are rich in FeO, MgO and CaO and dense (about 2.95 g/cm³); felsic rocks such as granite are rich in SiO₂ and K₂O and lighter (about 2.65 g/cm³).

The model is the same equation with more columns,

densityi=β0+β1 SiO2,i+β2 Al2O3,i+⋯+β7 K2Oi+εi,\text{density}_i = \beta_0 + \beta_1\,\text{SiO}_{2,i} + \beta_2\,\text{Al}_2\text{O}_{3,i} + \dots + \beta_7\,\text{K}_2\text{O}_i + \varepsilon_i,

so XX now has 8 columns (ones and 7 oxides) and 5,000 rows, and β^=(XTX)−1XTy\hat{\boldsymbol\beta} = (X^\mathsf{T}X)^{-1}X^\mathsf{T}\mathbf{y} still gives the answer in one step.

label
granite     2794
basalt      1713
andesite     493
Loading...

Try it 5: many inputs. Build X_rock, a column of ones followed by the 7 columns OXIDES of rocks, and solve the normal equations for beta_rock (8 values).

Worked solution below (click ⋯ to open).

Notebook Cell
X_rock: not filled in yet, so the worked solution is used.
beta_rock: not filled in yet, so the worked solution is used.
Loading...

How good is it? We compare three models by their mean absolute error (MAE), the average size of the miss in g/cm³: the mean density for every rock (no inputs), SiO₂ alone, and all seven oxides.

Loading...
<Figure size 1200x450 with 2 Axes>

Seven oxides predict density to about 0.025 g/cm³, five times better than the mean alone. But SiO₂ alone does almost as well. The oxides rise and fall together (a basalt has little SiO₂ and much FeO, MgO and CaO), so the other six add little that SiO₂ did not already say. Keep this in mind for Part 2: many columns do not mean much independent information.

Part 2. Unsupervised learning: structure without an answer column

In Part 1 every sample came with the value we wanted to predict. Now there is none: only inputs. The question becomes which samples belong together? (clustering) or which directions carry the information? (dimensionality reduction).

8. Old Faithful: two eruption regimes

Old Faithful in Yellowstone erupts every one to one and a half hours, in two regimes: short eruptions of about 2 minutes and long ones of about 4.3 minutes. The table holds 272 consecutive eruptions (Azzalini and Bowman 1990, distributed with R as faithful), arranged in pairs: one sample is a pair of consecutive eruptions, the duration of an eruption (current_min) and the duration of the next one (next_min). That gives 271 pairs.

Old Faithful: 271 pairs of consecutive eruptions
Loading...
<Figure size 720x450 with 1 Axes>
median duration (min): {'long': 4.3, 'short': 2.0}
Loading...

Two regimes make four possible kinds of pair. Three are common: short then long (upper left, 91 pairs), long then long (upper right, 83) and long then short (lower right, 91). Short then short (lower left) happened only 6 times: after a short eruption, the next one is long in 94% of cases, while after a long eruption the next one is short in 52%. A common explanation is that a short eruption does not empty the geyser’s reservoir, so the next eruption is a long one. Nobody labeled the pairs; can an algorithm find the groups?

9. k-means, step by step

Distance. k-means groups samples that are close. Close is measured with the Euclidean distance between a sample x\mathbf{x} and a center μ\boldsymbol\mu:

d(x,μ)=(x1−μ1)2+(x2−μ2)2.d(\mathbf{x}, \boldsymbol\mu) = \sqrt{(x_1 - \mu_1)^2 + (x_2 - \mu_2)^2}.

We first standardize each column (subtract its mean, divide by its standard deviation), so that every column counts equally in the distance. Here both columns are durations in minutes with the same spread, so standardizing changes little; in most data the columns have different units and ranges (the rocks below, or duration against waiting time in minutes), and the column with the largest numbers would otherwise decide every distance. The figures are drawn in minutes, the arithmetic is done in standardized units.

The loop. (1) Put KK centers somewhere. (2) Assign: each sample joins its nearest center. (3) Update: move each center to the mean of its samples. Repeat (2) and (3) until no center moves. Each step can only lower the total squared distance from the samples to their centers, J=∑id(xi,μc(i))2J = \sum_i d(\mathbf{x}_i, \boldsymbol\mu_{c(i)})^2, so the loop always stops.

Try it 6: the assign step. Complete nearest_center(Z, centers). Z has shape (n, 2) and centers shape (K, 2). Return an array of n integers: the index of the nearest center of each sample.

Hint: Z[:, None, :] - centers[None, :, :] has shape (n, K, 2): every sample minus every center. Square, sum over the last axis, take the square root, then argmin(axis=1).

Worked solution below (click ⋯ to open).

Notebook Cell
nearest_center: not filled in yet, so the worked solution is used.

The update step and the loop are given.

K = 3: converged after 5 updates; groups of [93 97 81] pairs
<Figure size 1200x370 with 4 Axes>

From the left: three centers placed by hand in a row along the bottom; each pair joins the nearest center; each center moves to the mean of its pairs (arrows); the loop repeats assign and update until nothing changes. At first the orange center takes all the long-first pairs, so it moves up between their two groups; once the green center climbs to the long-then-long pairs, orange moves back down. After 5 updates each center sits in one of the three common kinds of pair.

Now the same loop for KK = 1 to 4. A bad start can stop the loop at a poor solution, so for each KK we start it N_STARTS times from KK pairs drawn at random and keep the run with the smallest JJ. The lines track every center of that run from its start (hollow circle) to its final position (cross).

K = 1: J from 542.0 (best start) to 542.0 (worst start); best run 1 updates, group sizes [271]
K = 2: J from 211.9 (best start) to 211.9 (worst start); best run 4 updates, group sizes [106 165]
K = 3: J from 74.0 (best start) to 183.9 (worst start); best run 5 updates, group sizes [93 97 81]
K = 4: J from 49.4 (best start) to 65.3 (worst start); best run 3 updates, group sizes [82  6 92 91]
<Figure size 1200x400 with 4 Axes>

With K=3K = 3 the centers settle on the three common kinds of pair; with K=4K = 4 the fourth center finds the 6 rare short-then-short pairs. k-means returns KK groups for any KK we ask for; whether they mean something is for us to judge.

Where are the boundaries? Every point of the plane, not only the eruption pairs, belongs to its nearest center. The border between two centers is the set of points at equal distance from both: a straight line halfway between them, at right angles to the line joining them (in standardized units). The regions form a Voronoi diagram (a topic for further study; the same construction gives the “nearest station” regions of a seismic network).

<Figure size 1200x400 with 4 Axes>

10. Choosing K: the elbow

k-means needs KK before it starts. A common guide is the elbow of the curve of JJ (the total squared distance to the centers) against KK. JJ always decreases as KK grows (with one center per sample, J=0J = 0), so we look for the KK after which adding a center stops paying off.

We compute the curve for Old Faithful and for the rocks of Part 1 (seven standardized oxides), and plot the one of Old Faithful. scikit-learn’s KMeans runs the same loop as ours, from 10 starts, and keeps the best.

Loading...
<Figure size 720x410 with 1 Axes>

For Old Faithful the curve bends at K=3K = 3 or 4. There are four kinds of pair, but the short-then-short pairs are only 6 of 271, too few to lower JJ much. For the rocks, the biggest drop is at K=2K = 2, yet the table holds three rock types; andesite is only 10% of the samples and sits between the other two, so a third center pays off less. In both cases a small group hides from the elbow. Reading an elbow is a judgment, and two people can read the same curve differently. For further study: the silhouette score asks, for every sample, whether it is closer to its own group than to the next one (sklearn.metrics.silhouette_score).

11. Rock chemistry without labels

Hide the rock type and keep only the seven oxides. Each rock is now a point in a seven-dimensional space: we cannot plot it, and there are 21 pairs of oxides to look at.

Loading...
<Figure size 560x460 with 36 Axes>

12. Why reduce the dimension first?

Many of the 21 small plots are nearly straight lines: those oxides repeat each other. The Pearson correlation coefficient of two columns xx and yy measures it,

r=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2 ∑i(yi−yˉ)2,−1≤r≤1,r = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sqrt{\sum_i (x_i - \bar x)^2}\,\sqrt{\sum_i (y_i - \bar y)^2}}, \qquad -1 \le r \le 1,

and the correlation matrix holds rr for every pair of oxides. A correlation rr near +1 or −1 means that knowing one oxide almost tells you the other; such a pair holds about one number’s worth of information in two columns.

Loading...
<Figure size 1200x450 with 4 Axes>
SiO2 and Al2O3, for comparison: r = -0.53

FeO and MgO move together (r = 0.96), SiO₂ and FeO move against each other (r = −0.98). (The row of points at MgO = 0 comes from the synthetic table, which sets negative values to 0 wt%.) Not every pair is redundant: SiO₂ and Al₂O₃ correlate only moderately (r = −0.53). Redundant columns are a problem for k-means: a property measured by four oxides counts four times in the distance. They also hide the structure in a forest of plots.

13. PCA: new axes made of the old ones

Which single axis describes the rocks best? We could pick one oxide, SiO₂ for instance. Principal component analysis (PCA) does better: it builds a new axis that mixes the old ones, a weighted sum of the standardized oxides,

PC1=w1 SiO2+w2 Al2O3+w3 FeO,w12+w22+w32=1,\text{PC1} = w_1\,\text{SiO}_2 + w_2\,\text{Al}_2\text{O}_3 + w_3\,\text{FeO}, \qquad w_1^2 + w_2^2 + w_3^2 = 1,

with the weights chosen so that the rocks spread out along it as much as possible. The spread is measured by the variance, a number for how spread out the data are: the average squared distance from the mean, Var⁡(z)=1n∑i(zi−zˉ)2\operatorname{Var}(z) = \frac{1}{n}\sum_i (z_i - \bar z)^2. After standardizing, every oxide has variance 1. PC2 is the best axis at right angles to PC1, PC3 the best at right angles to both, and so on. Turning to these axes removes nothing; it reorders the information so that the first few axes hold most of it, and we can drop the rest.

First with three oxides, so that we can draw the cloud: SiO₂, Al₂O₃ and FeO, each standardized as for k-means.

Loading...

Each row is one new axis, written as a recipe of the three oxides. How much of the variance of the cloud does a single axis keep? For one standardized oxide, its variance (1) over the total (3): a third. For PC1, the variance of the rocks’ PC1 values over the same total:

SIO2 33.3 AL2O3 33.3 FEO 33.3 PC1 79.2 Name: variance kept by this one axis (%), dtype: float64
<Figure size 1200x440 with 2 Axes>

The long direction of the cloud (PC1, the arrow) does not run along any of the three oxide axes: it points toward low SiO₂ and high Al₂O₃ and FeO at the same time, the mafic direction. Its recipe is PC1 = −0.62 SiO₂ + 0.48 Al₂O₃ + 0.62 FeO. Picking any one oxide keeps a third of the variance (33%); mixing all three keeps 79%. That is the idea of PCA: the best axis is a combination of the old ones. (The sign of a component is arbitrary: −PC1 is the same axis, pointing the other way.)

PC2 is the best axis at right angles to PC1: PC2 = 0.34 SiO₂ + 0.88 Al₂O₃ − 0.33 FeO, mostly Al₂O₃, and it keeps 20%. PC1 and PC2 together span a plane that holds 99% of the variance of the three oxides; only PC3 (1%), across the plane, is left out. Projecting every rock onto that plane replaces three numbers by two.

<Figure size 1200x440 with 2 Axes>

Now all seven oxides. Nothing changes but the number of weights in each recipe: seven instead of three.

Try it 7: PCA on all seven oxides. Fit pca = PCA() on Z_rock (standardized above, for the elbow) and store in scores the first two columns of pca.transform(Z_rock).

Worked solution below (click ⋯ to open).

Notebook Cell
pca: not filled in yet, so the worked solution is used.
scores: not filled in yet, so the worked solution is used.
variance explained by each component (%): [78.7 12.4  6.6  1.3  0.5  0.4  0.2]
PC1 and PC2 together: 91.1%
Loading...
<Figure size 1200x410 with 2 Axes>

Two components keep 91% of the variance of seven oxides. PC1 (79%) weighs SiO₂, K₂O and Na₂O against FeO, MgO and CaO: it is the mafic-to-felsic axis, from basalt to granite. PC2 (12%) is mostly Al₂O₃ and Na₂O. The table of 5,000 rocks shrinks from seven columns to two:

Loading...
<Figure size 640x450 with 1 Axes>

14. k-means on the principal components

Three groups are visible by eye. Try it 8. Fit km_rock = KMeans(n_clusters=3, n_init=10, random_state=SEED) on scores.

Worked solution below (click ⋯ to open).

Notebook Cell
km_rock: not filled in yet, so the worked solution is used.

Only now do we look at the hidden rock types, to judge the groups. The cross-table counts the rocks of each type in each cluster.

rocks in the cluster of their own type: 99.0% on PC1-PC2, 99.4% on all 7 oxides
Loading...
<Figure size 1200x410 with 2 Axes>

Without ever seeing a label, k-means on two principal components puts 99% of the rocks in the cluster of their own type; the misplaced rocks are mostly andesites at the edge of the basalt cluster. k-means on all seven standardized oxides does as well here, so PCA did not change the answer for these rocks. What PCA gave us is the same grouping from two numbers instead of seven, a picture we can check by eye, and axes with a geological meaning. With many more features, of which many repeat each other (the 61 waveform features of section 15), reducing first also keeps the redundant features from deciding the distances.

15. A harder case: seismic sources from 61 waveform features

The rocks were an easy case. Here is a real and harder dataset: 4,000 events recorded by the Pacific Northwest Seismic Network, 1,000 of each type labeled by analysts (earthquake, explosion, surface event such as a rockfall, and noise), each described by 61 features computed from its waveform (Kharita et al. 2026, Seismica; data on Zenodo, record 14025693). We repeat the same steps, standardize, PCA, k-means, and keep the labels aside. How many components should we keep? For the rocks, two of seven kept 91% of the variance. Here we keep the smallest number of components that together keep 80%.

PNW seismic features: 4 tables read from Zenodo
4000 events, 61 features; the variance kept by PC1 is 26.5%, by PC1 and PC2 43.6%, by 15 components 80.9%
k-means (K = 4) on 15 components, against the analyst labels:
Loading...
<Figure size 1200x415 with 2 Axes>

Left: the 4,000 events on PC1 and PC2, colored by the analyst labels for viewing only. Earthquakes and noise sit apart; explosions and surface events overlap in the middle. But this picture holds only 44% of the variance. Right: the variance kept by the first components. PC1 alone keeps 26.5%, and 15 of the 61 components are needed to keep 80%, against 2 of 7 for 91% with the rocks. The 61 features repeat each other much less than the seven oxides did, so the variance is shared by many components.

The table above compares the k-means clusters (K = 4, on the 15 components) with the analyst labels. Most earthquakes (768 of 1,000) form one cluster and noise is split over two (692 and 252), but most explosions and surface events (730 and 777) share one cluster. Clustering finds the structure that the features contain, and these features do not separate a blast from a rockfall. Section 16 asks how close these clusters come to the analysts’ four source types, and how to put a number on it. For further study with this dataset: the silhouette score, t-SNE, and other clustering methods.

16. Practice: do the four source types come back?

About 20 minutes, in pairs. The crosstab in section 15 shows that k-means found some of the analysts’ categories and not others. In this section you put a number on that, calibrate the number against two clusterings that need no algorithm, and test whether a different number of clusters would do better. On Monday the same 4,000 events become a supervised problem, so the numbers you get here are the ones a classifier trained with the labels will have to beat.

Scoring clusters against labels

Using labels to score an unsupervised method treats clustering as unsupervised classification: the algorithm never sees the labels, and we use them afterwards only to judge the result.

Accuracy does not work here. k-means numbers its clusters 0, 1, 2, 3 in an arbitrary order, and nothing tells it that cluster 2 should be “explosion”. Two scores avoid this problem because they ask only which events end up together:

  • Homogeneity: does each cluster hold events of a single source type? It is 1 when every cluster is pure. Think of a geologic map where each map unit contains only one rock type.

  • Completeness: do all events of one source type end up in the same cluster? It is 1 when no source type is split. On the map, each rock type would appear in only one map unit.

  • V-measure: the harmonic mean of the two, as the F1 score is for precision and recall. It is high only when both are high.

All three run from 0 to 1. On the crosstab, homogeneity reads along the rows (is each cluster dominated by one column?) and completeness reads down the columns (is each source type concentrated in one row?). The two pull against each other: putting every event in its own cluster gives perfect homogeneity and poor completeness, and putting all events in one cluster does the opposite. Formally both are built from conditional entropies (Rosenberg & Hirschberg 2007, EMNLP-CoNLL, 410–420), but you need only the two questions above.

The cell below defines check, which compares your answer with a reference. If your cell is unfinished or gives a different result, it prints a hint and uses the reference, so the rest of the notebook still runs.

Notebook Cell

Your turn (1): score the k-means clusters

homogeneity_completeness_v_measure(labels_true, labels_pred) returns the three scores at once. The analyst labels are y_seis; the k-means clusters from section 15 are clusters_seis.

Hint: one line; the true labels come first.

Worked solution below (click ⋯ to open it).

Notebook Cell
hcv: not answered yet. Hint: homogeneity_completeness_v_measure(y_seis, clusters_seis)
  Using the reference result below.
homogeneity 0.36, completeness 0.39, V-measure 0.37

Your turn (2): two clusterings that need no algorithm

A score means little until you know what a useless clustering gets. Build two:

  • one_cluster: every event in cluster 0;

  • random_clusters: each event in a random cluster from 0 to 3, using the random generator rng defined in the cell.

Both must have one entry per event, len(y_seis) = 4,000.

Hint: np.zeros(len(y_seis), dtype=int) and rng.integers(0, 4, len(y_seis)).

Worked solution below (click ⋯ to open it).

Notebook Cell
one_cluster: not answered yet. Hint: np.zeros(len(y_seis), dtype=int)
  Using the reference result below.
random_clusters: not answered yet. Hint: rng.integers(0, 4, len(y_seis))
  Using the reference result below.
Loading...

One cluster is perfectly complete, since no source type is split, and has zero homogeneity, so its V-measure is 0. Random clusters score close to 0 on all three. k-means sits well above both and well below 1: the 61 features contain real structure, but not exactly the four categories the analysts use.

Your turn (3): does a different number of clusters do better?

We asked k-means for four clusters because there are four source types, but nothing forces the structure in the features to have four groups. Fill in the loop: for each K from 2 to 8, cluster X_pca_seis with KMeans(n_clusters=k, n_init=N_STARTS, random_state=SEED), score the clusters against y_seis, and append the three numbers to scores_by_k.

Hint: inside the loop, two lines: clusters = KMeans(...).fit_predict(X_pca_seis), then scores_by_k.append(homogeneity_completeness_v_measure(y_seis, clusters)).

Worked solution below (click ⋯ to open it).

Notebook Cell
scores_by_k: not answered yet. Hint: KMeans(n_clusters=k, n_init=N_STARTS, random_state=SEED).fit_predict(X_pca_seis), then score and append
  Using the reference result below.
<Figure size 800x400 with 1 Axes>
Loading...

Homogeneity rises overall with K: smaller clusters are purer. Completeness falls after K = 3: each source type is split over more clusters. The V-measure is highest at K = 3 (0.43), not at K = 4 (0.37). With three clusters, k-means finds earthquakes, noise, and explosions together with surface events, so the features hold about three groups, not the analysts’ four. Adding clusters splits the existing groups instead of separating blasts from rockfalls: the limit is in the features, not in K.

Pause and discuss (5 minutes, with your partner):

  1. Explosions and surface events share one cluster for every K. Both are shallow sources with emergent waveforms. What information does an analyst use to tell a quarry blast from a rockfall that is not in these 61 waveform features? (Think back to notebook 3.2.)

  2. Suppose your goal is a catalog of earthquakes only. Which matters more for the earthquake cluster, homogeneity or completeness, and what does each kind of error do to the catalog?

  3. On Monday a classifier will be trained with the labels. What V-measure, or what per-class result from the crosstab, should it beat to show that the labels added something?

Points to bring out
  1. Time of day and location. In notebook 3.2, 94% of explosions occur between 08:00 and 17:00 local time, at quarries and mines; rockfalls and other surface events cluster on volcano flanks and steep slopes. Neither is a waveform feature, so clustering on waveforms cannot use them.

  2. A pure earthquake cluster (high homogeneity) keeps blasts and noise out of the catalog, which matters for seismicity rates and hazard. A complete one misses no earthquakes. Seismologists usually accept some missed small events rather than contaminate the catalog, and decide the trade-off with a threshold, the subject of the next lectures on precision and recall.

  3. At least the best unsupervised result: V-measure 0.43 at K = 3 (0.37 at K = 4), and the per-class pattern of the crosstab (earthquakes about 77% in one cluster, explosions and surface events mixed). A supervised model that does not separate explosions from surface events has learned little that the features did not already show.

Summary

MethodQuestionWhat it makes smallToday’s example
Linear regressionHow does yy depend on xx?∑iεi2\sum_i \varepsilon_i^2weight from height; density from 7 oxides
Covariance matrix, bootstrapHow sure is the fit?(spread of the estimates)slope 0.77 ± 0.11 kg/cm
k-meansWhich samples belong together?∑id(xi,μc(i))2\sum_i d(\mathbf{x}_i, \boldsymbol\mu_{c(i)})^2the kinds of eruption pair at Old Faithful
PCAWhich directions carry the information?the variance left out7 oxides to 2 components, 91%
Homogeneity, completeness, V-measureDo the clusters match known labels?(scores, nothing is fitted)PNSN source types: V-measure 0.37 at K = 4, 0.43 at K = 3

For further study. The silhouette score for choosing KK; Voronoi diagrams; regularized regression (ridge, lasso) for many correlated inputs; Gaussian mixtures, which let each cluster have its own shape.