🖥️ 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:
write a straight-line model and name its data, parameters and error;
find the parameters that make the sum of squared errors smallest in three ways: a grid search, one matrix inversion, and small steps downhill;
say how sure you are of the parameters, from the covariance matrix and from the bootstrap;
fit a model with many inputs (rock density from seven oxides) with the same matrix equation ;
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 = 1 to 4;
explain why the choice of is part of the result;
reduce seven oxides to two principal components and cluster rocks without their labels;
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.
# Data handling
import json
import os
from pathlib import Path
import numpy as np
import pandas as pd
# Plotting
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Ellipse
# Machine learning (scikit-learn) and the course's synthetic data
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs # synthetic stand-in if Zenodo cannot be reached
from sklearn.decomposition import PCA
from sklearn.metrics import homogeneity_completeness_v_measure # scores clusters against known labels (section 16)
from sklearn.preprocessing import StandardScaler
from mlgeo_synth import geochem_table # synthetic rock chemistry, the same table as in notebook 3.2The values below are used in several places, so they are defined once.
SEED = 42
H_REF = 170.0 # cm: x = height - H_REF, so beta0 is the weight of a 170 cm person
TRUE_B0, TRUE_B1 = 68.0, 0.8 # the rule used to make the synthetic people: kg at 170 cm, kg per cm
NOISE_KG = 7.0 # scatter of the weights around that rule (kg)
N_PEOPLE = 50
N_BOOT = 1000 # bootstrap resamples
OXIDES = ["SIO2", "AL2O3", "FEO", "MGO", "CAO", "NA2O", "K2O"] # major-element oxides (wt%)
FAITHFUL_URL = "https://raw.githubusercontent.com/UW-MLGEO/MLGeo-dataset/main/data/faithful.csv" # MLGeo dataset repository
SHORT_MIN = 3.0 # minutes: eruptions shorter than this are called short
N_STARTS = 20 # random starts of k-means for each K; the run with the smallest J is kept
K_MAX = 8 # largest number of clusters in the elbow plots
SLIDE_DIR = os.environ.get("MLGEO_SLIDE_FIGS") # set only when the lecture slides are builtFigure 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.
INK, MUTED, ACCENT, ERR = "#26241f", "#6e675c", "#116b66", "#D55E00" # text, secondary, model line, errors
GROUP_COLORS = ["#0072B2", "#E69F00", "#009E73", "#D55E00"]
GROUP_MARKERS = ["o", "s", "^", "D"]
ROCK_COLORS = {"basalt": "#0072B2", "andesite": "#009E73", "granite": "#E69F00"}
ROCK_MARKERS = {"basalt": "o", "andesite": "^", "granite": "s"}
OXIDE_TEX = {"SIO2": "SiO$_2$", "AL2O3": "Al$_2$O$_3$", "FEO": "FeO", "MGO": "MgO", "CAO": "CaO",
"NA2O": "Na$_2$O", "K2O": "K$_2$O"}
plt.rcParams.update({
"font.family": "sans-serif", "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
"mathtext.fontset": "custom", "mathtext.rm": "sans", "mathtext.it": "sans:italic", "mathtext.bf": "sans:bold",
"font.size": 18, "axes.labelsize": 18, "xtick.labelsize": 16, "ytick.labelsize": 16, "legend.fontsize": 16,
"text.color": INK, "axes.labelcolor": INK, "axes.edgecolor": INK, "xtick.color": INK, "ytick.color": INK,
"axes.spines.top": False, "axes.spines.right": False, "axes.grid": False, "axes.linewidth": 1.2,
"figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white",
"figure.constrained_layout.use": True, "figure.dpi": 100, "legend.frameon": False,
"lines.linewidth": 2.5, "lines.markersize": 8,
})
def finish(fig, name):
"""Show a figure; when the slides are built (SLIDE_DIR set), also save it as a 300-dpi PNG."""
if SLIDE_DIR:
fig.savefig(Path(SLIDE_DIR) / f"{name}.png", dpi=300)
boxes = [ax.get_position().bounds for ax in fig.axes] # panel positions, to place the slide labels
(Path(SLIDE_DIR) / f"{name}.json").write_text(json.dumps(boxes))
plt.show()
def show_table(df, name):
"""Return a table for display; when the slides are built, also save it as CSV."""
if SLIDE_DIR:
df.to_csv(Path(SLIDE_DIR) / f"{name}.csv")
return df
def check(name, yours, solution, args=(), rtol=1e-6, summary=None):
"""Compare your answer with the worked solution; keep yours if it matches, otherwise use the solution."""
try:
a, b = (yours(*args), solution(*args)) if callable(solution) else (yours, solution)
if a is None:
print(f"{name}: not filled in yet, so the worked solution is used.")
return solution
if summary is not None:
a, b = summary(a), summary(b)
ok = np.allclose(np.asarray(a, dtype=float), np.asarray(b, dtype=float), rtol=rtol)
except Exception as err:
print(f"{name}: your code raised {type(err).__name__}: {err}")
ok = False
print(f"{name}: " + ("correct." if ok else "differs from the worked solution, which is used from here on."))
return yours if ok else solutionPart 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.
def make_people(n=N_PEOPLE, seed=SEED):
"""Synthetic heights (cm) and weights (kg) of n adults: a known straight-line rule plus scatter."""
rng = np.random.default_rng(seed)
height = rng.normal(H_REF, 9.0, n)
weight = TRUE_B0 + TRUE_B1 * (height - H_REF) + rng.normal(0, NOISE_KG, n)
return pd.DataFrame({"height_cm": height.round(1), "weight_kg": weight.round(1)})
people = make_people()
x = people["height_cm"].to_numpy() - H_REF # input: height above 170 cm
y = people["weight_kg"].to_numpy() # output we want to predict: weight (kg)
people.head()# Helper: the 50 people as a scatter plot.
def plot_people(people):
fig, ax = plt.subplots(figsize=(7.2, 4.5))
ax.plot(people["height_cm"], people["weight_kg"], "o", color=INK, alpha=0.8, label=f"{len(people)} people")
ax.set(xlabel="height (cm)", ylabel="weight (kg)")
ax.legend(loc="upper left")
return fig
finish(plot_people(people), "reg_data")
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¶
Data : what we measured, one pair per person. Here is the height above 170 cm and the weight.
Parameters : what we solve for. is the slope (kg per cm); is the weight of a 170 cm person. (We measure height from 170 cm so that means something: the weight of a person 0 cm tall would not.)
Error : what the line misses for person , .
Below, a first guess of the line, with the error of every person drawn as a vertical segment.
B0_GUESS, B1_GUESS = 65.0, 0.4 # a first guess: kg at 170 cm, kg per cm
def predict(b0, b1, height_cm):
"""Weight (kg) predicted by the line with intercept b0 (kg at 170 cm) and slope b1 (kg per cm)."""
return b0 + b1 * (np.asarray(height_cm) - H_REF)
# Helper: data, one line, and the error of every person as a vertical segment.
def plot_model(people, b0, b1):
fig, ax = plt.subplots(figsize=(7.2, 4.5))
h, w = people["height_cm"].to_numpy(), people["weight_kg"].to_numpy()
ax.vlines(h, predict(b0, b1, h), w, color=ERR, lw=1.8, label=r"error $\varepsilon_i$")
hh = np.array([h.min() - 2, h.max() + 2])
ax.plot(hh, predict(b0, b1, hh), color=ACCENT, label=r"model $\beta_1 x + \beta_0$ (parameters)")
ax.plot(h, w, "o", color=INK, alpha=0.8, label=r"data $(x_i, y_i)$")
ax.set(xlabel="height (cm)", ylabel="weight (kg)")
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], loc="upper left")
return fig
finish(plot_model(people, B0_GUESS, B1_GUESS), "reg_model")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

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.
# --- your code
eps_guess = None # y minus the prediction of the guessed line, one value per person
sse_guess = None # sum of the squared errors (kg^2)
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
eps_guess_sol = y - (B1_GUESS * x + B0_GUESS)
sse_guess_sol = np.sum(eps_guess_sol ** 2)
eps_guess = check("eps_guess", eps_guess, eps_guess_sol)
sse_guess = check("sse_guess", sse_guess, sse_guess_sol)eps_guess: not filled in yet, so the worked solution is used.
sse_guess: not filled in yet, so the worked solution is used.
print(f"guessed line: sum of squared errors {sse_guess:,.0f} kg^2; "
f"typical error (root mean square) {np.sqrt(sse_guess / len(y)):.1f} kg")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,
and look for the that make 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. is called the objective, cost or misfit function.
The figure holds at the mean weight and tries three slopes. as a function of the slope is a bowl, and the best slope is at its bottom.
def sse(b0, b1):
"""Sum of squared errors (kg^2) of the line b1 * x + b0 on the height-weight data."""
return float(np.sum((y - (b1 * x + b0)) ** 2))
# Helper: three candidate lines on the data, and the sum of squared errors as a function of the slope.
def plot_objective(people, b0, slopes):
fig, ax = plt.subplots(1, 2, figsize=(12.0, 4.3))
h, w = people["height_cm"].to_numpy(), people["weight_kg"].to_numpy()
hh = np.array([h.min() - 2, h.max() + 2])
ax[0].plot(h, w, "o", color=INK, alpha=0.8)
b1_curve = np.linspace(-0.4, 2.0, 200)
ax[1].plot(b1_curve, [sse(b0, b) for b in b1_curve], color=MUTED, lw=2)
styles = [("#0072B2", "o"), ("#E69F00", "s"), (ACCENT, "D")]
for (color, marker), b1 in zip(styles, slopes):
ax[0].plot(hh, predict(b0, b1, hh), color=color, label=rf"$\beta_1$ = {b1:.2f} kg/cm")
ax[1].plot(b1, sse(b0, b1), marker, color=color, ms=14, mec="white", mew=1.5)
ax[0].set(xlabel="height (cm)", ylabel="weight (kg)")
ax[0].legend(loc="upper left")
ax[1].set(xlabel=r"slope $\beta_1$ (kg/cm)", ylabel=r"$J$ (kg²)")
ax[1].yaxis.set_major_formatter(lambda v, pos: f"{v:,.0f}")
return fig
b0_mean = y.mean()
b1_curve = np.linspace(-0.4, 2.0, 2001)
b1_bowl = b1_curve[np.argmin([sse(b0_mean, b) for b in b1_curve])]
print(f"with beta0 held at the mean weight ({b0_mean:.1f} kg), the bottom of the bowl is at beta1 = {b1_bowl:.2f} kg/cm")
finish(plot_objective(people, b0_mean, [0.2, 1.4, b1_bowl]), "reg_objective")with beta0 held at the mean weight (67.3 kg), the bottom of the bowl is at beta1 = 0.76 kg/cm

4. Three ways to find the bottom of the bowl¶
With two parameters, is a bowl over the plane of . 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).
B0_GRID = np.arange(55.0, 80.01, 1.0) # kg at 170 cm, steps of 1 kg
B1_GRID = np.arange(-0.2, 1.801, 0.1) # kg per cm, steps of 0.1 kg/cm
def sse_grid(b0_values, b1_values):
"""Sum of squared errors for every combination: rows are b0 values, columns b1 values."""
pred = b0_values[:, None, None] + b1_values[None, :, None] * x[None, None, :]
return ((y - pred) ** 2).sum(axis=2)
J_grid = sse_grid(B0_GRID, B1_GRID)
i_best, j_best = np.unravel_index(J_grid.argmin(), J_grid.shape)
b0_grid, b1_grid = B0_GRID[i_best], B1_GRID[j_best]
print(f"grid search: {J_grid.size} trials; best beta0 = {b0_grid:.1f} kg, beta1 = {b1_grid:.2f} kg/cm")grid search: 546 trials; best beta0 = 67.0 kg, beta1 = 0.80 kg/cm
(b) Matrix inversion. Write the 50 equations as one matrix equation,
The column of ones multiplies , the column of heights multiplies . Setting the slope of to zero gives the normal equations , whose solution is
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 . In NumPy, A @ B is the matrix product, A.T the transpose and np.linalg.inv(A) the inverse.
X = np.column_stack([np.ones_like(x), x]) # 50 x 2: a column of ones (for beta0) and the heights (for beta1)
print("first rows of X:\n", X[:3].round(1))
# --- your code
beta_hat = None # (X^T X)^-1 X^T y
# --- endfirst rows of X:
[[ 1. 2.7]
[ 1. -9.4]
[ 1. 6.8]]
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
beta_hat_sol = np.linalg.inv(X.T @ X) @ (X.T @ y) # np.linalg.solve(X.T @ X, X.T @ y) is the more accurate spelling
beta_hat = check("beta_hat", beta_hat, beta_hat_sol)beta_hat: not filled in yet, so the worked solution is used.
(c) Iterative: walk downhill. Start anywhere, compute which way 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.
def gradient_descent(b0, b1, step=0.005, n_steps=600):
"""Walk downhill on the mean squared error from (b0, b1); returns the path, one (b0, b1) row per step."""
path = [(b0, b1)]
for _ in range(n_steps):
eps = y - (b1 * x + b0)
b0 += step * 2 * eps.mean() # minus the slope of the mean squared error along b0
b1 += step * 2 * (eps * x).mean() # minus the slope along b1
path.append((b0, b1))
return np.array(path)
path_gd = gradient_descent(b0=57.0, b1=1.6)
show_table(pd.DataFrame({"beta0 (kg at 170 cm)": [b0_grid, beta_hat[0], path_gd[-1, 0]],
"beta1 (kg/cm)": [b1_grid, beta_hat[1], path_gd[-1, 1]],
"J (kg^2)": [sse(b0_grid, b1_grid), sse(*beta_hat), sse(*path_gd[-1])],
"evaluations of J": [J_grid.size, 1, len(path_gd)]},
index=["grid search", "matrix inversion", "gradient descent"]).round(3), "reg_methods")# Helper: the three methods on the contours of J in the plane of the parameters.
def plot_optimizers(b0_grid, b1_grid, beta_hat, path):
fig, ax = plt.subplots(1, 3, figsize=(12.0, 4.0), sharex=True, sharey=True)
b0s, b1s = np.linspace(53, 82, 200), np.linspace(-0.35, 1.95, 200)
J = sse_grid(b0s, b1s)
levels = J.min() * np.array([1.05, 1.2, 1.5, 2, 3, 5, 8])
for a in ax:
a.contour(b1s, b0s, J, levels=levels, colors=MUTED, linewidths=1.0)
a.set_xlabel(r"slope $\beta_1$ (kg/cm)")
gb1, gb0 = np.meshgrid(B1_GRID, B0_GRID)
ax[0].plot(gb1, gb0, ".", color=MUTED, ms=3)
ax[0].plot(b1_grid, b0_grid, "s", color="#E69F00", ms=13, mec=INK, label="best grid point")
ax[1].plot(*beta_hat[::-1], "*", color=ACCENT, ms=22, mec=INK, label="exact minimum")
ax[2].plot(path[:, 1], path[:, 0], "-", color=ACCENT, lw=2)
ax[2].plot(path[:60:3, 1], path[:60:3, 0], "o", color=ACCENT, ms=5)
ax[2].plot(path[0, 1], path[0, 0], "o", color="white", mec=ACCENT, mew=2.5, ms=12, label="start")
ax[2].plot(path[-1, 1], path[-1, 0], "*", color=ACCENT, ms=22, mec=INK, label=f"after {len(path) - 1} steps")
ax[0].set_ylabel(r"intercept $\beta_0$ (kg at 170 cm)")
for a in ax:
a.legend(loc="upper left", handletextpad=0.3, borderaxespad=0.2, frameon=True, facecolor="white",
edgecolor="none", framealpha=0.95)
return fig
finish(plot_optimizers(b0_grid, b1_grid, beta_hat, path_gd), "reg_optimizers")
The gray curves are contours of , 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.
eps_hat = y - X @ beta_hat # error of every person for the best line (kg)
rms = np.sqrt(np.mean(eps_hat ** 2))
print(f"best line: weight = {beta_hat[0]:.1f} kg + {beta_hat[1]:.2f} kg/cm x (height - 170 cm); "
f"typical error {rms:.1f} kg (the rule that made the data: {TRUE_B0} kg + {TRUE_B1} kg/cm, scatter {NOISE_KG} kg)")
# Helper: the best line on the data, and the errors against height.
def plot_fit(people, beta_hat, eps_hat):
fig, ax = plt.subplots(1, 2, figsize=(12.0, 4.5))
h, w = people["height_cm"].to_numpy(), people["weight_kg"].to_numpy()
hh = np.array([h.min() - 2, h.max() + 2])
ax[0].plot(h, w, "o", color=INK, alpha=0.8, label="data")
ax[0].plot(hh, predict(*beta_hat, hh), color=ACCENT,
label=rf"{beta_hat[0]:.1f} kg + {beta_hat[1]:.2f} kg/cm $\times$ (height $-$ 170 cm)")
ax[0].set(xlabel="height (cm)", ylabel="weight (kg)")
ax[0].legend(loc="upper left", fontsize=15)
ax[1].axhline(0, color=ACCENT, lw=2)
ax[1].vlines(h, 0, eps_hat, color=ERR, lw=1.5)
ax[1].plot(h, eps_hat, "o", color=ERR, label=r"error $\varepsilon_i$")
ax[1].set(xlabel="height (cm)", ylabel="error (kg)")
ax[1].legend(loc="upper left")
return fig
finish(plot_fit(people, beta_hat, eps_hat), "reg_fit")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)

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 , the parameters have the covariance matrix
The diagonal holds the variance of each parameter, so and 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. ( because two parameters were fitted.)
Try it 3: the covariance matrix. Compute cov_beta, the 2 x 2 matrix .
n, p = X.shape
sigma2 = np.sum(eps_hat ** 2) / (n - p) # variance of the errors (kg^2), given
# --- your code
cov_beta = None # sigma2 times the inverse of X^T X
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
cov_beta_sol = sigma2 * np.linalg.inv(X.T @ X)
cov_beta = check("cov_beta", cov_beta, cov_beta_sol)cov_beta: not filled in yet, so the worked solution is used.
se_beta = np.sqrt(np.diag(cov_beta))
print(f"sigma = {np.sqrt(sigma2):.2f} kg (spread of the errors, from n - 2 = {n - p})")
print("covariance matrix C:\n", cov_beta.round(4))
print(f"beta0 = {beta_hat[0]:.1f} +/- {se_beta[0]:.1f} kg; beta1 = {beta_hat[1]:.2f} +/- {se_beta[1]:.2f} kg/cm (one standard error)")
print(f"about 95% confidence interval for beta1 (two standard errors): "
f"{beta_hat[1] - 2 * se_beta[1]:.2f} to {beta_hat[1] + 2 * se_beta[1]:.2f} kg/cm")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
def ellipse(center, cov, n_sd, **kw):
"""Ellipse of n_sd standard deviations of a 2-D covariance matrix, as a matplotlib patch."""
vals, vecs = np.linalg.eigh(cov)
angle = np.degrees(np.arctan2(vecs[1, -1], vecs[0, -1]))
return Ellipse(center, 2 * n_sd * np.sqrt(vals[-1]), 2 * n_sd * np.sqrt(vals[0]), angle=angle, fill=False, **kw)
def param_plane(ax, beta_hat, cov):
"""The estimate and its 1 and 2 standard-error ellipses in the (beta1, beta0) plane."""
cov_xy = cov[::-1, ::-1] # beta1 on the horizontal axis, beta0 on the vertical
for n_sd, ls in [(1, "-"), (2, "--")]:
ax.add_patch(ellipse(beta_hat[::-1], cov_xy, n_sd, color=ACCENT, lw=2.5, ls=ls))
ax.plot(*beta_hat[::-1], "o", color=ACCENT, ms=9)
ax.set(xlabel=r"$\beta_1$ (kg/cm)", ylabel=r"$\beta_0$ (kg at 170 cm)", xlim=(0.38, 1.17), ylim=(64.0, 69.6))
ax.xaxis.set_major_locator(plt.MaxNLocator(4))
# Helper: the band of lines allowed by C on the data, and C as ellipses in the plane of the parameters.
def plot_covariance(people, beta_hat, cov):
fig, ax = plt.subplots(1, 2, figsize=(7.4, 4.5))
h, w = people["height_cm"].to_numpy(), people["weight_kg"].to_numpy()
hh = np.linspace(h.min() - 2, h.max() + 2, 100)
A = np.column_stack([np.ones_like(hh), hh - H_REF])
sd = np.sqrt(np.einsum("ij,jk,ik->i", A, cov, A)) # standard error of the line at each height
ax[0].plot(h, w, "o", color=INK, alpha=0.5, ms=6)
ax[0].fill_between(hh, A @ beta_hat - 2 * sd, A @ beta_hat + 2 * sd, color=ACCENT, alpha=0.25, lw=0)
ax[0].plot(hh, A @ beta_hat, color=ACCENT)
ax[0].set(xlabel="height (cm)", ylabel="weight (kg)")
param_plane(ax[1], beta_hat, cov)
handles = [Line2D([], [], color=ACCENT, lw=2.5, label="1 standard error"),
Line2D([], [], color=ACCENT, lw=2.5, ls="--", label="2 standard errors")]
fig.legend(handles=handles, loc="outside lower center", ncol=2, fontsize=14, handlelength=1.5, columnspacing=1)
return fig
finish(plot_covariance(people, beta_hat, cov_beta), "reg_covariance")
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_example = np.sort(np.random.default_rng(1).integers(0, n, n)) # n row numbers, drawn with replacement
print("rows in one resample:", rows_example)
print(f"{len(np.unique(rows_example))} different people of {n}; the others are left out, and some are drawn twice or more")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.
rng = np.random.default_rng(SEED)
# --- your code
boot = None # (N_BOOT, 2) array: beta_hat of each resample
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
rng_sol = np.random.default_rng(SEED)
boot_sol = np.empty((N_BOOT, 2))
for b in range(N_BOOT):
rows = rng_sol.integers(0, n, n) # n people drawn with replacement
Xb, yb = X[rows], y[rows]
boot_sol[b] = np.linalg.inv(Xb.T @ Xb) @ (Xb.T @ yb)
boot = check("boot (its spread)", boot, boot_sol, rtol=0.15, summary=lambda bt: bt.std(axis=0))boot (its spread): not filled in yet, so the worked solution is used.
se_boot = boot.std(axis=0)
print(f"standard error of beta0: covariance matrix {se_beta[0]:.2f} kg, bootstrap {se_boot[0]:.2f} kg")
print(f"standard error of beta1: covariance matrix {se_beta[1]:.3f} kg/cm, bootstrap {se_boot[1]:.3f} kg/cm")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
# Helper: bootstrap lines on the data, and bootstrap estimates against the ellipses of C.
def plot_bootstrap(people, beta_hat, cov, boot, n_lines=200):
fig, ax = plt.subplots(1, 2, figsize=(7.4, 4.5))
h, w = people["height_cm"].to_numpy(), people["weight_kg"].to_numpy()
hh = np.array([h.min() - 2, h.max() + 2])
for b0, b1 in boot[:n_lines]:
ax[0].plot(hh, predict(b0, b1, hh), color=ACCENT, lw=1, alpha=0.08)
ax[0].plot(h, w, "o", color=INK, alpha=0.5, ms=6)
ax[0].set(xlabel="height (cm)", ylabel="weight (kg)")
ax[1].plot(boot[:, 1], boot[:, 0], ".", color=MUTED, ms=3, alpha=0.5, zorder=0)
param_plane(ax[1], beta_hat, cov)
handles = [Line2D([], [], color=MUTED, marker=".", ms=10, ls="", label=f"{len(boot):,} resamples"),
Line2D([], [], color=ACCENT, lw=2.5, label="covariance matrix")]
fig.legend(handles=handles, loc="outside lower center", ncol=2, fontsize=14, handlelength=1.5, columnspacing=1)
return fig
finish(plot_bootstrap(people, beta_hat, cov_beta, boot), "reg_bootstrap")
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,
so now has 8 columns (ones and 7 oxides) and 5,000 rows, and still gives the answer in one step.
rocks = geochem_table(n=5000, seed=SEED)
y_rock = rocks["density_g_cm3"].to_numpy()
print(rocks["label"].value_counts().to_string())
rocks[OXIDES + ["density_g_cm3", "label"]].head().round(2)label
granite 2794
basalt 1713
andesite 493
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).
# --- your code
X_rock = None # 5000 x 8: ones, then the 7 oxides
beta_rock = None # the 8 coefficients
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
X_rock_sol = np.column_stack([np.ones(len(rocks)), rocks[OXIDES].to_numpy()])
beta_rock_sol = np.linalg.inv(X_rock_sol.T @ X_rock_sol) @ (X_rock_sol.T @ y_rock)
X_rock = check("X_rock", X_rock, X_rock_sol)
beta_rock = check("beta_rock", beta_rock, beta_rock_sol, rtol=1e-4)X_rock: not filled in yet, so the worked solution is used.
beta_rock: not filled in yet, so the worked solution is used.
eps_rock = y_rock - X_rock @ beta_rock
cov_rock = np.sum(eps_rock ** 2) / (len(y_rock) - X_rock.shape[1]) * np.linalg.inv(X_rock.T @ X_rock)
coef = pd.DataFrame({"coefficient": beta_rock, "standard error": np.sqrt(np.diag(cov_rock))},
index=["intercept (g/cm3)"] + [f"{ox} (g/cm3 per wt%)" for ox in OXIDES])
coef.round(4)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.
X_sio2 = np.column_stack([np.ones(len(rocks)), rocks["SIO2"]])
beta_sio2 = np.linalg.inv(X_sio2.T @ X_sio2) @ (X_sio2.T @ y_rock)
mae = {"mean density only": np.mean(np.abs(y_rock - y_rock.mean())),
"SiO2 only": np.mean(np.abs(y_rock - X_sio2 @ beta_sio2)),
"all 7 oxides": np.mean(np.abs(eps_rock))}
show_table(pd.Series(mae, name="MAE (g/cm3)").round(4).to_frame(), "rock_mae")# Helper: density against SiO2 by rock type, and predicted against measured density.
def plot_rock_regression(rocks, beta_sio2, pred):
fig, ax = plt.subplots(1, 2, figsize=(12.0, 4.5))
for rock in ["basalt", "andesite", "granite"]:
sel = (rocks["label"] == rock).to_numpy()
kw = dict(s=10, alpha=0.35, color=ROCK_COLORS[rock], marker=ROCK_MARKERS[rock], lw=0)
ax[0].scatter(rocks.loc[sel, "SIO2"], rocks.loc[sel, "density_g_cm3"], label=rock, **kw)
ax[1].scatter(rocks.loc[sel, "density_g_cm3"], pred[sel], **kw)
s = np.array([42, 80])
ax[0].plot(s, beta_sio2[0] + beta_sio2[1] * s, color=INK, lw=2, label="fit on SiO$_2$ only")
lim = np.array([2.5, 3.1])
ax[1].plot(lim, lim, color=INK, lw=2, label="predicted = measured")
ax[0].set(xlabel="SiO$_2$ (wt%)", ylabel="density (g/cm³)")
ax[1].set(xlabel="measured density (g/cm³)", ylabel="predicted from 7 oxides", xlim=lim, ylim=lim)
leg = ax[0].legend(loc="upper right", markerscale=2.5)
for handle in leg.legend_handles:
handle.set_alpha(1)
ax[1].legend(loc="upper left")
return fig
finish(plot_rock_regression(rocks, beta_sio2, X_rock @ beta_rock), "rock_regression")
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.
def synthetic_faithful(n=272, seed=SEED):
"""Synthetic two-regime geyser (short eruptions are followed by long ones), used only if the download fails."""
rng = np.random.default_rng(seed)
state = [1]
for _ in range(n - 1):
state.append(int(rng.uniform() < (0.94 if state[-1] == 0 else 0.48)))
state = np.array(state)
dur = np.where(state == 1, rng.normal(4.3, 0.4, n), rng.normal(2.0, 0.25, n))
return pd.DataFrame({"current": dur[:-1].round(3), "next": dur[1:].round(3)})
def load_faithful():
"""Old Faithful: duration of each eruption and of the next one (min), one row per pair."""
try:
df = pd.read_csv(FAITHFUL_URL)
print(f"Old Faithful: {len(df)} pairs of consecutive eruptions")
except Exception as err:
print(f"FALLBACK: the Old Faithful table could not be downloaded ({type(err).__name__}). "
"Using a synthetic geyser; its numbers are NOT Old Faithful.")
df = synthetic_faithful()
return df[["current", "next"]].rename(columns={"current": "current_min", "next": "next_min"})
faithful = load_faithful()
faithful.describe().round(1)Old Faithful: 271 pairs of consecutive eruptions
# Helper: the eruptions as a scatter plot.
def plot_faithful(faithful):
fig, ax = plt.subplots(figsize=(7.2, 4.5))
ax.plot(faithful["current_min"], faithful["next_min"], "o", color=INK, alpha=0.6, ms=7,
label=f"{len(faithful)} pairs of consecutive eruptions")
ax.set(xlabel="eruption duration (min)", ylabel="next eruption duration (min)", xticks=[2, 3, 4, 5],
yticks=[2, 3, 4, 5], ylim=(1.3, 6.0))
ax.legend(loc="upper left")
return fig
finish(plot_faithful(faithful), "faithful_data")
def regime(minutes):
"""'short' or 'long' for each eruption duration."""
return np.where(minutes < SHORT_MIN, "short", "long")
print("median duration (min):", faithful["current_min"].groupby(regime(faithful["current_min"])).median().round(1).to_dict())
pd.crosstab(regime(faithful["current_min"]), regime(faithful["next_min"]), rownames=["eruption"],
colnames=["next eruption"])
median duration (min): {'long': 4.3, 'short': 2.0}
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 and a center :
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 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, , so the loop always stops.
scaler_faith = StandardScaler().fit(faithful)
Z_faith = scaler_faith.transform(faithful) # standardized: mean 0, standard deviation 1 in both columnsTry 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).
# --- your code
def nearest_center(Z, centers):
"""Index of the nearest center (Euclidean distance) for each sample."""
return None # replace with your code
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
def nearest_center_sol(Z, centers):
d = np.sqrt(((Z[:, None, :] - centers[None, :, :]) ** 2).sum(axis=2)) # (n, K) distances
return d.argmin(axis=1)
nearest_center = check("nearest_center", nearest_center, nearest_center_sol, args=(Z_faith, Z_faith[:3]))nearest_center: not filled in yet, so the worked solution is used.
The update step and the loop are given.
def move_centers(Z, labels, centers):
"""Move each center to the mean of its samples (a center left without samples stays where it is)."""
return np.array([Z[labels == j].mean(axis=0) if np.any(labels == j) else centers[j]
for j in range(len(centers))])
def kmeans_loop(Z, centers, max_iter=50):
"""Assign and update until no center moves; returns the centers after each update and the final groups."""
history = [centers]
for _ in range(max_iter):
labels = nearest_center(Z, centers)
new = move_centers(Z, labels, centers)
if np.allclose(new, centers):
break
centers = new
history.append(centers)
return np.array(history), labels
# 3 centers placed by hand in a row along the bottom (listed so that the colors match the K = 3 panels below)
START_K3 = scaler_faith.transform(pd.DataFrame([[2.0, 2.0], [4.4, 2.0], [3.2, 2.0]], columns=faithful.columns))
history_k3, labels_k3 = kmeans_loop(Z_faith, START_K3)
print(f"K = 3: converged after {len(history_k3) - 1} updates; groups of {np.bincount(labels_k3)} pairs")K = 3: converged after 5 updates; groups of [93 97 81] pairs
def to_minutes(Z):
"""Standardized Old Faithful coordinates back to minutes."""
return scaler_faith.inverse_transform(Z)
def draw_groups(ax, pts, labels, ms=6, alpha=0.7):
"""Samples colored and shaped by group."""
for j in np.unique(labels):
ax.plot(*pts[labels == j].T, GROUP_MARKERS[j], color=GROUP_COLORS[j], ms=ms, alpha=alpha, mec="none")
def draw_centers(ax, centers_min, hollow=False):
"""Centers as large crosses in the color of their group (hollow circles for earlier positions)."""
for j, c in enumerate(centers_min):
if hollow:
ax.plot(*c, "o", color="white", mec=GROUP_COLORS[j], mew=2.5, ms=13, zorder=5)
else:
ax.plot(*c, "X", color=GROUP_COLORS[j], mec=INK, mew=1.5, ms=18, zorder=6)
def draw_paths(ax, history):
"""The track of every center through the iterations, from a hollow start to a cross."""
for j in range(history.shape[1]):
track = to_minutes(history[:, j])
ax.plot(*track.T, "-", color=INK, lw=1.8, zorder=4)
ax.plot(*track[:-1].T, ".", color=INK, ms=7, zorder=4)
draw_centers(ax, to_minutes(history[0]), hollow=True)
draw_centers(ax, to_minutes(history[-1]))
# Helper: the k-means loop for K = 3 in four panels: start, assign, update, converged.
def plot_kmeans_steps(faithful, history, labels_final):
fig, ax = plt.subplots(1, 4, figsize=(12.0, 3.7), sharex=True, sharey=True)
pts = faithful.to_numpy()
first = nearest_center(Z_faith, history[0])
ax[0].plot(*pts.T, "o", color=MUTED, ms=6, alpha=0.5, mec="none")
draw_centers(ax[0], to_minutes(history[0]))
draw_groups(ax[1], pts, first)
draw_centers(ax[1], to_minutes(history[0]))
draw_groups(ax[2], pts, first)
draw_centers(ax[2], to_minutes(history[0]), hollow=True)
for c0, c1 in zip(to_minutes(history[0]), to_minutes(history[1])):
ax[2].annotate("", c1, c0, arrowprops=dict(arrowstyle="-|>", color=INK, lw=2, mutation_scale=22), zorder=4)
draw_centers(ax[2], to_minutes(history[1]))
draw_groups(ax[3], pts, labels_final)
draw_paths(ax[3], history)
for a in ax:
a.set(xlabel="duration (min)", xticks=[2, 3, 4, 5], yticks=[2, 3, 4, 5])
ax[0].set_ylabel("next duration (min)")
return fig
finish(plot_kmeans_steps(faithful, history_k3, labels_k3), "kmeans_steps")
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 = 1 to 4. A bad start can stop the loop at a poor solution, so for each we start it N_STARTS times from pairs drawn at random and keep the run with the smallest . The lines track every center of that run from its start (hollow circle) to its final position (cross).
def inertia(Z, labels, centers):
"""J: the sum of squared distances from each sample to the center of its group."""
return float(((Z - centers[labels]) ** 2).sum())
runs = {}
for k in range(1, 5):
rng = np.random.default_rng(SEED + k)
trials = [kmeans_loop(Z_faith, Z_faith[rng.choice(len(Z_faith), k, replace=False)]) for _ in range(N_STARTS)]
J_trials = [inertia(Z_faith, labels, history[-1]) for history, labels in trials]
runs[k] = trials[int(np.argmin(J_trials))]
print(f"K = {k}: J from {min(J_trials):.1f} (best start) to {max(J_trials):.1f} (worst start); "
f"best run {len(runs[k][0]) - 1} updates, group sizes {np.bincount(runs[k][1])}")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]
# Helper: final groups and center tracks for each K.
def plot_kmeans_paths(faithful, runs):
fig, ax = plt.subplots(1, len(runs), figsize=(12.0, 4.0), sharex=True, sharey=True)
pts = faithful.to_numpy()
for a, (k, (history, labels)) in zip(ax, runs.items()):
draw_groups(a, pts, labels, alpha=0.5)
draw_paths(a, history)
a.set(xlabel="duration (min)", xticks=[2, 3, 4, 5], yticks=[2, 3, 4, 5])
ax[0].set_ylabel("next duration (min)")
return fig
finish(plot_kmeans_paths(faithful, runs), "kmeans_paths")
With the centers settle on the three common kinds of pair; with the fourth center finds the 6 rare short-then-short pairs. k-means returns groups for any 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).
# Helper: the region owned by each center, with the eruptions and the centers.
def plot_kmeans_regions(faithful, runs):
fig, ax = plt.subplots(1, len(runs), figsize=(12.0, 4.0), sharex=True, sharey=True)
pts = faithful.to_numpy()
cur, nxt = np.meshgrid(np.linspace(1.3, 5.4, 400), np.linspace(1.3, 5.4, 400))
grid = scaler_faith.transform(pd.DataFrame({"current_min": cur.ravel(), "next_min": nxt.ravel()}))
for a, (k, (history, labels)) in zip(ax, runs.items()):
owner = nearest_center(grid, history[-1]).reshape(cur.shape)
a.contourf(cur, nxt, owner, levels=np.arange(-0.5, k), colors=GROUP_COLORS[:k], alpha=0.18)
if k > 1:
a.contour(cur, nxt, owner, levels=np.arange(0.5, k - 0.5), colors=INK, linewidths=1.5)
draw_groups(a, pts, labels, ms=5, alpha=0.8)
draw_centers(a, to_minutes(history[-1]))
a.set(xlabel="duration (min)", xticks=[2, 3, 4, 5], yticks=[2, 3, 4, 5])
ax[0].set_ylabel("next duration (min)")
return fig
finish(plot_kmeans_regions(faithful, runs), "kmeans_regions")
10. Choosing K: the elbow¶
k-means needs before it starts. A common guide is the elbow of the curve of (the total squared distance to the centers) against . always decreases as grows (with one center per sample, ), so we look for the 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.
scaler_rock = StandardScaler().fit(rocks[OXIDES])
Z_rock = scaler_rock.transform(rocks[OXIDES]) # the 7 oxides, standardized
def inertia_curve(Z, k_max=K_MAX):
"""J of the best of 10 k-means runs for K = 1 to k_max."""
return np.array([KMeans(n_clusters=k, n_init=10, random_state=SEED).fit(Z).inertia_ for k in range(1, k_max + 1)])
J_faith, J_rock = inertia_curve(Z_faith), inertia_curve(Z_rock)
show_table(pd.DataFrame({"Old Faithful": J_faith / J_faith[0], "rocks (7 oxides)": J_rock / J_rock[0]},
index=pd.Index(range(1, K_MAX + 1), name="K")).round(3), "elbow")# Helper: J against K, as a fraction of J at K = 1.
def plot_elbow(J):
fig, ax = plt.subplots(figsize=(7.2, 4.1))
k = np.arange(1, len(J) + 1)
ax.plot(k, J / J[0], "-o", color=INK, ms=10, mfc=ACCENT, mec=INK)
ax.set(xlabel="number of clusters K", ylabel="J (fraction of K = 1)", xticks=k, ylim=(0, 1.05))
return fig
finish(plot_elbow(J_faith), "elbow_faithful")
For Old Faithful the curve bends at or 4. There are four kinds of pair, but the short-then-short pairs are only 6 of 271, too few to lower much. For the rocks, the biggest drop is at , 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.
show_table(rocks[OXIDES].head(8).round(1).rename_axis("rock"), "rock_table")# Helper: every pair of oxides as a small scatter plot.
def plot_pairs(rocks):
m = len(OXIDES) - 1
fig, ax = plt.subplots(m, m, figsize=(5.6, 4.6), sharex="col", sharey="row")
for r in range(m):
for c in range(m):
a = ax[r, c]
a.set_xticks([])
a.set_yticks([])
if c > r:
a.set_visible(False)
continue
a.plot(rocks[OXIDES[c]], rocks[OXIDES[r + 1]], ",", color=INK, alpha=0.3)
for side in a.spines.values():
side.set(visible=True, color="#cfcac0", linewidth=0.8)
if r == m - 1:
a.set_xlabel(OXIDE_TEX[OXIDES[c]], fontsize=13, rotation=45)
if c == 0:
a.set_ylabel(OXIDE_TEX[OXIDES[r + 1]], fontsize=13, rotation=0, ha="right", va="center")
fig.get_layout_engine().set(w_pad=0.01, h_pad=0.01, wspace=0.02, hspace=0.02)
return fig
finish(plot_pairs(rocks), "rock_pairs")
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 and measures it,
and the correlation matrix holds for every pair of oxides. A correlation 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.
corr_rock = rocks[OXIDES].corr()
corr_rock.round(2)# Helper: the correlation matrix, and two strongly correlated pairs.
def plot_redundancy(rocks, corr, pairs):
fig = plt.figure(figsize=(12.0, 4.5))
gs = fig.add_gridspec(1, 3, width_ratios=[1.35, 1, 1])
a = fig.add_subplot(gs[0])
im = a.imshow(corr.to_numpy(), cmap="RdBu_r", vmin=-1, vmax=1)
labels = [OXIDE_TEX[o] for o in OXIDES]
a.set_xticks(range(len(OXIDES)), labels, rotation=90, fontsize=14)
a.set_yticks(range(len(OXIDES)), labels, fontsize=14)
for i in range(len(OXIDES)):
for j in range(len(OXIDES)):
r = corr.iloc[i, j]
a.text(j, i, f"{r:.2f}".replace("-", "\u2212"), ha="center", va="center", fontsize=11,
color="white" if abs(r) > 0.6 else INK)
for side in a.spines.values():
side.set_visible(False)
fig.colorbar(im, ax=a, shrink=0.85, label="r", ticks=[-1, 0, 1])
for k, (u, v) in enumerate(pairs):
b = fig.add_subplot(gs[k + 1])
b.plot(rocks[u], rocks[v], "o", color=INK, ms=2, alpha=0.2, mec="none")
b.plot([], [], " ", label=f"r = {corr.loc[u, v]:.2f}".replace("-", "\u2212"))
b.set(xlabel=f"{OXIDE_TEX[u]} (wt%)", ylabel=f"{OXIDE_TEX[v]} (wt%)")
b.xaxis.set_major_locator(plt.MaxNLocator(4))
b.legend(loc="upper left" if corr.loc[u, v] > 0 else "upper right", handlelength=0, handletextpad=0)
fig.get_layout_engine().set(wspace=0.06)
return fig
finish(plot_redundancy(rocks, corr_rock, [("FEO", "MGO"), ("SIO2", "FEO")]), "rock_redundancy")
print("SiO2 and Al2O3, for comparison: r =", round(corr_rock.loc["SIO2", "AL2O3"], 2))
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,
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, . 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.
PCA_TRIO = ["SIO2", "AL2O3", "FEO"]
Z_trio = StandardScaler().fit_transform(rocks[PCA_TRIO])
pca_trio = PCA().fit(Z_trio)
trio = pd.DataFrame(pca_trio.components_, index=["PC1", "PC2", "PC3"], columns=PCA_TRIO) # the weights w
trio["variance (%)"] = 100 * pca_trio.explained_variance_ratio_
show_table(trio.round(2), "pca3_weights")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:
scores_trio = pca_trio.transform(Z_trio) # coordinates of every rock on PC1, PC2, PC3
total_var = Z_trio.var(axis=0).sum() # total variance of the cloud: 3 for three standardized columns
var_kept = pd.Series(100 * np.r_[Z_trio.var(axis=0), scores_trio[:, 0].var()] / total_var,
index=PCA_TRIO + ["PC1"], name="variance kept by this one axis (%)")
var_kept.round(1)SIO2 33.3
AL2O3 33.3
FEO 33.3
PC1 79.2
Name: variance kept by this one axis (%), dtype: float64PC_COLORS = [ACCENT, ERR] # PC1, PC2
def cloud_3d(ax, Z):
"""The standardized SiO2, Al2O3, FeO of every rock as a 3-D point cloud."""
ax.scatter(*Z.T, s=2, color=INK, alpha=0.12, depthshade=False)
for setter, ox in zip([ax.set_xlabel, ax.set_ylabel, ax.set_zlabel], PCA_TRIO):
setter(OXIDE_TEX[ox], labelpad=6)
ax.set(xticks=[-2, 0, 2], yticks=[-2, 0, 2], zticks=[-2, 0, 2])
ax.tick_params(labelsize=13, pad=1)
ax.view_init(elev=18, azim=-58)
ax.set_box_aspect(None, zoom=1.12)
def draw_axes_3d(ax, pca, which, scale=2.0):
"""Principal axes as arrows through the center of the cloud, scale standard deviations long each way."""
for j in which:
v = pca.components_[j] * scale * np.sqrt(pca.explained_variance_[j])
ax.quiver(*-v, *(2 * v), color=PC_COLORS[j], lw=3.5, arrow_length_ratio=0.15)
def pc_handles(pca, which):
return [Line2D([], [], color=PC_COLORS[j], lw=3.5,
label=f"PC{j + 1}: {100 * pca.explained_variance_ratio_[j]:.0f}% of the variance") for j in which]
# Helper: the 3-D cloud with PC1, and the variance kept by each single axis.
def plot_pca_axis(Z, pca, var_kept):
fig = plt.figure(figsize=(12.0, 4.4))
gs = fig.add_gridspec(1, 2, width_ratios=[1.2, 1])
fig.get_layout_engine().set(wspace=0.12) # room for the 3-D axis labels
ax = fig.add_subplot(gs[0], projection="3d")
cloud_3d(ax, Z)
draw_axes_3d(ax, pca, [0])
ax.legend(handles=pc_handles(pca, [0]), loc="upper left", fontsize=15)
b = fig.add_subplot(gs[1])
b.barh(range(len(var_kept)), var_kept.values, height=0.6, color=[MUTED] * (len(var_kept) - 1) + [ACCENT])
b.set_yticks(range(len(var_kept)), [OXIDE_TEX.get(n, n) for n in var_kept.index])
b.invert_yaxis()
b.set(xlabel="variance kept by this one axis (%)", xlim=(0, 100))
return fig
finish(plot_pca_axis(Z_trio, pca_trio, var_kept), "pca3_axis")
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.
# Helper: the 3-D cloud with the plane of PC1 and PC2, and the rocks projected onto that plane.
def plot_pca_plane(Z, pca):
fig = plt.figure(figsize=(12.0, 4.4))
gs = fig.add_gridspec(1, 2, width_ratios=[1.2, 1])
fig.get_layout_engine().set(wspace=0.12) # room for the 3-D axis labels
ax = fig.add_subplot(gs[0], projection="3d")
cloud_3d(ax, Z)
scores = pca.transform(Z)
s, t = np.meshgrid(np.percentile(scores[:, 0], [0.5, 99.5]), np.percentile(scores[:, 1], [0.5, 99.5]))
plane = s[..., None] * pca.components_[0] + t[..., None] * pca.components_[1]
ax.plot_surface(*np.moveaxis(plane, -1, 0), color=ACCENT, alpha=0.15, lw=0)
draw_axes_3d(ax, pca, [0, 1])
ax.legend(handles=pc_handles(pca, [0, 1]), loc="upper left", fontsize=15)
b = fig.add_subplot(gs[1])
b.plot(*scores[:, :2].T, "o", color=INK, ms=2, alpha=0.2, mec="none")
for j in range(2):
v = 2.0 * np.sqrt(pca.explained_variance_[j]) * np.eye(2)[j]
b.annotate("", v, -v, arrowprops=dict(arrowstyle="-|>", color=PC_COLORS[j], lw=3.5, mutation_scale=26))
b.set(xlabel="PC1", ylabel="PC2", aspect="equal", xlim=(-4, 4), ylim=(-2.6, 3.0))
return fig
finish(plot_pca_plane(Z_trio, pca_trio), "pca3_plane")
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).
# --- your code
pca = None # PCA fitted on Z_rock
scores = None # (5000, 2): PC1 and PC2 of every rock
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
pca_sol = PCA().fit(Z_rock)
scores_sol = pca_sol.transform(Z_rock)[:, :2]
pca = check("pca", pca, pca_sol, summary=lambda m: m.explained_variance_ratio_)
scores = check("scores", scores, scores_sol)pca: not filled in yet, so the worked solution is used.
scores: not filled in yet, so the worked solution is used.
var_pct = 100 * pca.explained_variance_ratio_
print("variance explained by each component (%):", var_pct.round(1))
print(f"PC1 and PC2 together: {var_pct[:2].sum():.1f}%")
loadings = pd.DataFrame(pca.components_[:2].T, index=OXIDES, columns=["PC1", "PC2"])
loadings.round(2)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%
# Helper: variance explained by each component, and the weights (loadings) of the oxides in PC1 and PC2.
def plot_pca_variance(pca):
fig, ax = plt.subplots(1, 2, figsize=(12.0, 4.1))
pct = 100 * pca.explained_variance_ratio_
k = np.arange(1, len(pct) + 1)
ax[0].bar(k, pct, color=ACCENT, width=0.7, label="each component")
ax[0].plot(k, np.cumsum(pct), "-o", color=INK, ms=8, label="cumulative")
ax[0].set(xlabel="principal component", ylabel="variance explained (%)", xticks=k, ylim=(0, 105))
ax[0].legend(loc="center right")
pos = np.arange(len(OXIDES))
for j, (color, dy) in enumerate([(ACCENT, -0.2), ("#E69F00", 0.2)]):
ax[1].barh(pos + dy, pca.components_[j], height=0.38, color=color, label=f"PC{j + 1}")
ax[1].axvline(0, color=INK, lw=1)
ax[1].set_yticks(pos, [OXIDE_TEX[o] for o in OXIDES])
ax[1].invert_yaxis()
ax[1].set(xlabel="weight in the component (loading)", xlim=(-0.85, 0.85))
ax[1].legend(loc="lower left")
return fig
finish(plot_pca_variance(pca), "pca_variance")
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:
show_table(pd.DataFrame(scores[:8], columns=["PC1", "PC2"]).round(2).rename_axis("rock"), "pca_table")# Helper: the rocks on the first two components, without labels.
def plot_pca_scatter(scores):
fig, ax = plt.subplots(figsize=(6.4, 4.5))
ax.plot(*scores.T, "o", color=INK, ms=3, alpha=0.25, mec="none", label=f"{len(scores):,} rocks, no labels")
ax.set(xlabel=f"PC1 ({var_pct[0]:.0f}% of the variance)", ylabel=f"PC2 ({var_pct[1]:.0f}%)")
ax.legend(loc="upper left", markerscale=3)
return fig
finish(plot_pca_scatter(scores), "pca_scatter")
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.
# --- your code
km_rock = None # KMeans with 3 clusters, fitted on scores
# --- endWorked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
km_rock_sol = KMeans(n_clusters=3, n_init=10, random_state=SEED).fit(scores)
km_rock = check("km_rock", km_rock, km_rock_sol, rtol=1e-3, summary=lambda m: m.inertia_)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.
clusters_rock = km_rock.labels_
crosstab = pd.crosstab(rocks["label"], clusters_rock, rownames=["rock type"], colnames=["cluster"])
match = crosstab.max(axis=0).sum() / len(rocks) # rocks that share their cluster with the majority of their type
groups_7 = KMeans(n_clusters=3, n_init=10, random_state=SEED).fit_predict(Z_rock)
match_7 = pd.crosstab(rocks["label"], groups_7).max(axis=0).sum() / len(rocks)
print(f"rocks in the cluster of their own type: {match:.1%} on PC1-PC2, {match_7:.1%} on all 7 oxides")
show_table(crosstab, "pca_crosstab")rocks in the cluster of their own type: 99.0% on PC1-PC2, 99.4% on all 7 oxides
# Helper: the k-means clusters on PC1-PC2, next to the hidden rock types.
def plot_pca_kmeans(scores, km, labels, crosstab):
fig, ax = plt.subplots(1, 2, figsize=(12.0, 4.1), sharex=True, sharey=True)
majority = crosstab.idxmax(axis=0) # the main rock type of each cluster, to pick its color
for j in range(km.n_clusters):
sel = km.labels_ == j
rock = majority[j]
ax[0].plot(*scores[sel].T, ROCK_MARKERS[rock], color=ROCK_COLORS[rock], ms=4, alpha=0.4, mec="none",
label=f"cluster {j + 1} ({sel.sum():,})")
ax[0].plot(*km.cluster_centers_[j], "X", color=ROCK_COLORS[rock], mec=INK, mew=1.5, ms=18)
for rock in ["basalt", "andesite", "granite"]:
sel = (labels == rock).to_numpy()
ax[1].plot(*scores[sel].T, ROCK_MARKERS[rock], color=ROCK_COLORS[rock], ms=4, alpha=0.4, mec="none",
label=f"{rock} ({sel.sum():,})")
for a in ax:
a.set(xlabel="PC1", ylim=(-3, 5.3))
leg = a.legend(loc="upper left", markerscale=2.5, handletextpad=0.2, ncol=3, columnspacing=0.6,
fontsize=14)
for handle in leg.legend_handles:
handle.set_alpha(1)
ax[0].set_ylabel("PC2")
return fig
finish(plot_pca_kmeans(scores, km_rock, rocks["label"], crosstab), "pca_kmeans")
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%.
ZENODO_FILES = "https://zenodo.org/api/records/14025693/files"
SEISMIC_FILES = ["1000_earthquakes_physical_features.csv", "1000_explosion_physical_features.csv",
"1000_surface_physical_features.csv", "1000_noise_physical_features.csv"]
SEISMIC_TYPES = ["earthquake", "explosion", "surface event", "noise"]
def synthetic_seismic(n_per_class=1000, n_features=61, seed=SEED):
"""Synthetic stand-in for the feature table, used only if Zenodo cannot be reached."""
rng = np.random.default_rng(seed)
centers = rng.normal(0, 2.5, (4, 8))
centers[2] = centers[1] + rng.normal(0, 0.6, 8) # surface events next to explosions
Z, y = make_blobs(n_samples=[n_per_class] * 4, centers=centers, cluster_std=1.0, random_state=seed)
F = Z @ rng.normal(size=(8, n_features)) + rng.normal(0, 1.0, (len(Z), n_features))
df = pd.DataFrame(F * 10 ** rng.uniform(-3, 3, n_features), columns=[f"f{i:02d}" for i in range(n_features)])
df["source"] = np.array(SEISMIC_TYPES)[y]
df["serial_no"] = np.arange(len(df))
return df
def load_seismic():
"""PNW waveform features, 1,000 events per source type (Zenodo record 14025693); synthetic table if offline."""
try:
frames = [pd.read_csv(f"{ZENODO_FILES}/{name}/content", index_col=0) for name in SEISMIC_FILES]
print("PNW seismic features: 4 tables read from Zenodo")
return pd.concat(frames, ignore_index=True)
except Exception as err:
print(f"FALLBACK: Zenodo could not be reached ({type(err).__name__}). Using a synthetic table with four "
"groups; its numbers are NOT the PNSN events.")
return synthetic_seismic()
seismic = load_seismic().dropna(axis=1) # one feature (Gamma) has missing values
y_seis = seismic["source"] # analyst labels: kept aside, used only to score
X_seis = seismic.drop(columns=["source", "serial_no"])
Z_seis = StandardScaler().fit_transform(X_seis)
pca_seis = PCA().fit(Z_seis)
cum_var = np.cumsum(pca_seis.explained_variance_ratio_) # variance kept by the first 1, 2, 3, ... components
n_pcs = int(np.searchsorted(cum_var, 0.80) + 1) # smallest number of components that keep 80%
X_pca_seis = pca_seis.transform(Z_seis)[:, :n_pcs]
clusters_seis = KMeans(n_clusters=4, n_init=N_STARTS, random_state=SEED).fit_predict(X_pca_seis)
print(f"{X_seis.shape[0]} events, {X_seis.shape[1]} features; the variance kept by PC1 is {cum_var[0]:.1%}, "
f"by PC1 and PC2 {cum_var[1]:.1%}, by {n_pcs} components {cum_var[n_pcs - 1]:.1%}")
print(f"k-means (K = 4) on {n_pcs} components, against the analyst labels:")
pd.crosstab(clusters_seis, y_seis, rownames=["cluster"], colnames=["analyst label"])[SEISMIC_TYPES]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:
# Helper: the seismic events on PC1-PC2 colored by analyst label, and the variance kept by the first components.
def plot_seismic_pca(scores, labels, pca, cum_var, n_pcs, target=0.80):
fig = plt.figure(figsize=(12.0, 4.15))
gs = fig.add_gridspec(1, 2, width_ratios=[1, 1.1])
ax = fig.add_subplot(gs[0])
for j, name in enumerate(SEISMIC_TYPES):
sel = (labels == name).to_numpy()
ax.plot(*scores[sel, :2].T, GROUP_MARKERS[j], color=GROUP_COLORS[j], ms=3, alpha=0.45, mec="none",
label=name)
pct = 100 * pca.explained_variance_ratio_
ax.set(xlabel=f"PC1 ({pct[0]:.0f}% of the variance)", ylabel=f"PC2 ({pct[1]:.0f}%)")
leg = ax.legend(loc="upper left", fontsize=14, markerscale=3, handletextpad=0.2, borderaxespad=0.1)
for handle in leg.legend_handles:
handle.set_alpha(1)
b = fig.add_subplot(gs[1])
k = np.arange(1, len(cum_var) + 1)
b.plot(k, 100 * cum_var, "-o", color=INK, lw=1.5, ms=4)
b.axhline(100 * target, color=ACCENT, ls="--", lw=2, label=f"{target:.0%} of the variance")
b.axvline(n_pcs, color=MUTED, ls=":", lw=2.5, label=f"{n_pcs} components")
b.set(xlabel="number of principal components", ylabel="variance kept (%)", xlim=(0, len(k) + 1), ylim=(0, 102))
b.legend(loc="lower right", fontsize=14)
return fig
finish(plot_seismic_pca(X_pca_seis, y_seis, pca_seis, cum_var, n_pcs), "seis_scores")
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
# Helper: compare an answer with a reference. If the answer is missing or different, print a hint and use the
# reference so the cells below still run; a different answer is kept as <name>_yours.
def check(name, ns, reference, hint, measure=None, tol=1e-3):
measure = measure or (lambda value: np.asarray(value, dtype=float))
yours = ns.get(name)
if yours is None or (hasattr(yours, "__len__") and len(yours) == 0):
print(f"{name}: not answered yet. Hint: {hint}\n Using the reference result below.")
else:
try:
ok = np.allclose(measure(yours), measure(reference), atol=tol)
except Exception:
ok = False
if ok:
print(f"{name}: correct")
return
print(f"{name}: not the expected result. Hint: {hint}\n Your answer is kept as {name}_yours; "
"the reference is used below.")
ns[f"{name}_yours"] = yours
ns[name] = referenceYour 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.
# hcv should hold three numbers: (homogeneity, completeness, V-measure)
hcv = None
Worked solution below (click ⋯ to open it).
Notebook Cell
hcv_sol = homogeneity_completeness_v_measure(y_seis, clusters_seis)
check("hcv", globals(), hcv_sol, "homogeneity_completeness_v_measure(y_seis, clusters_seis)")hcv: not answered yet. Hint: homogeneity_completeness_v_measure(y_seis, clusters_seis)
Using the reference result below.
print(f"homogeneity {hcv[0]:.2f}, completeness {hcv[1]:.2f}, V-measure {hcv[2]:.2f}")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 generatorrngdefined 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)).
rng = np.random.default_rng(SEED)
one_cluster = None
random_clusters = None
Worked solution below (click ⋯ to open it).
Notebook Cell
def _scores(clusters):
return np.array(homogeneity_completeness_v_measure(y_seis, clusters))
one_cluster_sol = np.zeros(len(y_seis), dtype=int)
random_clusters_sol = np.random.default_rng(SEED).integers(0, 4, len(y_seis))
# Any random draw is accepted: its scores only need to be close to those of the reference draw.
check("one_cluster", globals(), one_cluster_sol, "np.zeros(len(y_seis), dtype=int)", measure=_scores)
check("random_clusters", globals(), random_clusters_sol, "rng.integers(0, 4, len(y_seis))", measure=_scores, tol=0.02)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.
clusterings = {"all in one cluster": one_cluster, "random clusters": random_clusters, "k-means, K = 4": clusters_seis}
pd.DataFrame([homogeneity_completeness_v_measure(y_seis, c) for c in clusterings.values()],
index=list(clusterings), columns=["homogeneity", "completeness", "V-measure"]).round(3)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)).
ks = range(2, 9)
scores_by_k = [] # one row (homogeneity, completeness, V-measure) per K
for k in ks:
# cluster X_pca_seis into k groups, score against y_seis, append the three numbers
pass
Worked solution below (click ⋯ to open it).
Notebook Cell
scores_by_k_sol = [homogeneity_completeness_v_measure(
y_seis, KMeans(n_clusters=k, n_init=N_STARTS, random_state=SEED).fit_predict(X_pca_seis)) for k in ks]
check("scores_by_k", globals(), scores_by_k_sol,
"KMeans(n_clusters=k, n_init=N_STARTS, random_state=SEED).fit_predict(X_pca_seis), then score and append")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.
# Helper: the three scores against the number of clusters
def plot_scores_by_k(ks, scores):
scores = np.asarray(scores)
fig, ax = plt.subplots(figsize=(8.0, 4.0))
for j, (name, marker) in enumerate(zip(["homogeneity", "completeness", "V-measure"], ["o-", "s-", "D-"])):
ax.plot(list(ks), scores[:, j], marker, color=GROUP_COLORS[j], lw=2, ms=7, label=name)
ax.axvline(4, color=MUTED, ls=":", lw=2)
ax.set(xlabel="number of clusters K", ylabel="score (0 to 1)", ylim=(0, 0.75))
ax.legend(loc="upper right", fontsize=14)
return fig
finish(plot_scores_by_k(ks, scores_by_k), "seis_scores_by_k")
pd.DataFrame(np.asarray(scores_by_k), index=pd.Index(list(ks), name="K"),
columns=["homogeneity", "completeness", "V-measure"]).round(3)
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):
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.)
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?
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
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.
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.
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¶
| Method | Question | What it makes small | Today’s example |
|---|---|---|---|
| Linear regression | How does depend on ? | weight from height; density from 7 oxides | |
| Covariance matrix, bootstrap | How sure is the fit? | (spread of the estimates) | slope 0.77 ± 0.11 kg/cm |
| k-means | Which samples belong together? | the kinds of eruption pair at Old Faithful | |
| PCA | Which directions carry the information? | the variance left out | 7 oxides to 2 components, 91% |
| Homogeneity, completeness, V-measure | Do 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 ; Voronoi diagrams; regularized regression (ridge, lasso) for many correlated inputs; Gaussian mixtures, which let each cluster have its own shape.