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.11 Forests in practice

🖥️ Lecture slides, Session 17 (Fri Nov 6)

Forests are the default model for feature tables in the geosciences: snow instability in the Swiss Alps (Mayer et al., 2022), global soil maps (Poggio et al., 2021), seismic source types in the Pacific Northwest (Kharita et al., 2026). This notebook uses two data sets. For classes, the 4,000 Pacific Northwest seismic events of notebooks 3.3 and 3.5. For numbers, ten years of daily soil and air measurements at a U.S. Climate Reference Network station in eastern Washington.

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

  1. compute recall and false-positive rate at a threshold, and say how a ROC curve collects them;

  2. show that a full decision tree memorizes its training events, and that many trees do better on new ones;

  3. read a forest’s out-of-bag score as an estimate of its test score;

  4. show that one threshold means different things for two models with the same ROC curve;

  5. compare a regression forest with climatology and with yesterday’s value;

  6. explain why a copy of a feature changes its importance and not the error;

  7. say why a forest cannot predict beyond the range of its training values.

Time: about 35 minutes in pairs. If you run short, skip Parts 2 and 6.

How this notebook works

Each Your turn cell asks for a few lines of code. Read the hint, write your answer where the cell says, and run it. The cell below it holds a worked solution, hidden until you click ⋯. That hidden cell also checks your answer: it prints correct, or a hint, and if your answer is missing or different it uses the reference result so that the rest of the notebook still runs. Your own answer, if different, is kept under the same name followed by _yours.

The values below are used in several places, so they are defined once. The figure colors stay distinct for color-blind readers (the Okabe-Ito palette).

Notebook Cell

The seismic events

📍 In-situ sensor · 🪨 Solid Earth · 📈 Seismology

Each data sample is one seismic event recorded by the Pacific Northwest Seismic Network, described by 61 features computed from its waveform (Zenodo record 14025693). An analyst labeled each one as an earthquake, an explosion, a surface event or noise, with 1,000 of each. Keep in mind that this table has been balanced by selection, while the real stream has not. Kharita et al. (2026) show the map of these events and the larger study behind this table.

The next cell downloads the tables once and makes the canonical split of notebook 3.5: 3,000 events to train and 1,000 to test. It also makes the two-class version of Wednesday’s lecture, explosion against earthquake.

Four classes: 3000 training events, 1000 test events, 61 features
Two classes: 1500 training events, 500 test events

Part 1. A ROC curve from ten events

The table below holds ten real test events with the probability of explosion given by Wednesday’s logistic regression. They were chosen to include every kind of error, so the curve they give is worse than the model’s full curve.

On paper first, if you have not done it yet. Start at (0, 0) and go down the list: for an explosion move up 0.2; for an earthquake move right 0.2. Circle where you stand at thresholds 0.8, 0.5 and 0.2.

Loading...

Your turn (1): recall and false-positive rate at a threshold

Write a function rates(labels, probabilities, threshold) that returns two numbers: the recall (of the true explosions, the share with a probability at or above the threshold) and the false-positive rate (of the true earthquakes, the share at or above the threshold). labels holds 1 for explosion and 0 for earthquake; both inputs are arrays.

Hint: flagged = probabilities >= threshold, then flagged[labels == 1].mean() and flagged[labels == 0].mean().

Worked solution below (click ⋯ to open it).

Notebook Cell
rates: not answered yet. Hint: flagged = probabilities >= threshold; then the mean of flagged for each class.
  Using the reference result below.

Compare with your drawing: each threshold gives one confusion matrix, and so one point. Then see where the full curve of the same model lies, on all 500 test events.

threshold 0.8: recall 0.4, false-positive rate 0.0
threshold 0.5: recall 0.6, false-positive rate 0.2
threshold 0.2: recall 0.8, false-positive rate 0.4
AUC: ten events 0.76, all 500 test events 0.963
Notebook Cell
<Figure size 520x480 with 1 Axes>

Part 2. One tree (skip if short of time)

A tree asks a sequence of questions, each a threshold on one feature. Print a small one and read it aloud. Note the word: a split threshold acts on a feature, while the decision threshold of Part 1 acts on a probability.

|--- Kurto_3_10 <= 1.49
|   |--- Kurto_1_3 <= 2.54
|   |   |--- class: noise
|   |--- Kurto_1_3 >  2.54
|   |   |--- class: explosion
|--- Kurto_3_10 >  1.49
|   |--- DistMaxMedianFreqDTF <= 0.01
|   |   |--- class: earthquake
|   |--- DistMaxMedianFreqDTF >  0.01
|   |   |--- class: surface event

Your turn (2): how deep?

Fill depth_scores, a list with one row [depth, train_f1, test_f1] for each depth in DEPTHS. Fit a DecisionTreeClassifier(max_depth=depth, random_state=SEED) on X_train, y_train, and score it with the macro-F1 of Wednesday, once on the training events and once on the test events. None means no limit.

Hint: f1_score(y_train, tree.predict(X_train), average="macro").

Worked solution below (click ⋯ to open it).

Notebook Cell
depth_scores: not answered yet. Hint: fit one tree per depth; score train and test with average='macro'.
  Using the reference result below.
Loading...

Where do the two columns start to separate? The last row is a tree that has memorized its training events.

Part 3. Many trees

A forest trains each tree on a bootstrap of the events (drawn with replacement, about 37% left out each time) and offers each split a random subset of the features. Each event can then be scored by the trees that never saw it: the out-of-bag score, which spends no test event.

Your turn (3): fit a forest

Fit forest, a RandomForestClassifier(n_estimators=N_TREES, oob_score=True, random_state=SEED, n_jobs=-1) on the raw X_train, y_train: a forest needs no standardizing. Then compute forest_f1, its macro-F1 on the test events.

Hint: f1_score(y_test, forest.predict(X_test), average="macro"). The out-of-bag accuracy is stored in forest.oob_score_ after the fit.

Worked solution below (click ⋯ to open it).

Notebook Cell
forest: not answered yet. Hint: RandomForestClassifier(...).fit(X_train, y_train)
  Using the reference result below.
forest_f1: not answered yet. Hint: f1_score(y_test, forest.predict(X_test), average='macro')
  Using the reference result below.

Now the same split with logistic regression, with and without standardizing. The last model may warn that it did not converge: that is part of the result.

Forest, 300 trees:              macro-F1 0.885, out-of-bag accuracy 0.881
Logistic regression, standardized: macro-F1 0.884
Logistic regression, raw features: macro-F1 0.786
/home/runner/work/mlgeo-book/mlgeo-book/.pixi/envs/default/lib/python3.12/site-packages/sklearn/linear_model/_logistic.py:599: ConvergenceWarning: lbfgs failed to converge after 5000 iteration(s) (status=1):
STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT

Increase the number of iterations to improve the convergence (max_iter=5000).
You might also want to scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(

Part 4. One threshold, two models

A forest also gives a probability: the mean over its trees. Fit one on the two-class problem and compare it with logistic regression.

Your turn (4): the forest at three thresholds

Fit binary_forest as in Part 3 (without oob_score) on Xb_train, yb_train. Then compute p_forest, the probability of explosion for Xb_test, and forest_rates, the list of rates(labels_test, p_forest, t) for each t in THRESHOLDS.

Hint: binary_forest.predict_proba(Xb_test)[:, 1], then a list comprehension.

Worked solution below (click ⋯ to open it).

Notebook Cell
binary_forest: not answered yet. Hint: RandomForestClassifier(...).fit(Xb_train, yb_train)
  Using the reference result below.
p_forest: not answered yet. Hint: binary_forest.predict_proba(Xb_test)[:, 1]
  Using the reference result below.
forest_rates: not answered yet. Hint: [rates(labels_test, p_forest, t) for t in THRESHOLDS]
  Using the reference result below.
ROC AUC: logistic 0.963, forest 0.964
Loading...

The two models rank events about equally well, and still the same threshold gives different errors. Mayer et al. (2022) had to choose a threshold for their own forest for the same reason, and report that 0.71 and 0.5 gave the same accuracy with different errors.

For your project: where would you choose your threshold, and on which data?

Part 5. Numbers: soil moisture at Turnbull, Washington

📍 In-situ sensor · 💧 Land water · 💧 Hydrology & land-surface modeling

The U.S. Climate Reference Network station WA Spokane 17 SSW sits in Turnbull National Wildlife Refuge, in a dry-summer, cold-winter climate (Bell et al., 2013). You met it in Session 7. Rain and snowmelt fill the top of the soil; evaporation, roots and drainage empty it. Each data sample is one day, 2015 to 2024. The target is today’s soil moisture at 5 cm (m³/m³). The features are yesterday’s moisture at 5 and 10 cm, rain today and yesterday, air temperature and solar radiation.

A regression forest differs in one way: each leaf stores the mean of its training values, and the forest averages the leaves. We train on 2015 to 2020 and test on 2021 to 2024. Monday’s lecture explains why the split follows time here.

Keep in mind that days with a missing or frozen sensor are dropped, and most of those are in winter.

1630 training days, 1172 test days
Notebook Cell
<Figure size 1100x380 with 3 Axes>

Two baselines come first. Climatology is the mean for that day of the year over the training years, smoothed over 15 days. Yesterday’s value repeats the last measurement. A linear regression gives the third reference.

Your turn (5): does the forest beat them?

Fit soil_forest, a RandomForestRegressor(n_estimators=N_TREES, random_state=SEED, n_jobs=-1), on train[FEATURES] and train["moisture"]. Then compute p_soil, its predictions for test[FEATURES].

Hint: the same three lines as a classifier, with .predict.

Worked solution below (click ⋯ to open it).

Notebook Cell
soil_forest: not answered yet. Hint: RandomForestRegressor(...).fit(train[FEATURES], train['moisture'])
  Using the reference result below.
p_soil: not answered yet. Hint: soil_forest.predict(test[FEATURES])
  Using the reference result below.
Loading...

The error is the mean absolute error, in the units of the sensor. R² is the share of variance explained. Read the second row before the last: repeating yesterday’s value already reaches a very high R², because soil moisture changes slowly. A high R² on a slow variable says little until you compare it with persistence.

Part 6. A copy of a feature (skip if short of time)

Impurity importance measures how much each feature reduced the variance across all splits, on the training data. Yesterday’s moisture dominates. Now add the same column again, in percent. It holds no new information about the soil.

Your turn (6): where does the credit go?

Fit copy_forest with the same settings on train_copy (below), and store copy_importance, a pd.Series of its feature_importances_ with train_copy.columns as the index.

Hint: pd.Series(copy_forest.feature_importances_, index=train_copy.columns).

Worked solution below (click ⋯ to open it).

Notebook Cell
copy_forest: not answered yet. Hint: RandomForestRegressor(...).fit(train_copy, train['moisture'])
  Using the reference result below.
copy_importance: not answered yet. Hint: pd.Series(copy_forest.feature_importances_, index=train_copy.columns)
  Using the reference result below.
Error without the copy 0.0033, with the copy 0.0034 m3/m3
Loading...

The error did not change, and the credit split. Real features correlate the same way: moisture at 5 and 10 cm, temperature and solar radiation. Mayer et al. (2022) removed features correlated above r = 0.8 before reading their importance. Importance describes how this model used its inputs; it does not show cause.

Part 7. Outside the training range

A forest’s prediction is an average of training values. What happens on days hotter than any it has seen? Ground surface temperature follows air temperature closely (both from the same station), so this is a clean test. We train only on days with a maximum air temperature below 28 °C, keep a quarter of those days aside, and then predict the hot days. This is a designed test, as with the silica-rich rocks of notebook 3.2.

2301 days to fit, 767 cool days held out, 570 hot days

Your turn (7): a forest and a line

Fit hot_forest (same settings, on fit_days[["air"]] and fit_days["ground"]) and hot_line, a LinearRegression on the same data. Then fill hot_errors, a dictionary with the mean absolute error of each on the hot days: {"forest": ..., "line": ...}.

Hint: the double brackets keep air as a table with one column: hot_forest.predict(hot[["air"]]).

Worked solution below (click ⋯ to open it).

Notebook Cell
hot_forest: not answered yet. Hint: RandomForestRegressor(...).fit(fit_days[['air']], fit_days['ground'])
  Using the reference result below.
hot_line: not answered yet. Hint: LinearRegression().fit(fit_days[['air']], fit_days['ground'])
  Using the reference result below.
hot_errors: not answered yet. Hint: mean_absolute_error(hot['ground'], model.predict(hot[['air']])) for each model
  Using the reference result below.
Notebook Cell
Cool days held out: forest 4.1, line 4.0 °C
Hot days:           forest 7.9, line 4.0 °C
Largest value on hot days: observed 67.6, forest 45.5, line 70.8 °C
<Figure size 700x460 with 1 Axes>

On the cool days the two models tie, so a validation set drawn from those days could not separate them. Above 28 °C the forest’s curve goes flat. The line holds here only because this relation happens to be nearly straight: it would extrapolate just as confidently if the relation bent.

Pause and discuss

  1. In Part 4 the two models have nearly the same AUC. What would you need to know to choose one for an operational catalog?

  2. In Part 5, the forest beats yesterday’s value by about .0009 m³/m³. Is that gain worth having? What would you ask about the sensor?

  3. Your project: in which conditions will your model be used outside the range of its training data? How would you test that before someone relies on it?

Points to bring out
  1. Their costs: what a missed blast and a false alarm each cost, then a threshold chosen for each model on validation data. Also which features are available when the prediction is needed, how much preparation each model needs, and whether the probabilities are calibrated. The weights of logistic regression are simpler to read; a forest needs less preparation and held up better with few training events in the lecture’s test.

  2. Compare with the sensor’s own uncertainty and its use. The gain is small on average, and on rainy days the linear model does about as well. A simple model may be the better choice here, and that is a useful result.

  3. Answers will differ: another climate, volcano, sensor or network. The test is to hold out the conditions you expect, as Part 7 held out hot days, and as Monday’s robust training will do with time, groups and regions.

Summary

QuestionToolExampleResult on these data
Where does a ROC curve come from?one point per thresholdten seismic eventsAUC .76 by hand; .963 on 500 events
Why not one tree?training against test scorefour source typesmacro-F1 1.000 against .800
What do many trees add?bootstrap, random featuresfour source types.884 with 300 trees; logistic regression also .884
Do thresholds transfer?one threshold, two modelsexplosion or earthquake62 or 89 missed at 0.8
Did the forest learn anything?climatology, yesterday’s valueTurnbull soil moisture.0284, .0042, forest .0033 m³/m³
What does importance show?add a copy of a featureTurnbull soil moisture.99 splits into .53 and .46; same error
What happens outside training?hold out hot daysground surface temperatureforest error 4.1 to 7.9 °C; line 4.0

Next. Lessons 3.7 and 3.9 go further into partial dependence, boosting and stacking. Lesson 3.8 on Monday takes the train and test split itself as the question.

References

  • Bell, J. E., and others (2013). U.S. Climate Reference Network soil moisture and temperature observations. Journal of Hydrometeorology, 14, 977-988. Bell et al. (2013)

  • Breiman, L. (2001). Random forests. Machine Learning, 45, 5-32. Breiman (2001)

  • Kharita, A., Denolle, M., Hutko, A., Hartog, R., and Malone, S. (2026). Exploration of machine learning methods to seismic event discrimination in the Pacific Northwest. Seismica, 5(1). Kharita et al. (2026)

  • Mayer, S., van Herwijnen, A., Techel, F., and Schweizer, J. (2022). A random forest model to assess snow instability from simulated snow stratigraphy. The Cryosphere, 16, 4593-4615. Mayer et al. (2022)

  • Poggio, L., and others (2021). SoilGrids 2.0: producing soil information for the globe with quantified spatial uncertainty. SOIL, 7, 217-240. Poggio et al. (2021)

References
  1. Bell, J. E., Palecki, M. A., Baker, C. B., Collins, W. G., Lawrimore, J. H., Leeper, R. D., Hall, M. E., Kochendorfer, J., Meyers, T. P., Wilson, T., & Diamond, H. J. (2013). U.S. Climate Reference Network Soil Moisture and Temperature Observations. Journal of Hydrometeorology, 14(3), 977–988. 10.1175/jhm-d-12-0146.1
  2. Breiman, L. (2001). Random Forests. Machine Learning, 45(1), 5–32. 10.1023/a:1010933404324
  3. Kharita, A., Denolle, M., Hutko, A., Hartog, R., & Malone, S. (2026). Exploration of Machine Learning Methods to Seismic Event Discrimination in the Pacific Northwest. Seismica, 5(1). 10.26443/seismica.v5i1.2068
  4. Mayer, S., van Herwijnen, A., Techel, F., & Schweizer, J. (2022). A random forest model to assess snow instability from simulated snow stratigraphy. The Cryosphere, 16(11), 4593–4615. 10.5194/tc-16-4593-2022
  5. Poggio, L., de Sousa, L. M., Batjes, N. H., Heuvelink, G. B. M., Kempen, B., Ribeiro, E., & Rossiter, D. (2021). SoilGrids 2.0: producing soil information for the globe with quantified spatial uncertainty. SOIL, 7(1), 217–240. 10.5194/soil-7-217-2021