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.10 AutoML: a search is only as good as its score

🖥️ Lecture slides, Session 18 (Mon Nov 9)

Automated machine learning (AutoML) tools such as H2O AutoML, AutoGluon and auto-sklearn automate the middle of a project: try many model families and settings, score each one, keep the best, often stack the winners. Underneath is a loop short enough to write yourself, so this notebook needs only scikit-learn. Earlier editions of this chapter taught pycaret and Optuna. Writing the loop by hand shows what those packages cannot do for you: they rank models by whatever score you give them.

Lee et al. (2023, Remote Sensing) show why that matters. AutoML beat a random forest for daily soil moisture in South Korea under random sampling (error 2.21% against 2.71%). When whole years were held out, the two tied (4.13% against 4.10%).

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

  1. write a small AutoML loop with scikit-learn;

  2. show that the choice of validation can change the winner, and measure what that costs on a final test;

  3. say why the best score of a search is optimistic;

  4. audit a modeling script written by an AI agent, and repair it.

Time: about 20 minutes in pairs. If you run short, skip Part 2.

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
Notebook Cell
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_earthquakes_physical_features.csv/content' to file '/home/runner/.cache/mlgeo/1000_earthquakes_physical_features.csv'.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_explosion_physical_features.csv/content' to file '/home/runner/.cache/mlgeo/1000_explosion_physical_features.csv'.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_noise_physical_features.csv/content' to file '/home/runner/.cache/mlgeo/1000_noise_physical_features.csv'.
Downloading data from 'https://zenodo.org/api/records/14025693/files/1000_surface_physical_features.csv/content' to file '/home/runner/.cache/mlgeo/1000_surface_physical_features.csv'.
3000 training events, 1000 test events, 61 waveform features

Part 1. A small AutoML, by hand

Data: 📍 In-situ sensor · 🪨 Solid Earth · 📐 Geodesy

We reuse the forecast of 3.8: GNSS station P395 in the Oregon Coast Range, 60 days of east position predicting the mean of the next 30 days. The search sees the first 80% of the record. The last 20% stays out for one final test.

Notebook Cell
1482 samples, 6 features
1185 samples to search on, 291 for the final test

These are the candidates: model families and settings an AutoML tool would try.

Your turn (1): the loop

Write mini_automl(candidates, X, y, cv). For each candidate, compute the cross-validated mean absolute error, then return a pandas Series of errors sorted from best to worst.

Hint:

scores = {}
for name, model in candidates.items():
    scores[name] = -cross_val_score(model, X, y, cv=cv, scoring="neg_mean_absolute_error").mean()
return pd.Series(scores).sort_values()

Worked solution below (click ⋯ to open it).

Notebook Cell
mini_automl: not answered yet. Hint: loop over candidates.items(), score each with cross_val_score, return a sorted Series.
  Using the reference result below.

Your turn (2): run the search twice

Fill ranking_shuffled with your function on X_search, y_search with cv=shuffled, and ranking_future with cv=future. Before you run it, write down which model you expect to win each one. It takes about 20 seconds.

Worked solution below (click ⋯ to open it).

Notebook Cell
ranking_shuffled: not answered yet. Hint: mini_automl(candidates, X_search, y_search, shuffled)
  Using the reference result below.
ranking_future: not answered yet. Hint: mini_automl(candidates, X_search, y_search, future)
  Using the reference result below.
Loading...

Your turn (3): the final test, once

Each search names a winner. Fit each winner on X_search, y_search and compute its mean absolute error on X_final, y_final: final_shuffled for the winner on shuffled folds, final_future for the winner on future folds.

Hint: ranking_shuffled.index[0] is the name of the winner, and candidates[name] is the model. Then mean_absolute_error(y_final, model.fit(X_search, y_search).predict(X_final)).

Worked solution below (click ⋯ to open it).

Notebook Cell
final_shuffled: not answered yet. Hint: take the first name in ranking_shuffled, fit that candidate, score it on the final samples.
  Using the reference result below.
final_future: not answered yet. Hint: take the first name in ranking_future, fit that candidate, score it on the final samples.
  Using the reference result below.
Winner on shuffled folds: Forest, final test 13.36 mm
Winner on future folds:   Linear, final test 0.74 mm
Persistence, final test:  1.12 mm

Pause and discuss.

  • The same loop, same candidates and same data chose two different models. What did the loop change?

  • Lee et al. (2023) found AutoML ahead under random sampling and tied when whole years were held out. Which comparison matches daily soil moisture for next year?

  • What would you ask of a paper that reports “the best of 20 models selected by AutoML”?

Points to bring out

Only the validation changed. A search rewards whatever the score rewards, and shuffled folds reward copying neighbors, which forests do well. Then ask of the paper: what was held out, what baseline did the winner beat, and was the reported score used to choose the winner? Packages save time on the loop. They do not know how your model will be used.

Part 2. Searching settings, and why the best score is optimistic

The loop extends to settings: draw a model at random, score it, keep the best. scikit-learn’s GridSearchCV and RandomizedSearchCV do the same with less typing. Libraries such as Optuna draw new settings near the ones that scored well, which saves time when each fit takes hours, and they optimize the same score.

The more candidates a search tries, the more likely its best score is partly luck. To make that visible, this search uses only 300 of the seismic training events from 3.5, and it also records the test score of each candidate, which we would never use in a real search. It takes about 30 seconds.

Loading...

Read the table. Compare the top cv value with the test value on the same row. The gap is the optimism of the search, and the top row is often not the best on test. Report the test score of the winner, measured once, and never the search’s best score.

Part 3. Audit a script written by an agent

Today much of the search is written by a coding agent rather than a package. Below is the kind of script an agent will produce when asked to “find the best model for this seismic table”. It runs, and it prints a strong score.

logistic_regression: accuracy = 0.915
random_forest: accuracy = 1.000
best model: random_forest, accuracy = 1.000
The three flaws
  1. A class is dropped. seismic["source"] != "surface event" removes one of the four source types under a comment about noisy labels. The score now describes an easier problem, and the model can never predict a surface event.

  2. The scaler is fit before the split. fit_transform on all samples uses the test events to compute means and variances. The effect is small here, but with imputation or target encoding it can be large.

  3. Models are chosen on training accuracy. model.score(a_train, b_train) rewards memorization: a forest reaches 1.000 on data it has seen.

Warning signs: a near-perfect score, no baseline, no held-out score.

Your turn (4): repair it

Put the scaler inside a pipeline and use the canonical split with all four classes. Compute fair_cv, the 5-fold cross-validated macro-F1 of the forest on X_train, y_train. Then compute fair_test, its macro-F1 on the test events, once.

Hint: pipeline = make_pipeline(StandardScaler(), RandomForestClassifier(n_estimators=100, random_state=7, n_jobs=-1)), then cross_val_score(pipeline, X_train, y_train, cv=5, scoring="f1_macro").mean(), then macro(y_test, pipeline.fit(X_train, y_train).predict(X_test)).

Worked solution below (click ⋯ to open it).

Notebook Cell
fair_cv: not answered yet. Hint: use cross_val_score on X_train, y_train with scoring='f1_macro'.
  Using the reference result below.
fair_test: not answered yet. Hint: fit the pipeline on all of X_train, then score on X_test.
  Using the reference result below.
Agent's script: accuracy 1.000 on three classes, on data it had seen
Repaired: macro-F1 0.872 in cross-validation, 0.889 on test, four classes (always guessing one class: 0.10)

If you have time: try it with your own agent. Ask a coding agent for a short AutoML using scikit-learn only, on your project’s data or on P395. Then check its answer against this list: what does it hold out, what baseline does it report, is the scaler fit on training folds only, is the test set used once? Bring what you find to Friday’s class on evaluating agents (6.3).

What to keep

Automation moved from search packages to agents that write the whole pipeline on request. The checks stayed the same: a baseline, a split that matches how the model will be used, cross-validation inside the training data, and one look at a held-out test. Automate the search, and check the result yourself.