🖥️ 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:
write a small AutoML loop with scikit-learn;
show that the choice of validation can change the winner, and measure what that costs on a final test;
say why the best score of a search is optimistic;
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.
# Data handling
import hashlib
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
import pooch
# Plotting
import matplotlib.pyplot as plt
# Models, splits and scores (scikit-learn)
from sklearn.datasets import make_classification # synthetic stand-in if Zenodo cannot be reached
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestClassifier, RandomForestRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.metrics import f1_score, mean_absolute_error
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScalerThe 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).
SEED = 42
SPLIT_SEED = 2026 # the canonical split of notebook 3.5
BLUE, ORANGE, RED, MUTED = "#0072B2", "#E69F00", "#D55E00", "#6e675c"
plt.rcParams.update({"font.size": 12, "axes.spines.top": False, "axes.spines.right": False})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] = referenceNotebook Cell
SEISMIC_FILES = {
"1000_earthquakes_physical_features.csv": "md5:28129c8dd1b3e14f655d489577b841b5",
"1000_explosion_physical_features.csv": "md5:af1342d32e163e961e043364136359b0",
"1000_noise_physical_features.csv": "md5:16cdb992fed6cf6273d5624f5df905da",
"1000_surface_physical_features.csv": "md5:9a2c2643030cf058704d68e130654e9d",
}
try:
tables = [pd.read_csv(pooch.retrieve(url=f"https://zenodo.org/api/records/14025693/files/{name}/content",
known_hash=checksum, fname=name, path=pooch.os_cache("mlgeo")), index_col=0)
for name, checksum in SEISMIC_FILES.items()]
seismic = pd.concat(tables, ignore_index=True).dropna(axis=1)
X = seismic.drop(columns=["source", "serial_no"])
y = seismic["source"]
except Exception as error:
print(f"Zenodo could not be reached ({error}). Using SYNTHETIC events: the scores below will differ from the text.")
values, codes = make_classification(n_samples=4000, n_features=61, n_informative=20, n_classes=4, random_state=SEED)
X = pd.DataFrame(values, columns=[f"feature_{i}" for i in range(61)])
y = pd.Series(np.array(["earthquake", "explosion", "noise", "surface event"])[codes])
seismic = X.assign(source=y.to_numpy(), serial_no=np.arange(len(y)))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=SPLIT_SEED, stratify=y)
truth = y_test.to_numpy()
macro = lambda a, b: f1_score(a, b, average="macro")
print(f"{len(X_train)} training events, {len(X_test)} test events, {X.shape[1]} waveform features")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
course_path = Path("../Chapter1-GettingStarted/data/gps_P395_relative_position.csv")
if not course_path.exists():
course_path = Path("gps_P395_relative_position.csv")
if not course_path.exists():
urllib.request.urlretrieve("https://raw.githubusercontent.com/geo-smart/mlgeo-book/main/book/Chapter1-GettingStarted/data/gps_P395_relative_position.csv", course_path)
if hashlib.sha256(course_path.read_bytes()).hexdigest() != "eb22473bbc5565caafbfe1b3b539c65cf88ba3cb23dec07106d81738957a4ff6":
raise ValueError(f"{course_path} is not the course copy. Delete it, or restore it with git, and run this cell again.")
gnss = pd.read_csv(course_path)
east = gnss["east_m"].to_numpy() * 1000 # mm, relative to the first day
year = gnss["decimal_year"].to_numpy()
history, horizon, stride = 60, 30, 5
rows = []
for i in range(history, len(east) - horizon, stride):
past = east[i - history:i]
rows.append({"mean_60d": past.mean(), "mean_10d": east[i - 10:i].mean(), "last": east[i - 1],
"slope_60d": np.polyfit(np.arange(history), past, 1)[0],
"season_sin": np.sin(2 * np.pi * year[i]), "season_cos": np.cos(2 * np.pi * year[i]),
"target": east[i:i + horizon].mean(), "year": year[i]})
samples = pd.DataFrame(rows)
FEATURES = ["mean_60d", "mean_10d", "last", "slope_60d", "season_sin", "season_cos"]
X_time, y_time = samples[FEATURES].to_numpy(), samples["target"].to_numpy()
last_value = samples["last"].to_numpy()
GAP = horizon // stride # samples left out between training and validation, so target windows do not overlap
print(f"{len(samples)} samples, {X_time.shape[1]} features")
cut = int(0.8 * len(X_time))
X_search, y_search = X_time[:cut], y_time[:cut]
X_final, y_final = X_time[cut + GAP:], y_time[cut + GAP:]
print(f"{len(X_search)} samples to search on, {len(X_final)} for the final test")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.
candidates = {"Linear": LinearRegression(),
"Ridge": make_pipeline(StandardScaler(), Ridge(alpha=10.0)),
"Nearest 3": make_pipeline(StandardScaler(), KNeighborsRegressor(3)),
"Nearest 30": make_pipeline(StandardScaler(), KNeighborsRegressor(30)),
"Forest": RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1),
"Forest, leaf 20": RandomForestRegressor(n_estimators=100, min_samples_leaf=20, random_state=SEED, n_jobs=-1),
"Boosted": HistGradientBoostingRegressor(random_state=SEED),
"Boosted, slow": HistGradientBoostingRegressor(learning_rate=0.03, random_state=SEED)}
shuffled = KFold(n_splits=5, shuffle=True, random_state=SEED)
future = TimeSeriesSplit(n_splits=5, gap=GAP)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()mini_automl = None # replace this line with your function: def mini_automl(candidates, X, y, cv): ...Worked solution below (click ⋯ to open it).
Notebook Cell
def mini_automl_sol(candidates, X, y, cv):
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()
check("mini_automl", globals(), mini_automl_sol, "loop over candidates.items(), score each with cross_val_score, return a sorted Series.",
measure=lambda f: f({"Linear": LinearRegression(), "Ridge": candidates["Ridge"]}, X_search, y_search, shuffled).to_numpy())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.
ranking_shuffled = None # replace None with your expression
ranking_future = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
# Check each ranking without running the search again: all candidates present, sorted from best to worst,
# and the cheap linear model scored with the right folds. The full search runs only if the answer is missing or wrong.
def check_ranking(name, cv, hint):
yours = globals().get(name)
try:
linear = -cross_val_score(candidates["Linear"], X_search, y_search, cv=cv, scoring="neg_mean_absolute_error").mean()
ok = sorted(yours.index) == sorted(candidates) and yours.is_monotonic_increasing and abs(yours["Linear"] - linear) < 0.01
except Exception:
ok = False
if ok:
print(f"{name}: correct")
else:
check(name, globals(), mini_automl(candidates, X_search, y_search, cv), hint, measure=lambda s: s.sort_index().to_numpy(), tol=0.01)
check_ranking("ranking_shuffled", shuffled, "mini_automl(candidates, X_search, y_search, shuffled)")
check_ranking("ranking_future", future, "mini_automl(candidates, X_search, y_search, future)")
pd.DataFrame({"shuffled folds (mm)": ranking_shuffled, "future folds (mm)": ranking_future}).sort_values("shuffled folds (mm)").round(2)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.
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)).
final_shuffled = None # replace None with your expression
final_future = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
final_shuffled_sol = mean_absolute_error(y_final, candidates[ranking_shuffled.index[0]].fit(X_search, y_search).predict(X_final))
final_future_sol = mean_absolute_error(y_final, candidates[ranking_future.index[0]].fit(X_search, y_search).predict(X_final))
check("final_shuffled", globals(), final_shuffled_sol, "take the first name in ranking_shuffled, fit that candidate, score it on the final samples.", tol=0.01)
check("final_future", globals(), final_future_sol, "take the first name in ranking_future, fit that candidate, score it on the final samples.", tol=0.01)
print(f"Winner on shuffled folds: {ranking_shuffled.index[0]}, final test {final_shuffled:.2f} mm")
print(f"Winner on future folds: {ranking_future.index[0]}, final test {final_future:.2f} mm")
print(f"Persistence, final test: {mean_absolute_error(y_final, X_final[:, FEATURES.index('last')]):.2f} mm")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.
few = np.random.default_rng(1).choice(len(X_train), 300, replace=False)
X_few, y_few = X_train.iloc[few], y_train.iloc[few]
draw = np.random.default_rng(SEED)
tried = []
for _ in range(30):
kind = draw.choice(["logistic", "forest", "nearest"])
if kind == "logistic":
model = make_pipeline(StandardScaler(), LogisticRegression(C=10 ** draw.uniform(-3, 2), max_iter=5000))
elif kind == "forest":
model = RandomForestClassifier(n_estimators=100, min_samples_leaf=int(draw.choice([1, 2, 5, 10, 20])),
max_features=float(draw.choice([0.1, 0.33, 1.0])), random_state=SEED, n_jobs=-1)
else:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(int(draw.choice([1, 3, 5, 10, 20, 40]))))
tried.append({"kind": kind, "cv": cross_val_score(model, X_few, y_few, cv=5, scoring="f1_macro").mean(),
"test": macro(y_test, model.fit(X_few, y_few).predict(X_test))})
tried = pd.DataFrame(tried).sort_values("cv", ascending=False)
tried.head(5).round(3)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.
# --- AI-generated modeling script: do NOT trust it yet ---
two_labels = seismic[seismic["source"] != "surface event"] # remove noisy labels
features = StandardScaler().fit_transform(two_labels.drop(columns=["source", "serial_no"])) # normalize features
a_train, a_test, b_train, b_test = train_test_split(features, two_labels["source"], test_size=0.25, random_state=7)
best_name, best_score = None, -1.0
for name, model in {"logistic_regression": LogisticRegression(max_iter=5000),
"random_forest": RandomForestClassifier(n_estimators=100, random_state=7, n_jobs=-1)}.items():
model.fit(a_train, b_train)
score = model.score(a_train, b_train) # evaluate each candidate
print(f"{name}: accuracy = {score:.3f}")
if score > best_score:
best_name, best_score = name, score
print(f"best model: {best_name}, accuracy = {best_score:.3f}")logistic_regression: accuracy = 0.915
random_forest: accuracy = 1.000
best model: random_forest, accuracy = 1.000
The three flaws
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.The scaler is fit before the split.
fit_transformon 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.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)).
fair_cv = None # replace None with your expression
fair_test = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
pipeline_sol = make_pipeline(StandardScaler(), RandomForestClassifier(n_estimators=100, random_state=7, n_jobs=-1))
fair_cv_sol = cross_val_score(pipeline_sol, X_train, y_train, cv=5, scoring="f1_macro").mean()
fair_test_sol = macro(y_test, pipeline_sol.fit(X_train, y_train).predict(X_test))
check("fair_cv", globals(), fair_cv_sol, "use cross_val_score on X_train, y_train with scoring='f1_macro'.", tol=0.01)
check("fair_test", globals(), fair_test_sol, "fit the pipeline on all of X_train, then score on X_test.", tol=0.01)
print(f"Agent's script: accuracy 1.000 on three classes, on data it had seen")
print(f"Repaired: macro-F1 {fair_cv:.3f} in cross-validation, {fair_test:.3f} on test, four classes (always guessing one class: 0.10)")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.