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

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

3.2 Classification and regression

🖥️ Lecture slides: Session 12 (Mon Oct 26)

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

  1. 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;

  2. 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);

  3. 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;

  4. 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.

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.

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

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
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
Loading...

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
label
earthquake    10263
explosion      5128
<Figure size 1200x600 with 2 Axes>

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.

[H] not answered yet
[hour] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell

Your 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()).

[W] not answered yet
[work_share] using the reference result so the next cells run.
<Figure size 700x350 with 1 Axes>

Worked solution below (click ⋯ to open).

Notebook Cell
<Figure size 700x350 with 1 Axes>
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.

Loading...

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).

[B] not answered yet
[acc_base] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
baseline accuracy on validation: 0.681; recall: earthquake 1.0, explosion 0.0; balanced accuracy 0.5
Source

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] not answered yet
[val_scores, best_k] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
best k: 3  validation balanced accuracy: {1: 0.958, 3: 0.972, 9: 0.968, 27: 0.958, 81: 0.944}
<Figure size 600x320 with 1 Axes>

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).

[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
Source
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
<Figure size 860x380 with 2 Axes>

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].

[N] not answered yet
[y_pred_nohour] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
Source
Loading...

The 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
train 1642, validation 548, silica-rich test 2810
<Figure size 700x400 with 1 Axes>

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)).

[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

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
chosen on validation: linear
Loading...

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().

[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
Source
chosen model (linear): 100.0% of test predictions within 2.5-3.3 g/cm3
Loading...
<Figure size 1200x380 with 3 Axes>

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
Loading...

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.

References
  1. 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