Regression: fitting a line,
clustering: groups without labels

Session 13 · Wed Oct 28 · Book sections 3.2–3.3

📈

Today’s question

How does a machine learn a rule from examples, and find groups when nobody gives it the answer?

  1. Regression: fit a line by making the squared errors small
  2. k-means clustering: find groups without labels
  3. PCA, then k-means: fewer axes, the same groups

Part 1 · Regression

Learn a rule from examples that come with answers

1 Regression · 2 k-means clustering · 3 PCA

Height and weight: is there a rule?

Synthetic: 50 adults made from a known rule, so every answer can be checked

Weight against height for 50 synthetic adults; weight rises with height.


Taller people tend to be heavier, but no line passes through every point

  • Regression: find the line closest to all the points at once
  • … and say how far off it is

y = β1x + β0 + ε: data, parameters, error

The same people with a guessed straight line and a vertical segment for each person's error.

Data (xi, yi)
measured, one pair per person

Parameters β0, β1
what we solve for

Error εi = yi − (β1xi + β0)
what the line misses

x = height − 170 cm, so β0 is the weight of a 170 cm person

We keep the data and choose the parameters; the errors are what the line misses. This first guess misses by 6.2 kg on average.

The objective: make the squared errors small

\[J(\beta_0, \beta_1) = \sum_i \varepsilon_i^2 = \sum_i (y_i - \beta_1 x_i - \beta_0)^2\]

Three candidate lines on the data, and the sum of squared errors against slope: a bowl.

The best slope sits at the bottom of the bowl.

Three ways to find the bottom of the bowl

Contours of the squared error over slope and intercept, with the paths of grid search, matrix inversion and gradient descent. Grid search: try them all Inversion: one exact step Iterative: walk downhill

All three reach β1 ≈ 0.77 kg/cm. You can choose the appropriate method for your situation.

Matrix inversion: y = Xβ

\[ \begin{array}{cccccc} \begin{bmatrix} y_1 \\ 64.9 \\ 63.2 \\ \vdots \\ y_{50} \end{bmatrix} & = & \begin{bmatrix} 1 & x_1 \\ 1 & -9.4 \\ 1 & 6.8 \\ \vdots & \vdots \\ 1 & x_{50} \end{bmatrix} & \begin{bmatrix} \beta_0 \\ \beta_1 \end{bmatrix} & + & \begin{bmatrix} \varepsilon_1 \\ \varepsilon_2 \\ \varepsilon_3 \\ \vdots \\ \varepsilon_{50} \end{bmatrix} \\[6pt] \mathbf{y} & & X & \boldsymbol\beta & & \boldsymbol\varepsilon \\ \scriptsize\text{weight (kg)} & & \scriptsize\text{ones and } x & \scriptsize\text{parameters} & & \scriptsize\text{errors} \\ \scriptsize 50 \times 1 & & \scriptsize 50 \times 2 & \scriptsize 2 \times 1 & & \scriptsize 50 \times 1 \end{array} \]

In Python: beta = np.linalg.inv(X.T @ X) @ (X.T @ y)

Weight against height for 50 synthetic adults. (x1, y1)

The best β, in one step:

\[X^\mathsf{T}X\,\boldsymbol\beta = X^\mathsf{T}\mathbf{y}\]

\[\boldsymbol\beta = (X^\mathsf{T}X)^{-1}X^\mathsf{T}\mathbf{y}\]

β0 = 66.7 kg, β1 = 0.77 kg/cm

Stacking the 50 equations gives one matrix equation, and β = (XTX)−1XTy is the exact bottom of the bowl, in one step.

The fit: 0.77 kg per cm

Best-fit line on the data, and the errors against height scattered around zero.

Weight = 66.7 kg + 0.77 kg/cm × (height − 170 cm); the errors scatter around zero with no trend left, typically 5.3 kg.

How sure are we? The covariance matrix

Band of lines within two standard errors, and standard-error ellipses in parameter space. On the data In parameter space


\[C = \sigma^2 (X^\mathsf{T}X)^{-1}\]

σ = 5.4 kg: spread of the errors

standard errors = √(diagonal of C):

β0 = 66.7 ± 0.8 kg
β1 = 0.77 ± 0.11 kg/cm

off-diagonal: β0, β1 trade-off

β1 = 0.77 ± 0.11 kg/cm (one standard error); two standard errors, 0.55 to 0.99 kg/cm, is about a 95% confidence interval.

How sure are we? The bootstrap

200 bootstrap lines on the data, and 1,000 bootstrap estimates filling the covariance ellipses. 200 of 1,000 refits In parameter space

Original samples: (x1, x2, x3, x4, x5, …, x50)
Bootstrap samples: (x3, x3, x4, x6, x8, …, x47)

  1. Draw 50 people from the 50, with replacement
  2. Fit the line again
  3. Repeat 1,000 times
  4. The spread of the 1,000 fits is the uncertainty

β1 ± 0.106 kg/cm: bootstrap
β1 ± 0.112 kg/cm: formula

Refitting 1,000 resamples gives ± 0.106 kg/cm for the slope, close to the ± 0.112 kg/cm of the formula.

Many inputs: rock density from chemistry

Synthetic rock table of notebook 3.2 (mlgeo_synth): 5,000 rocks, 7 major-element oxides (wt%), density

Hand sample of dark gray basalt.
Basalt
~49 wt% SiO2 · ~2.95 g/cm3
Hand sample of light, speckled biotite granite.
Granite
~72 wt% SiO2 · ~2.65 g/cm3

Photos: GeoDIL 140 (M. Davis) and 18 (D. Perkins), CC0, via Wikimedia Commons

density = β0 + β1SiO2 + β2Al2O3 + … + β7K2O + ε

  • One β per oxide: how much density changes per wt% of that oxide
  • Basalt: rich in FeO, MgO, CaO, dense
  • Granite: rich in SiO2, K2O, light

Same y = Xβ + ε, with 8 columns in X (a column of ones and 7 oxides) and 5,000 rows.

Seven oxides predict density; SiO2 alone nearly as well

Predicted against measured density, seven oxides.
Density against SiO2 by rock type.

Mean absolute error: 0.132 g/cm3 with no inputs, 0.025 with SiO2 alone, 0.025 with all 7 oxides. The oxides repeat each other.

Part 2 · k-means clustering

Find groups in data that come without answers

1 Regression · 2 k-means clustering · 3 PCA

Unsupervised learning: no answer column

Height and weight with a fitted rule, next to unlabeled pairs of Old Faithful eruptions. Supervised: every x comes with its y Unsupervised: inputs only

Without answers the question changes: which samples belong together (clustering), and which directions carry the information (PCA)?

Old Faithful: two eruption regimes

Old Faithful geyser, Yellowstone: 271 pairs of consecutive eruptions (Azzalini & Bowman 1990)

Old Faithful erupting in winter, with visitors behind a sign.

Photo: NPS / Yellowstone National Park, public domain

Next eruption duration against eruption duration for 271 Old Faithful pairs: three main groups and a rare fourth.

One sample is a pair of consecutive eruptions. Two regimes, short (~2 min) and long (~4.3 min), make three common kinds of pair; short then short happened only 6 times.

How k-means works: assign, update, repeat

distance: d(x, μ) = √[(x1 − μ1)2 + (x2 − μ2)2]   on standardized durations

k-means with three centers on Old Faithful: start, assign, update, and assign again. 1. Start: 3 centers 2. Assign to nearest 3. Move to the mean 4. Assign again
k-means with three centers on Old Faithful in four steps: start, assign, update, converged. 1. Start: 3 centers 2. Assign to nearest 3. Move to the mean 4. Repeat until stable

Each step lowers J = Σ d(xi, μ)2, the total squared distance to the centers; after 5 updates each center sits in one of the three common kinds of pair.

K = 1, 2, 3, 4: the centers walk to their groups

k-means for K = 1 to 4 on Old Faithful, with the track of each center. K = 1 · 1 update K = 2 · 4 updates K = 3 · 5 updates K = 4 · 3 updates

K = 3 finds the three common kinds of pair, K = 4 also the 6 rare short-short pairs

Each center owns a region

The region owned by each center for K = 1 to 4, separated by straight borders. K = 1 K = 2 K = 3 K = 4

Every point of the plane goes to its nearest center, so the borders are straight lines halfway between centers: a Voronoi diagram (further study).

Choosing K: the elbow

J against the number of clusters for Old Faithful.
Old Faithful
J against the number of clusters for the rocks, seven oxides.
Rocks: 7 oxides
Density against SiO2: three rock types, basalt, andesite and granite.

J always drops as K grows. Old Faithful bends at K = 3 or 4; the rocks bend at K = 2, yet hold 3 rock types. Further study: silhouette score.

Part 3 · Principal component analysis

PCA: find the few directions that carry most of the information

1 Regression · 2 k-means clustering · 3 PCA

Rock chemistry without labels: 7 numbers per rock

Major-element oxides (wt%), first 8 of 5,000 rocks

rock SiO2 Al2O3 FeO MgO CaO Na2O K2O
0 46.5 15.5 10.9 8.4 12.4 2.0 0.2
1 74.7 12.8 0.4 0.0 0.1 3.8 5.2
2 46.9 15.2 10.6 8.1 12.7 3.1 0.8
3 48.3 15.3 10.3 6.9 11.8 2.5 0.0
4 73.7 14.2 1.4 0.0 0.0 4.5 5.4
5 61.5 16.1 6.3 2.8 5.2 3.7 2.5
6 47.3 15.0 11.0 8.0 11.9 3.3 1.0
7 51.4 14.2 8.9 5.6 10.8 4.0 1.1

Scatter plots of all 21 pairs of seven oxides.

Each rock is a point in 7 dimensions: no single plot shows it, and there are 21 pairs of oxides to look at.

Why reduce the dimension first?

Correlation matrix of seven oxides, FeO against MgO, and SiO2 against FeO.

Pearson correlation coefficient

\[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}}\]

r = +1: the two rise together on a straight line
r = 0: no straight-line link
r = −1: one rises as the other falls

FeO and MgO rise together (r = 0.96), SiO2 and FeO move opposite (r = −0.98): each such pair holds about one number of information in two columns.

PCA: the best axis mixes the old ones

PC1 = −0.62 SiO2 + 0.48 Al2O3 + 0.62 FeO

3-D cloud of standardized SiO2, Al2O3 and FeO with the PC1 arrow, and bars of the variance kept by one oxide or by PC1. Three oxides, one new axis Variance kept by one axis

Variance is a number for how spread out the data are.

Picking one oxide keeps 33% of the variance; PC1, a weighted mix of all three, keeps 79%.

PC1 and PC2: three numbers become two

PC2 = 0.34 SiO2 + 0.88 Al2O3 − 0.33 FeO, at right angles to PC1

The same 3-D cloud with PC1, PC2 and the plane they span, and the rocks projected onto that plane. PC1 and PC2 span a plane Rocks projected onto the plane

PC1 and PC2 keep 99% of the variance of SiO2, Al2O3 and FeO; only PC3 (1%), across the plane, is dropped.

PCA on seven oxides: two axes keep 91%

Variance explained by each principal component, and the loadings of the oxides on PC1 and PC2. Variance kept by each axis What PC1 and PC2 measure

PC1 (79%) sets SiO2, K2O, Na2O against FeO, MgO, CaO: the mafic-to-felsic axis. PC2 (12%) is mostly Al2O3 and Na2O.

The table shrinks from 7 columns to 2

Same 8 rocks

rock PC1 PC2
0 −3.72 −0.41
1 3.14 −0.77
2 −3.05 0.23
3 −3.16 −0.04
4 2.96 0.69
5 −0.24 1.44
6 −2.85 0.27
7 −1.66 0.33

5,000 rocks on PC1 and PC2, without labels, in three groups.

The same 5,000 rocks, 2 numbers each instead of 7, with 91% of the variance kept: the table fits in one picture, and three groups appear.

k-means (K = 3) on PC1 and PC2

k-means clusters on PC1 and PC2 next to the hidden rock types; the panels nearly match. k-means, no labels The hidden rock types

99.0% of the rocks land in the cluster of their own type (99.4% with all 7 oxides): PCA kept the grouping with 2 numbers instead of 7, and made it visible.

A harder case: seismic sources classification

Pacific Northwest seismic events, 61 waveform features (Kharita et al. 2026, Seismica; Zenodo 14025693)

4,000 Pacific Northwest seismic events on PC1 and PC2 colored by analyst label, and the variance kept by the first principal components: 15 of 61 keep 80%. 4,000 seismic events on PC1 and PC2 15 components correspond to 80% of the variance

PC1 keeps only 26% of the variance, and 15 of the 61 axes are needed for 80%. Explosions and surface events still overlap.

Summary: three classic methods

Method Question What it makes small Today’s example
Linear regression How does y depend on x? Σ εi2, the squared errors weight from height; density from 7 oxides
+) Covariance matrix, bootstrap How sure is the fit? (measures the spread) slope 0.77 ± 0.11 kg/cm
k-means Which samples belong together? Σ d2, distances to the centers kinds of eruption pair at Old Faithful
PCA Which directions carry the information? the variance left out 7 oxides to 2 components, 91%

Each method makes one number small: the squared errors, the squared distances to the centers, or the variance left out.

Run the notebook

  1. pixi run jupyter lab → book/Chapter3-MachineLearning/3.3_clustering.ipynb
  2. Part 1: the errors of a guess, the normal equations, the covariance matrix, the bootstrap, seven oxides (Try it 1–5)
  3. Part 2: write the assign step of k-means (Try it 6); change K and the starting centers, watch the paths
  4. PCA on seven oxides, k-means on two components, compare with the hidden rock types (Try it 7–8); then the seismic events

Further study: silhouette score · Voronoi diagrams · ridge and lasso regression