🖥️ Lecture slides: Session 12 (Mon Oct 26)
Learning outcomes. By the end of this notebook you can:
train a classifier on analyst labels from a real seismic catalog and read its confusion matrix and per-class recall against a majority-class baseline;
choose a hyperparameter on a validation set drawn from the training domain, and score the chosen model once on a test set from outside that domain (a later period, or a different rock composition);
detect a shortcut feature, one that separates the classes in the catalog for a reason that will not hold for every event, and measure what the model loses or gains without it;
train a regression model for a physical quantity, report its error in physical units, and show that the error grows when the test samples lie outside the training range.
Classification predicts a category (earthquake or blast, rock type, flood or no flood). Regression predicts a quantity (density in g/cm³, discharge in m³/s, magnitude). The workflow is the same for both: define the target and features, partition the data, fit a trivial baseline, fit models, choose among them on validation data, test once. Only the metric changes: class counts and recalls for classification, errors in the units of the target for regression.
To run it. From the repository root, pixi run jupyter lab. Run the setup cell below once. Section 1 downloads two tables from the USGS earthquake catalog (about 3 MB, a few seconds) and keeps them in a local cache; without network the notebook says so and uses a synthetic catalog instead. Each Your turn cell is followed by a check that prints correct, a hint, or not answered yet. If your answer is not correct yet, the check puts the reference result in place so that the rest of the notebook runs; your own result is kept with the suffix _yours. Sections 1 to 5 fit in 45 minutes.
How this notebook is organized¶
The first code cell imports every package the notebook uses. Putting the imports first gives one place to see what the analysis depends on (all of it comes with the course environment) and makes a missing package fail at the top rather than halfway through.
Code that is used more than once, or that would clutter an analysis cell (downloading a catalog, styling a figure, laying out a table), is written as a named function and defined just before it is first needed. A function with a clear name and a one-line description lets each analysis cell show the steps of the analysis; open a collapsed cell to see how a figure or a table is made.
# Data handling
import warnings
import numpy as np
import pandas as pd
import pooch # downloads a file once and keeps a local copy
# Plotting
import matplotlib.pyplot as plt
# Machine learning (scikit-learn)
from sklearn.base import clone
from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import (ConfusionMatrixDisplay, balanced_accuracy_score, confusion_matrix,
mean_absolute_error, r2_score, recall_score)
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
# Course data generators (the Session 5 rock table)
import mlgeo_synth
The values below describe the study area and the data source. They are used in several places, so they are defined once: changing the region or the time zone here changes it everywhere.
warnings.filterwarnings("ignore", category=FutureWarning) # hide library deprecation notices
plt.rcParams.update({"figure.dpi": 100, "axes.grid": True, "grid.alpha": 0.3, "axes.spines.top": False,
"axes.spines.right": False, "font.size": 10})
CLASSES = ["earthquake", "explosion"]
COLORS = {"earthquake": "C0", "explosion": "C3", "basalt": "C3", "andesite": "C2", "granite": "C0"}
TZ = "America/Los_Angeles"
BOX = dict(minlatitude=42, maxlatitude=49.5, minlongitude=-125.5, maxlongitude=-116.5)
COMCAT = "https://earthquake.usgs.gov/fdsnws/event/1/query"
CACHE = pooch.os_cache("mlgeo")
SOURCE = {}
The next cell, collapsed, defines the checks for the Your turn cells. Each check compares your answer with a reference, prints correct or a hint, and, if your cell is unfinished, fills in the reference so the rest of the notebook still runs. You do not need to read it.
Source
# Checks for the Your-turn cells: each compares your answer with a reference and prints a hint.
TURNS = {"H": ["hour"], "W": ["work_share"], "B": ["acc_base"], "K": ["val_scores", "best_k"],
"T": ["knn", "y_pred_test", "recall_test"], "N": ["y_pred_nohour"], "R1": ["base_r", "lin", "val_mae"],
"R2": ["ood_mae", "frac_physical"]}
HINTS = {
"H": "hour = cat['time'].dt.tz_convert('America/Los_Angeles').dt.hour",
"W": "work_share = cat.groupby('label')['hour'].apply(lambda h: h.between(8, 16).mean()); "
"plt.hist(cat.loc[cat['label'] == lab, 'hour'], bins=np.arange(25), density=True, alpha=0.5) for each label.",
"B": "baseline = DummyClassifier(strategy='most_frequent').fit(X_train, y_train); acc_base = baseline.score(X_val, y_val)",
"K": "for k in K_LIST: fit make_knn(k) on (X_train, y_train) and store balanced_accuracy_score(y_val, model.predict(X_val)) "
"in val_scores[k]; best_k = max(val_scores, key=val_scores.get)",
"T": "knn = make_knn(best_k).fit(X_train, y_train); y_pred_test = knn.predict(X_test); "
"recall_test = recall_score(y_test, y_pred_test, labels=CLASSES, average=None)",
"N": "fit make_knn(best_k) on X_train[NOHOUR] and predict X_test[NOHOUR], with NOHOUR the feature list without 'hour'.",
"R1": "base_r = DummyRegressor(strategy='mean').fit(Xr_train, yr_train); lin = LinearRegression().fit(Xr_train, yr_train); "
"val_mae = {'mean': mean_absolute_error(yr_val, base_r.predict(Xr_val)), 'linear': ...}",
"R2": "ood_mae = {name: mean_absolute_error(yr_ood, m.predict(Xr_ood)) for name, m in models.items()}; "
"p = models[best_name].predict(Xr_ood); frac_physical = ((p >= 2.5) & (p <= 3.3)).mean()",
}
def _ref(key, ns):
r = {}
if key == "H":
r["hour"] = ns["cat"]["time"].dt.tz_convert(TZ).dt.hour
elif key == "W":
r["work_share"] = ns["cat"].groupby("label")["hour"].apply(lambda h: h.between(8, 16).mean())
elif key == "B":
r["acc_base"] = DummyClassifier(strategy="most_frequent").fit(ns["X_train"], ns["y_train"]).score(ns["X_val"], ns["y_val"])
elif key == "K":
r["val_scores"] = {k: balanced_accuracy_score(ns["y_val"], make_knn(k).fit(ns["X_train"], ns["y_train"]).predict(ns["X_val"]))
for k in ns["K_LIST"]}
r["best_k"] = max(r["val_scores"], key=r["val_scores"].get)
elif key == "T":
r["knn"] = make_knn(ns["best_k"]).fit(ns["X_train"], ns["y_train"])
r["y_pred_test"] = r["knn"].predict(ns["X_test"])
r["recall_test"] = recall_score(ns["y_test"], r["y_pred_test"], labels=CLASSES, average=None)
elif key == "N":
f = [c for c in ns["FEATURES"] if c != "hour"]
r["y_pred_nohour"] = make_knn(ns["best_k"]).fit(ns["X_train"][f], ns["y_train"]).predict(ns["X_test"][f])
elif key == "R1":
r["base_r"] = DummyRegressor(strategy="mean").fit(ns["Xr_train"], ns["yr_train"])
r["lin"] = LinearRegression().fit(ns["Xr_train"], ns["yr_train"])
r["val_mae"] = {n: mean_absolute_error(ns["yr_val"], r[m].predict(ns["Xr_val"]))
for n, m in [("mean", "base_r"), ("linear", "lin")]}
elif key == "R2":
r["ood_mae"] = {n: mean_absolute_error(ns["yr_ood"], m.predict(ns["Xr_ood"])) for n, m in ns["models"].items()}
p = ns["models"][ns["best_name"]].predict(ns["Xr_ood"])
r["frac_physical"] = float(((p >= 2.5) & (p <= 3.3)).mean())
return r
def _close(a, b, rtol=1e-3):
if isinstance(b, dict):
return isinstance(a, dict) and set(a) == set(b) and all(_close(a[k], b[k], rtol) for k in b)
try:
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
except (TypeError, ValueError):
return False
return a.shape == b.shape and bool(np.allclose(a, b, rtol=rtol, atol=1e-9))
def _verdict(key, v, r):
hint = "not yet. Hint: " + HINTS[key]
if key == "W":
w = v["work_share"]
try:
w = pd.Series(w).reindex(CLASSES)
except Exception:
return hint
return "correct" if _close(w.to_numpy(), r["work_share"].reindex(CLASSES).to_numpy()) else hint
if key in ("T", "N"):
n = TURNS[key][1] if key == "T" else TURNS[key][0]
if key == "T" and not _close(v["recall_test"], r["recall_test"]):
return hint
ok = v[n] is not None and len(v[n]) == len(r[n]) and np.mean(np.asarray(v[n]) == r[n]) > 0.999
return "correct" if ok else hint
if key == "K":
ok = _close(v["val_scores"], r["val_scores"]) and v["best_k"] == r["best_k"]
return "correct" if ok else hint
if key == "R1":
ok = _close(v["val_mae"], r["val_mae"]) and v["lin"] is not None and v["base_r"] is not None
return "correct" if ok else hint
ok = all(_close(v[n], r[n]) for n in TURNS[key])
return "correct" if ok else hint
def your_turn(key, ns):
r = _ref(key, ns)
v = {n: ns.get(n) for n in TURNS[key]}
verdict = "not answered yet" if all(x is None for x in v.values()) else _verdict(key, v, r)
print(f"[{key}] {verdict}")
if verdict == "correct":
return
kept = []
for n in TURNS[key]:
if ns.get(n) is not None:
ns[n + "_yours"] = ns[n]
kept.append(n + "_yours")
ns[n] = r[n]
note = f"; yours kept as {', '.join(kept)}" if kept else ""
print(f"[{', '.join(TURNS[key])}] using the reference result so the next cells run{note}.")
if key == "W":
plot_hours(ns["cat"])
1. Earthquake or blast? The catalog and its labels¶
The Pacific Northwest Seismic Network (PNSN) locates a few thousand events a year in Washington and Oregon. Not all of them are earthquakes: quarries, open-pit mines and construction sites set off blasts that the network also records. A PNSN analyst reviews each event and assigns a type; blasts are labeled explosion. Those analyst labels are the target of our classifier. They are published in the USGS Comprehensive Catalog (ComCat), which we query for 2015 to 2024 in a box from 42 to 49.5°N and 125.5 to 116.5°W: earthquakes of magnitude 1 and above, and all explosions.
Blasting is a working-hours activity, and blasts sit at the surface next to a pit. Earthquakes happen at any hour and at depths of several to tens of kilometers. Wiemer and Baer (2000, Bulletin of the Seismological Society of America 90, 525-530, Wiemer (2000)) used the first fact to find regions of a catalog contaminated by blasts: where the ratio of daytime to nighttime events is high, the catalog holds blasts. We ask the same question event by event.
The function below downloads the catalog from ComCat once and keeps a local copy, so the notebook runs quickly the second time and works on a later day with the same data. If ComCat cannot be reached, it builds a small synthetic catalog instead (collapsed cell) and says so.
Source
# Fallback used only when ComCat cannot be reached: a small synthetic catalog with the same columns.
def synthetic_catalog(seed=42):
"""Small stand-in catalog: earthquakes at any hour and depth, blasts at 12 'quarries' during working hours."""
rng = np.random.default_rng(seed)
n_eq, n_ex = 3000, 1600
t0, t1 = pd.Timestamp("2015-01-01", tz="UTC").value, pd.Timestamp("2025-01-01", tz="UTC").value
eq = pd.DataFrame({"time": pd.to_datetime(rng.uniform(t0, t1, n_eq).astype("int64"), utc=True),
"latitude": rng.uniform(42, 49.5, n_eq), "longitude": rng.uniform(-125.5, -116.5, n_eq),
"depth": rng.gamma(2.0, 7.0, n_eq), "mag": 1 + rng.exponential(0.45, n_eq),
"label": "earthquake"})
sites = np.column_stack([rng.uniform(43, 49.3, 12), rng.uniform(-123.5, -117, 12)])
k = rng.integers(0, 12, n_ex)
day = pd.to_datetime(rng.uniform(t0, t1, n_ex).astype("int64"), utc=True).tz_convert(TZ).normalize()
local = day + pd.to_timedelta(np.clip(rng.normal(12.5, 2.0, n_ex), 0, 23.9), unit="h")
ex = pd.DataFrame({"time": local.tz_convert("UTC"), "latitude": sites[k, 0] + rng.normal(0, 0.02, n_ex),
"longitude": sites[k, 1] + rng.normal(0, 0.02, n_ex), "depth": rng.normal(-0.5, 0.3, n_ex),
"mag": 1 + rng.exponential(0.5, n_ex), "label": "explosion"})
return pd.concat([eq, ex], ignore_index=True).sort_values("time", ignore_index=True)
def _comcat_url(eventtype, minmag=None):
q = dict(format="csv", starttime="2015-01-01", endtime="2025-01-01", eventtype=eventtype, orderby="time-asc", **BOX)
if minmag is not None:
q["minmagnitude"] = minmag
return COMCAT + "?" + "&".join(f"{k}={v}" for k, v in q.items())
def load_catalog():
"""PNSN earthquakes (M >= 1) and explosions from USGS ComCat, 2015-2024, cached; synthetic catalog if offline."""
try:
frames = []
for etype, minmag in [("earthquake", 1), ("explosion", None)]:
path = pooch.retrieve(_comcat_url(etype, minmag), known_hash=None, path=CACHE, progressbar=False,
fname=f"comcat_pnw_2015-2024_{etype}.csv",
downloader=pooch.HTTPDownloader(timeout=60))
frames.append(pd.read_csv(path))
raw = pd.concat(frames, ignore_index=True)
raw["time"] = pd.to_datetime(raw["time"], utc=True)
raw["label"] = raw["type"]
print(f"USGS ComCat, read from the cache {CACHE}:")
SOURCE["catalog"] = "ComCat"
return raw[["time", "latitude", "longitude", "depth", "mag", "magType", "depthError", "net", "label"]]
except Exception as err:
print(f"FALLBACK: USGS ComCat could not be reached ({type(err).__name__}: {str(err)[:80]}).\n"
"Using a small synthetic catalog built in the setup cell. Its numbers are NOT the Pacific Northwest;\n"
"the text describes the real catalog.")
SOURCE["catalog"] = "synthetic"
cat = synthetic_catalog()
cat["magType"], cat["depthError"], cat["net"] = "ml", np.nan, "synthetic"
return cat
cat = load_catalog()
print(cat["label"].value_counts().to_string())
cat.head(3)Downloading data from 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=csv&starttime=2015-01-01&endtime=2025-01-01&eventtype=earthquake&orderby=time-asc&minlatitude=42&maxlatitude=49.5&minlongitude=-125.5&maxlongitude=-116.5&minmagnitude=1' to file '/home/runner/.cache/mlgeo/comcat_pnw_2015-2024_earthquake.csv'.
SHA256 hash of downloaded file: cc533e32eea33e6d2633e63f67a17fb8378baa8250f56e5dc507d322671315a3
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
Downloading data from 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=csv&starttime=2015-01-01&endtime=2025-01-01&eventtype=explosion&orderby=time-asc&minlatitude=42&maxlatitude=49.5&minlongitude=-125.5&maxlongitude=-116.5' to file '/home/runner/.cache/mlgeo/comcat_pnw_2015-2024_explosion.csv'.
SHA256 hash of downloaded file: fe56b9ca5f12ec1435b82d4fd5f13532b90473bb987efe742e8dd7166a0a5ff4
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
USGS ComCat, read from the cache /home/runner/.cache/mlgeo:
label
earthquake 10263
explosion 5805
The magnitude cut. The earthquakes were requested with M ≥ 1 and the explosions without a cut, so every event below M 1 in the table is an explosion by construction of the query, not by physics. A classifier would learn that rule within seconds. We apply the same cut to both classes. Three explosions carry magnitude -5.0, a placeholder rather than a measurement; the cut removes them too.
Source
# Helper: the map of events with depth histograms, and the histogram of local hour, colored by label. Kept as functions so the analysis cells show the analysis, not the plot styling.
def plot_catalog(cat):
fig, ax = plt.subplots(1, 2, figsize=(12, 6), gridspec_kw={"width_ratios": [1, 1]})
try:
ne = pd.read_csv("../Chapter2-DataManipulation/snapshots/naturalearth_pnw_map.csv") # Natural Earth 1:50m
for (kind, part), g in ne[ne["kind"] != "place"].groupby(["kind", "part"]):
ax[0].plot(g["lon"], g["lat"], color="0.3" if kind == "coastline" else "0.65", lw=0.7)
for _, p in ne[ne["kind"] == "place"].iterrows():
ax[0].plot(p["lon"], p["lat"], "ks", ms=4)
ax[0].annotate(p["name"], (p["lon"], p["lat"]), xytext=(4, 4), textcoords="offset points", fontsize=8)
except FileNotFoundError:
pass
for lab in CLASSES:
m = cat["label"] == lab
ax[0].scatter(cat.loc[m, "longitude"], cat.loc[m, "latitude"], s=3, alpha=0.4, color=COLORS[lab],
label=f"{lab} ({m.sum()})")
ax[0].set(xlim=(-125.5, -116.5), ylim=(42, 49.5), xlabel="longitude (°)", ylabel="latitude (°)",
title=f"Events 2015-2024, M ≥ 1 ({SOURCE['catalog']})")
ax[0].set_aspect(1 / np.cos(np.radians(46)))
ax[0].legend(fontsize=8, markerscale=4, loc="lower left")
for lab in CLASSES:
d = cat.loc[cat["label"] == lab, "depth"]
ax[1].hist(d, bins=np.arange(-4, 41, 1), alpha=0.5, density=True, color=COLORS[lab], label=lab)
ax[1].set(xlabel="depth below sea level (km)", ylabel="density", title="Depth by label (negative = above sea level)")
ax[1].legend(fontsize=8)
fig.tight_layout()
def plot_hours(cat):
fig, ax = plt.subplots(figsize=(7, 3.5))
for lab in CLASSES:
ax.hist(cat.loc[cat["label"] == lab, "hour"], bins=np.arange(25), alpha=0.5, density=True,
color=COLORS[lab], label=lab)
ax.axvspan(8, 17, color="0.85", zorder=0, label="08:00-17:00")
ax.set(xlabel="local hour (Pacific time)", ylabel="fraction of events per hour", xticks=range(0, 25, 3))
ax.legend(fontsize=8)
cat = cat[cat["mag"] >= 1].reset_index(drop=True)
print(cat["label"].value_counts().to_string())
plot_catalog(cat)label
earthquake 10263
explosion 5128

Explosions cluster at quarry and mine sites, densest along the Interstate 5 corridor from the Puget Lowland to the Willamette Valley, where aggregate is quarried for construction, and scattered across eastern Washington and Oregon. Earthquakes are spread more widely, densest under Puget Sound and along the Cascade arc. The depth histogram separates the classes almost completely: about 98% of the explosions are shallower than 1 km against about 9% of the earthquakes. Part of that separation is not seismology. About 98% of the explosions carry the same depth uncertainty, 31.61 km, and many share identical depths (-0.37 or -0.53 km): the analyst fixed the depth at the surface once the event was called a blast. Depth is partly a consequence of the label. Keep that in mind when we read the scores.
Your turn: local hour of day. ComCat times are UTC. Write hour, the hour of each event (0 to 23) in Pacific time, daylight saving included.
Hint: cat["time"].dt.tz_convert("America/Los_Angeles").dt.hour.
# --- your code
hour = None # Series of integers 0-23, one per event
# --- end
your_turn("H", globals())[H] not answered yet
[hour] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
hour_sol = cat["time"].dt.tz_convert("America/Los_Angeles").dt.hourYour turn: hour of day by label. The first line, given, adds the hour to the catalog. Plot one histogram of hour per label on the same axes (24 bins of one hour, normalized with density=True), and write work_share, the fraction of each class between 08:00 and 16:59 local time (a Series indexed by label).
Hint: cat.groupby("label")["hour"].apply(lambda h: h.between(8, 16).mean()).
cat["hour"] = hour # given
# --- your code
work_share = None # Series: label -> fraction of events with 8 <= hour <= 16
# --- end
your_turn("W", globals())[W] not answered yet
[work_share] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
fig, ax = plt.subplots(figsize=(7, 3.5))
for lab in CLASSES:
ax.hist(cat.loc[cat["label"] == lab, "hour"], bins=np.arange(25), density=True, alpha=0.5, label=lab)
ax.set(xlabel="local hour", ylabel="fraction per hour"); ax.legend()
work_share_sol = cat.groupby("label")["hour"].apply(lambda h: h.between(8, 16).mean())
weekend = cat["time"].dt.tz_convert(TZ).dt.dayofweek >= 5
print("share between 08:00 and 16:59 local:", work_share.round(3).to_dict(), " (9 of 24 hours = 0.375)")
print("share on Saturday or Sunday:", weekend.groupby(cat["label"]).mean().round(3).to_dict(), " (2 of 7 days = 0.286)")share between 08:00 and 16:59 local: {'earthquake': 0.383, 'explosion': 0.943} (9 of 24 hours = 0.375)
share on Saturday or Sunday: {'earthquake': 0.281, 'explosion': 0.074} (2 of 7 days = 0.286)
Earthquakes follow the clock uniformly: their share in the nine working hours is close to 9/24, and their weekend share close to 2/7. Blasts fall almost entirely inside the working day, with a peak in the early afternoon, and rarely on weekends. The hour of day is a strong feature, and it is a social one: it describes the work schedule of the mine, not the source.
2. Partitions: within domain and out of domain in time¶
We follow the partition rule of 2.13 (criterion B7). The domain is 2015 to 2021. Training and validation come from it, with the validation set drawn at random among those events (stratified by label): validation tests interpolation and chooses the hyperparameter. The test set is 2022 to 2024, a later period. It measures whether a model trained on past years still works on the events the network will label next, when mines open and close, the network changes and analysts change. The test is touched once, at the end.
FEATURES = ["hour", "depth", "mag", "latitude", "longitude"]
in_domain = cat["time"] < pd.Timestamp("2022-01-01", tz="UTC")
X_train, X_val, y_train, y_val = train_test_split(cat.loc[in_domain, FEATURES], cat.loc[in_domain, "label"],
test_size=0.2, stratify=cat.loc[in_domain, "label"], random_state=42)
X_test, y_test = cat.loc[~in_domain, FEATURES], cat.loc[~in_domain, "label"]
pd.DataFrame({"train 2015-2021": y_train.value_counts(), "validation 2015-2021": y_val.value_counts(),
"test 2022-2024": y_test.value_counts()})Your turn: majority-class baseline. A model has to beat the classifier that always answers the most frequent class. Fit DummyClassifier(strategy="most_frequent") on the training set and write acc_base, its accuracy on the validation set.
Hint: .fit(X_train, y_train), then .score(X_val, y_val).
# --- your code
acc_base = None # accuracy of the majority-class baseline on the validation set
# --- end
your_turn("B", globals())[B] not answered yet
[acc_base] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
baseline_sol = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
acc_base_sol = baseline_sol.score(X_val, y_val)print(f"baseline accuracy on validation: {acc_base:.3f}; recall: earthquake 1.0, explosion 0.0; balanced accuracy 0.5")baseline accuracy on validation: 0.681; recall: earthquake 1.0, explosion 0.0; balanced accuracy 0.5
Source
# Helper: A k-nearest-neighbors classifier with feature scaling in front. A function because the same model is built three times: to choose k, to test once, and without the hour.
def make_knn(k):
return make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
def plot_k_curve(val_scores, best_k):
fig, ax = plt.subplots(figsize=(6, 3.2))
ax.plot(list(val_scores), list(val_scores.values()), "o-", color="k")
ax.axvline(best_k, color="C3", ls=":", label=f"best k = {best_k}")
ax.set(xscale="log", xlabel="number of neighbors k", ylabel="balanced accuracy (validation)")
ax.legend(fontsize=8)
The baseline is right about two times in three, and it never finds a blast. Accuracy rewards the majority class, so from here on we choose models with the balanced accuracy, the mean of the per-class recalls (recall of a class = fraction of its events that the model labels correctly). The baseline scores 0.5 on it.
Your turn: choose k on the validation set. The classifier is k-nearest neighbors on standardized features (make_knn(k) in the setup cell builds the pipeline StandardScaler then KNeighborsClassifier). For each k in K_LIST, fit on the training set and store the validation balanced accuracy in the dictionary val_scores; then set best_k to the k with the highest score.
Hint: balanced_accuracy_score(y_val, model.predict(X_val)); max(val_scores, key=val_scores.get).
K_LIST = [1, 3, 9, 27, 81]# --- your code
val_scores = None # dict: k -> balanced accuracy on the validation set
best_k = None
# --- end
your_turn("K", globals())[K] not answered yet
[val_scores, best_k] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
val_scores_sol = {}
for k in K_LIST:
model = make_knn(k).fit(X_train, y_train)
val_scores_sol[k] = balanced_accuracy_score(y_val, model.predict(X_val))
best_k_sol = max(val_scores_sol, key=val_scores_sol.get)print("best k:", best_k, " validation balanced accuracy:", {k: round(v, 3) for k, v in val_scores.items()})
plot_k_curve(val_scores, best_k)best k: 3 validation balanced accuracy: {1: 0.958, 3: 0.972, 9: 0.968, 27: 0.958, 81: 0.944}

Your turn: test once. Refit make_knn(best_k) on the training set, call it knn, predict the 2022-2024 test events into y_pred_test, and write recall_test, the recall of each class on the test set (order of CLASSES).
Hint: knn = make_knn(best_k).fit(X_train, y_train); recall_score(y_test, y_pred_test, labels=CLASSES, average=None).
# --- your code
knn = None
y_pred_test = None
recall_test = None # array: recall of earthquake, recall of explosion
# --- end
your_turn("T", globals())[T] not answered yet
[knn, y_pred_test, recall_test] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
knn_sol = make_knn(best_k).fit(X_train, y_train)
y_pred_test_sol = knn_sol.predict(X_test)
recall_test_sol = recall_score(y_test, y_pred_test_sol, labels=CLASSES, average=None)Source
# Helper: Confusion matrices side by side, one per partition.
def plot_confusions(pairs):
fig, ax = plt.subplots(1, len(pairs), figsize=(4.3 * len(pairs), 3.8))
for a, (title, yt, yp) in zip(np.atleast_1d(ax), pairs):
ConfusionMatrixDisplay(confusion_matrix(yt, yp, labels=CLASSES), display_labels=CLASSES).plot(
ax=a, colorbar=False, cmap="Blues", values_format="d")
a.set_title(title, fontsize=10)
a.grid(False)
fig.tight_layout()
y_pred_val = knn.predict(X_val)
plot_confusions([("validation 2015-2021", y_val, y_pred_val), ("test 2022-2024", y_test, y_pred_test)])
for name, yt, yp in [("validation", y_val, y_pred_val), ("test", y_test, y_pred_test)]:
r = recall_score(yt, yp, labels=CLASSES, average=None)
print(f"{name:10s} recall earthquake {r[0]:.3f} recall explosion {r[1]:.3f} balanced accuracy {r.mean():.3f}")validation recall earthquake 0.965 recall explosion 0.979 balanced accuracy 0.972
test recall earthquake 0.951 recall explosion 0.965 balanced accuracy 0.958

Rows of a confusion matrix are the analyst labels, columns the predictions; the off-diagonal cells are the errors. The test score is close to the validation score: from 2015-2021 to 2022-2024 the mining sites, the working hours and the way PNSN analysts label and locate blasts changed little, so the model transfers in time. That is a statement about this network and these years. It does not say the model would work in another region, where the quarries are elsewhere.
3. The shortcut: what does the model rely on?¶
A classifier that leans on the hour learns the work schedule of quarries. It will call a nighttime blast an earthquake (tunnel and construction blasting do happen at night), and it will doubt a daytime earthquake, for instance one event in a swarm that continues through the working day. The day/night ratio of Wiemer and Baer is a statistic over many events; one event at 10:00 is not a blast because of its time. The model is also allowed to use depth, which we saw is partly fixed by the analyst after the label is decided.
Your turn: drop the hour. Refit the k-NN classifier (same best_k) without the hour feature and predict the test set into y_pred_nohour.
Hint: NOHOUR = [f for f in FEATURES if f != "hour"], then fit on X_train[NOHOUR] and predict X_test[NOHOUR].
# --- your code
y_pred_nohour = None
# --- end
your_turn("N", globals())[N] not answered yet
[y_pred_nohour] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
NOHOUR = [f for f in FEATURES if f != "hour"]
y_pred_nohour_sol = make_knn(best_k).fit(X_train[NOHOUR], y_train).predict(X_test[NOHOUR])Source
# Helper: Recall on all test events, on blasts outside working hours and on earthquakes inside them, for several feature sets.
def shortcut_table(rows, te):
"""Recall on all test events, on blasts outside 08:00-17:00 and on earthquakes inside it."""
night_ex = (te["label"] == "explosion") & ~te["hour"].between(8, 16)
day_eq = (te["label"] == "earthquake") & te["hour"].between(8, 16)
out = []
for name, pred in rows.items():
r = recall_score(te["label"], pred, labels=CLASSES, average=None)
out.append({"features": name, "balanced accuracy": r.mean(), "recall earthquake": r[0],
"recall explosion": r[1],
f"blasts outside 08-17 h ({night_ex.sum()})": (pred[night_ex.to_numpy()] == "explosion").mean(),
f"earthquakes 08-17 h ({day_eq.sum()})": (pred[day_eq.to_numpy()] == "earthquake").mean()})
return pd.DataFrame(out).set_index("features").round(3)
LOCATION_ONLY = ["mag", "latitude", "longitude"]
y_pred_loc = make_knn(best_k).fit(X_train[LOCATION_ONLY], y_train).predict(X_test[LOCATION_ONLY])
te = cat.loc[~in_domain]
shortcut = shortcut_table({"all five": y_pred_test, "without hour": y_pred_nohour,
"without hour and depth": y_pred_loc}, te)
shortcutThe columns on the right are the events that contradict the shortcut: blasts outside working hours and earthquakes inside them. With the hour, the model misses a share of the off-hours blasts; without it, it finds more of them, and the overall score barely moves because depth and location already carry the information. Without depth as well, the score drops: the location of the mines remains, and that is a fair feature for this network, but it would not transfer to a new quarry. Which features are acceptable depends on how the model will be used. If it is meant to label new events before an analyst sees them, depth fixed by the analyst is not available, and the honest score is the last row.
4. Regression: rock density from major-element chemistry¶
Density is a bulk property of a rock that gravity and seismic models need, and it is measured on far fewer samples than chemistry. Mafic rocks are rich in iron and magnesium silicates (olivine, pyroxene, amphibole) and are denser than felsic rocks made mostly of quartz and feldspar. Can we predict density (g/cm³) from the seven major-element oxides (wt%)?
We use the synthetic whole-rock table of the course (mlgeo_synth.geochem_table, as in 2.4 and 2.12): 5000 analyses of basalt, andesite and granite. Its densities follow class averages with a weak trend along the differentiation of each magma (synthetic, so the true relation is known to be simple).
Partition along a physical axis. Training and validation use the rocks with SiO₂ below 63 wt%, the boundary between intermediate and felsic rocks in the total-alkali-silica classification (Le Bas et al., 1986). The test set is every rock at or above 63 wt%: the most silica-rich rocks, absent from training. This is what happens when a model calibrated on basalts and andesites is applied to a granitic pluton.
Source
# Helper: Silica content and density of the rocks, with the threshold that separates training from the silica-rich test.
def plot_rocks(rocks, thr):
fig, ax = plt.subplots(figsize=(7, 4))
for lab in ["basalt", "andesite", "granite"]:
m = rocks["label"] == lab
ax.scatter(rocks.loc[m, "SIO2"], rocks.loc[m, "density_g_cm3"], s=4, alpha=0.4, color=COLORS[lab], label=lab)
ax.axvline(thr, color="k", ls="--", lw=1)
ax.text(thr - 0.5, 3.12, "train and validation ", ha="right", fontsize=9)
ax.text(thr + 0.5, 3.12, "out-of-domain test", ha="left", fontsize=9)
ax.set(xlabel="SiO$_2$ (wt%)", ylabel="density (g/cm³)", title="Synthetic whole-rock analyses (mlgeo_synth)")
ax.legend(fontsize=8, markerscale=4, loc="lower left")
rocks = mlgeo_synth.geochem_table(n=5000, seed=42)
OXIDES = ["SIO2", "AL2O3", "FEO", "MGO", "CAO", "NA2O", "K2O"]
SIO2_MAX = 63.0
low = rocks["SIO2"] < SIO2_MAX
Xr_train, Xr_val, yr_train, yr_val = train_test_split(rocks.loc[low, OXIDES], rocks.loc[low, "density_g_cm3"],
test_size=0.25, random_state=42)
Xr_ood, yr_ood = rocks.loc[~low, OXIDES], rocks.loc[~low, "density_g_cm3"]
print(f"train {len(Xr_train)}, validation {len(Xr_val)}, silica-rich test {len(Xr_ood)}")
plot_rocks(rocks, SIO2_MAX)train 1642, validation 548, silica-rich test 2810

Your turn: baseline and linear regression. Fit base_r = DummyRegressor(strategy="mean") and lin = LinearRegression() on the training set, and write val_mae, a dictionary with the mean absolute error (g/cm³) of each on the validation set, keys "mean" and "linear".
Hint: mean_absolute_error(yr_val, lin.predict(Xr_val)).
# --- your code
base_r = None
lin = None
val_mae = None # {"mean": ..., "linear": ...}, in g/cm3
# --- end
your_turn("R1", globals())[R1] not answered yet
[base_r, lin, val_mae] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
base_r_sol = DummyRegressor(strategy="mean").fit(Xr_train, yr_train)
lin_sol = LinearRegression().fit(Xr_train, yr_train)
val_mae_sol = {"mean": mean_absolute_error(yr_val, base_r_sol.predict(Xr_val)),
"linear": mean_absolute_error(yr_val, lin_sol.predict(Xr_val))}Two nonlinear models: a degree-2 polynomial (all products of pairs of oxides, then a linear fit) and a random forest. We choose among the four models on the validation mean absolute error, and report R² too.
Source
# Helper: Validation scores of several regression models in one table; used for the three candidate models.
def val_table_of(models, X, y):
return pd.DataFrame({"MAE validation (g/cm3)": {n: mean_absolute_error(y, m.predict(X)) for n, m in models.items()},
"R2 validation": {n: r2_score(y, m.predict(X)) for n, m in models.items()}})
models = {"mean": base_r, "linear": lin,
"polynomial deg 2": make_pipeline(StandardScaler(), PolynomialFeatures(2), LinearRegression()).fit(Xr_train, yr_train),
"random forest": RandomForestRegressor(200, min_samples_leaf=5, n_jobs=-1, random_state=0).fit(Xr_train, yr_train)}
val_table = val_table_of(models, Xr_val, yr_val)
best_name = val_table["MAE validation (g/cm3)"].drop("mean").idxmin()
print("chosen on validation:", best_name)
val_table.round(4)chosen on validation: linear
The three models are within a few thousandths of g/cm³ of each other on validation, less than half the baseline error; the measurement noise in the synthetic table is 0.03 g/cm³, so none can do much better. Validation cannot tell them apart.
Your turn: the silica-rich test. Write ood_mae, the mean absolute error of every model in models on the silica-rich test set (a dictionary keyed like models), and frac_physical, the fraction of the chosen model’s test predictions between 2.5 and 3.3 g/cm³ (the range of common crustal igneous rocks).
Hint: a dictionary comprehension over models.items(); ((p >= 2.5) & (p <= 3.3)).mean().
# --- your code
ood_mae = None # dict: model name -> MAE (g/cm3) on rocks with SiO2 >= 63 wt%
frac_physical = None # fraction of models[best_name] predictions within 2.5-3.3 g/cm3
# --- end
your_turn("R2", globals())[R2] not answered yet
[ood_mae, frac_physical] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
ood_mae_sol = {name: mean_absolute_error(yr_ood, m.predict(Xr_ood)) for name, m in models.items()}
p_sol = models[best_name].predict(Xr_ood)
frac_physical_sol = ((p_sol >= 2.5) & (p_sol <= 3.3)).mean()Source
# Helper: Predicted against observed density within and outside the training range, and the same models refit on a random split.
def plot_pred_obs(models, Xv, yv, Xo, yo):
fig, ax = plt.subplots(1, len(models), figsize=(4 * len(models), 3.8), sharex=True, sharey=True)
for a, (name, m) in zip(ax, models.items()):
a.plot(yv, m.predict(Xv), ".", ms=2, alpha=0.4, color="0.4", label="validation (SiO$_2$ < threshold)")
a.plot(yo, m.predict(Xo), ".", ms=2, alpha=0.4, color="C0", label="test (silica-rich)")
a.plot([2.5, 3.2], [2.5, 3.2], "k-", lw=0.8)
a.set(title=name, xlabel="observed density (g/cm³)")
ax[0].set_ylabel("predicted density (g/cm³)")
ax[0].legend(fontsize=7, markerscale=5, loc="upper left")
fig.tight_layout()
def random_split_mae(rocks, models, oxides):
"""Same models refit on a random 80/20 split of all rocks: MAE on the random 20%."""
Xa, Xb, ya, yb = train_test_split(rocks[oxides], rocks["density_g_cm3"], test_size=0.2, random_state=42)
return {n: mean_absolute_error(yb, clone(m).fit(Xa, ya).predict(Xb)) for n, m in models.items()}
reg = pd.DataFrame({"validation (SiO2 < 63)": val_table["MAE validation (g/cm3)"], "silica-rich test": ood_mae,
"random 20% test": random_split_mae(rocks, models, OXIDES)}).round(4)
print(f"chosen model ({best_name}): {100 * frac_physical:.1f}% of test predictions within 2.5-3.3 g/cm3")
plot_pred_obs({n: m for n, m in models.items() if n != "mean"}, Xr_val, yr_val, Xr_ood, yr_ood)
regchosen model (linear): 100.0% of test predictions within 2.5-3.3 g/cm3

All predictions are physically plausible, yet the errors grow on the silica-rich rocks. The linear model extrapolates the trend from basalt to andesite and lands close to granite densities; its error grows by about a fifth. The random forest cannot extrapolate: each prediction is an average of training densities, so a granite receives the density of the most evolved andesites, about 0.1 g/cm³ too high, roughly four times its validation error. The random split hides the problem, because then every test rock has neighbors of the same type in the training set. Two models that tie on validation differ by a factor of more than three outside the domain, and only an out-of-domain test shows it.
5. Summary¶
Source
# Helper: The summary table at the end of the notebook.
def summarize(val_bal, test_bal, val_mae_base, val_mae_best, ood_mae_best):
return pd.DataFrame([
{"task": "classification", "target": "analyst label, earthquake or explosion", "metric": "balanced accuracy",
"baseline": 0.5, "best model, validation": val_bal, "best model, out of domain": test_bal,
"out-of-domain axis": "time: 2022-2024"},
{"task": "regression", "target": "density (g/cm3)", "metric": "MAE (g/cm3)", "baseline": val_mae_base,
"best model, validation": val_mae_best, "best model, out of domain": ood_mae_best,
"out-of-domain axis": "composition: SiO2 >= 63 wt%"}]).set_index("task").round(3)
summarize(val_scores[best_k], recall_test.mean(), val_mae["mean"], val_table.loc[best_name, "MAE validation (g/cm3)"],
ood_mae[best_name])Both tasks used labels or measured targets. Session 13 and notebook 3.3 remove the labels: clustering looks for the same structure (groups of events, families of rocks) from the features alone.
For criterion B7 of the AI-ready rubric in 2.13, state the axis of your test set (time, space, composition) and report the validation and test scores side by side, as in the table above.
- Wiemer, S. (2000). Mapping and Removing Quarry Blast Events from Seismicity Catalogs. Bulletin of the Seismological Society of America, 90(2), 525–530. 10.1785/0119990104