How to measure what a model will really do on the next new material, and the many ways a good-looking score can lie.
Undergraduate course · 16 weeks
Recap of lecture 5 · what it left open
We built classifiers. Can we trust their scores?
Logistic regressionp = σ(wᵀx), cross-entropy loss
→
Trees and forestsGini splits, bagging, boosting
→
Metricsconfusion matrix, precision, recall, ROC
→
TodayIs the score honest?
Open question 1 · one split
Every score so far came from one random train/test split. A different split gives a different number. How large is that luck, and how do we average it out?
Open question 2 · the stability classifier
Only about one compound in ten, often fewer, has Ehull < 25 meV/atom, and databases list the same compound and its polymorphs many times. Both can make a weak model look excellent.
A score is only as honest as the split, the tuning and the labels that produced it.
Why questions · answered at the end
Four puzzles for today
WHY 1
Why does trying fifty model settings and reporting the best cross-validation score make the model look better than it is?
WHY 2
Why can a model score a tiny error on a random split, then fail on the first compound from a new chemical family?
WHY 3
A 5-fold CV of 50 compounds, 5 of them stable, often cannot even compute a recall. Why, and what fixes it?
WHY 4
Why can no amount of cross-validation reveal that a band-gap model is 2 eV wrong?
Motivation · a test score is a measurement
One random split is a noisy measurement of the error
The experiment (simulated data)
40 band gaps simulated from Eg = 0.6 + 2.6 Δχ with 0.6 eV noise. Fit the line on 32, test on 8. Repeat with 2000 different random splits of the same 40 materials.
estimate
middle 95 % of results
one 32 / 8 split
0.24 – 0.67 eV
5-fold cross-validation
0.43 – 0.48 eV
What this tells us
With 8 test materials, the luck of the split moves the score by almost a factor of three. Testing every material once and averaging removes most of that luck.
Math primer · averages, spread, and the winner of a noisy contest
Three facts about noisy numbers
1
Mean and sample standard deviation of k scores \(E_1,\dots,E_k\):\[ \bar E = \frac1k\sum_{j=1}^{k} E_j, \qquad s = \sqrt{\frac{1}{k-1}\sum_{j=1}^{k}(E_j-\bar E)^2} \]
Divide by k − 1: the deviations are measured from Ē, which was fitted to the same numbers.
2
Standard error of the mean: for k independent scores,\[ \operatorname{Var}(\bar E) = \frac{1}{k^2}\sum_j \operatorname{Var}(E_j) = \frac{\sigma^2}{k} \;\Rightarrow\; \text{SE} = \frac{s}{\sqrt k} \]
Averaging k scores shrinks the spread by √k, not by k.
3
The minimum of m noisy scores is biased low. If every candidate has true error E* and each estimate has noise of spread σe:\[ \mathbb{E}\big[\min_{i\le m} \hat E_i\big] \approx E^* - c_m\,\sigma_e \]
cm = expected largest of m standard normal numbers (table).
candidates m
cm
1
0
2
0.56
5
1.16
20
1.87
50
2.25
100
2.51
What this tells us
Even if all 50 candidates are equally good, the best-looking one scores about 2.25 noise widths too well. The winner of a noisy contest is usually lucky.
Derivation · k-fold cross-validation
Use every material for testing, exactly once
1
Shuffle and cut the n materials into k folds of about n/k each.
Each fold will play the test set once.
2
For j = 1 … k: train on the other k − 1 folds, compute the error Ej on fold j.
The model that scores fold j has never seen fold j.
3
Average (weight by fold size nj if folds differ):\[ E_{\text{CV}} = \sum_{j=1}^{k} \frac{n_j}{n}\,E_j \]
Every material contributes to the estimate exactly once.
4
Report the spread: \(E_{\text{CV}} \pm s/\sqrt{k}\).
Rough: folds share training data, so the true uncertainty is somewhat larger.
✓
Sanity check: k = n gives leave-one-out (n fits); k = 2 trains on only half the data, so the error is pessimistic. k = 5 or 10 is the usual compromise.
What the estimate measures
Cross-validation scores the recipe (features, scaling, model, settings), not one fitted model. Afterwards we refit the recipe on all n materials. So every step that learns from data must run inside each training fold.
Worked problem 1 · by hand
A 5-fold estimate, its spread, and a fair comparison
fold
model A MAE (eV)
model B MAE (eV)
1
0.31
0.35
2
0.45
0.40
3
0.28
0.30
4
0.52
0.47
5
0.39
0.33
Equal folds of 10 band gaps each; both models scored on the same five folds.
Check and meaning
Compare fold by fold: the differences A − B have mean 0.02 eV and standard error 0.021 eV, so the gap is about one standard error. B wins on only 3 of 5 folds. The data do not show that B is better.
1
Mean of A:\[ \bar E_A = \frac{0.31+0.45+0.28+0.52+0.39}{5} = \frac{1.95}{5} = 0.39\ \text{eV} \]
2
Spread: deviations −0.08, 0.06, −0.11, 0.13, 0.00; squares sum to 0.0390.\[ s = \sqrt{0.0390/4} = \sqrt{0.00975} = 0.099\ \text{eV} \]
Divide by k − 1 = 4, as in the primer.
3
Standard error: \(0.099/\sqrt5 = 0.044\), so report \(E_A = 0.39 \pm 0.04\) eV.
4
Model B the same way: sum 1.85, mean 0.37, s = 0.067, SE = 0.03 → \(0.37 \pm 0.03\) eV.
Compare the difference with the spread before declaring a winner.
Hyperparameter tuning · choosing λ by cross-validation
Hyperparameters are chosen by validation, not by training
Simulated: 20 In1−xGaxAs band gaps (bowing law of lecture 1, 0.05 eV noise); degree-9 polynomial + ridge penalty λ; 5-fold CV for 37 values of λ.
5-fold CV RMSERMSE on 20 000 fresh points
1
For each λ on a grid, run k-fold CV on the training data (the same recipe chooses a tree depth).
2
Choose the lowest CV error; refit on all training data.
3
Score once on a test set that played no part.
Notice
best λ ≈ 0.06: CV RMSE 0.055 eV, but 0.071 eV on fresh data.
Hyperparameter tuning · the optimistic bias
The more settings you try, the more the best CV score lies
Simulation (300 repeats)
40 samples, 30 candidate descriptors, only two matter; noise σ = 1. Each candidate model = least squares on 5 random descriptors. Pick the one with the best 5-fold CV score among m candidates; then measure its error on 20 000 fresh samples.
m = 50 candidates
RMSE
best CV score (what you would report)
1.03
true error of the chosen model
1.21
What the selection learned
Part of "best" is real, part is the luck of these 40 samples (primer fact 3). The reported score was too low in 86 % of the repeats.
The fix · nested cross-validation
Tune inside, test outside
simulation, m = 50
RMSE
best inner CV score (optimistic)
1.03
nested CV estimate
1.26
true error of the tuned model (same 150 repeats)
1.20
1
Outer loop: hold out outer fold j as a test set.
It must never influence any choice.
2
Inner loop: on the remaining data only, run k-fold CV for every candidate and pick the best.
All tuning sees inner data only.
3
Refit and score once: train the chosen candidate on the outer training data, compute Ej on fold j.
The winner's luck cannot help on data it did not compete on.
4
Average Ej over the outer folds. Cost: 5 × 5 × 50 = 1250 fits here.
Estimates the whole procedure, tuning included.
Check
Nested CV gives 1.26, slightly pessimistic (it trains on 32 of 40), close to the true 1.20. The plain tuned score, 1.03, was 0.17 too low.
Splitting by family · group and leave-cluster-out CV
Materials come in families, so split by family
What counts as one group
• all entries of one composition (the same compound from several sources) • one chemical system or family (Li–Co–O, or LiCoO₂ and LiCo0.9Ni0.1O₂) • one structure prototype (all perovskites, all spinels): leave-cluster-out CV
Anatase, TiO₂. Didier Descouens, CC BY-SA 4.0Rutile, TiO₂. Rob Lavinsky, iRocks.com, CC BY-SA 3.0
Why it matters
Anatase and rutile are different materials, so both stay in the data. But they share chemistry, so a model that has seen one will find the other easy. Put the whole family on the same side of every split.
Materials example · a duplicate-rich dataset (simulated)
Random splits reward memory; group splits test discovery
Simulated formation energies
30 composition families × 4 near-duplicate entries = 120 rows, 6 descriptors. Each family has a hidden offset (spread 0.25 eV/atom) the descriptors cannot explain. 5-fold CV, averaged over 20 shuffles.
random 5-foldgroup 5-fold2000 new families
What the model learned
The 1-nearest-neighbour model learned a lookup table: copy the label of the sibling. Under a random split it looks 3 × better than the linear model; on new families it is worse than the linear model, about as bad as the mean. The group split predicted this; the random split did not.
Data leakage · four ways the test set gets contaminated
Leakage: information from the test set reaches the model
type
materials example
fix
Duplicates
ZnO from a handbook in training, ZnO from a review paper in the test set
merge duplicates before splitting
Families and polymorphs
rutile TiO₂ in training, anatase TiO₂ in test; LiCoO₂ in training, LiCo0.9Ni0.1O₂ in test
group split by composition, system or prototype
Preprocessing before the split
scaling, filling missing values or selecting features with statistics of the whole dataset
fit every step on training folds only (a pipeline)
Target leakage
predicting yield strength with Vickers hardness measured on the same sample; predicting a band gap with the measured absorption edge
ask: would I have this feature before the measurement?
A leak never shows up as an error. It shows up as a score that is too good, which is why nobody goes looking for it.
Worked problem 2 · by hand · spot the leaks
A band-gap study with four leaks. Find them.
#
compound
structure
Δχ
source
split
1
ZnO
wurtzite
1.79
handbook
train
2
GaN
wurtzite
1.23
handbook
train
3
TiO₂
rutile
1.90
handbook
train
4
Si
diamond
0.00
handbook
train
5
ZnO
wurtzite
1.79
review
test
6
TiO₂
anatase
1.90
handbook
test
7
GaAs
zinc blende
0.37
handbook
test
8
MgO
rock salt
2.13
handbook
test
Pipeline: (a) Δχ standardized with the mean and SD of all 8 rows; (b) a second feature, the optical absorption edge measured on each sample.
Row 6 is a polymorph of row 3: family leak. 2 of 4 test rows are compromised: 50 %.
Only GaAs and MgO test real generalization.
3
Scaling: training mean (1.79 + 1.23 + 1.90 + 0) / 4 = 1.23; mean of all 8 rows 11.11 / 8 = 1.39. Preprocessing leak: test rows moved the scale.
Fix: compute 1.23 from the training rows only.
4
Absorption edge is essentially the band gap measured another way: target leak.
Drop it; it is unknown for a material not yet made.
Interpolation versus extrapolation
Random CV tests interpolation, not discovery
true curvestraight line3-nearest neighbours
MAE
inside (x < 0.6)
outside (x > 0.75)
straight line
0.06
0.73
3-nearest neighbours
0.05
1.67
What the model learned
Nearest neighbours and tree ensembles average training labels, so they can never predict above the largest one they saw (here about 3.2). A record-breaking material is, by definition, outside the training range.
Test what you will do: hold out the top 10 % of y, a later year, or a new family, not a random 20 %.
Class imbalance · stratified splits and balanced metrics
In that fold recall cannot even be computed. A stratified split puts exactly one stable compound in each fold.
What to report
For rare classes: recall, precision, F1 or balanced accuracy, plus the class counts. Stratify the folds by class (and, if needed, group them by family as well).
Baselines and benchmarks
Three baselines, three different questions
1
Dummy: predict the training mean (or the majority class).
Is there any signal in the features at all?
2
Linear (ridge, logistic): few weights, no memory.
Does a flexible model really need its flexibility?
3
Nearest neighbour: copy the label of the most similar training material.
Is the test just a look-up? If 1-NN rivals your model, suspect near-duplicates.
slide-12 data, group 5-fold
MAE (eV/atom)
dummy (mean)
0.42
linear (ridge)
0.27
1-nearest neighbour
0.44
The Matbench idea
A fixed set of materials tasks (13 in the first version, from about 300 to about 130 000 entries: formation energies, band gaps, moduli, steel yield strength, glass formation …), each with fixed nested 5-fold splits and a dummy baseline. Everybody is scored the same way, so numbers can be compared.
What a baseline tells us
A score means nothing alone. "MAE 0.27 eV/atom" is good only next to 0.42 for the mean, on the same honest split.
Data quality · validation cannot see label bias
CV compares predictions with labels, not with reality
The label is biased, not noisy
PBE gaps of these six materials are 25–80 % too small; mean absolute difference from experiment 2.18 eV. A model with perfect CV error on PBE labels is still about 2 eV off the measured gaps.
Learn a correction, validate it honestly
Fit measured ≈ 1.22 + 1.35 × PBE on the six: training MAE 0.76 eV, but leave-one-out MAE 1.17 eV. Six points give a rough correction only.
What the model learned
It learned the labels, PBE included. Validation tells you how well; only an independent check against measurements tells you whether the labels are right.
Reporting checklist and FAIR data
What an honest result must state
1
Data: source, label type (computed or measured), size, cleaning log, duplicates removed.
2
Split: random, stratified, grouped (by what?) or by time; k; all preprocessing inside the folds.
3
Tuning: how many settings were tried; nested CV or a test set used once.
4
Scores: mean ± spread, a metric that fits the task, next to dummy, linear and nearest-neighbour baselines.
5
Domain: where the model may be used (interpolation range, families seen); an extrapolation test if discovery is the goal.
Findable
a persistent identifier (DOI) and rich metadata
Accessible
retrievable by a standard, open protocol
Interoperable
standard formats and units (CIF, eV/atom)
Reusable
licence, provenance: how each value was made
Servers at the NERSC supercomputing centre. Derrick Coetzee, CC0
Lab 6 · this week in Colab
Random, grouped and nested CV in scikit-learn
import numpy as np
from sklearn.model_selection import (KFold, GroupKFold,
GridSearchCV, cross_val_score)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridgemodel = make_pipeline(StandardScaler(), Ridge()) # scaled per fold
groups = df["chemsys"].values # e.g. "Li-Co-O"for cv in [KFold(5, shuffle=True, random_state=0), GroupKFold(5)]:
mae = -cross_val_score(model, X, y, groups=groups, cv=cv,
scoring="neg_mean_absolute_error")
print(type(cv).__name__, mae.mean(), mae.std())grid = {"ridge__alpha": np.logspace(-4, 2, 13)}
errs = []
for tr, te in GroupKFold(5).split(X, y, groups): # outer loop
gs = GridSearchCV(model, grid, cv=GroupKFold(5), # inner loop
scoring="neg_mean_absolute_error")
gs.fit(X[tr], y[tr], groups=groups[tr])
errs.append(np.abs(gs.predict(X[te]) - y[te]).mean())
print("nested MAE:", np.mean(errs))
Exercises
Formation energies: random vs grouped 5-fold MAE for ridge and a random forest. Which gains most from leakage?
Report the best GridSearchCV score and the nested score. How large is the optimism?
Hold out the 10 % most negative formation energies. What happens?
Runs in Google Colab; no GPU needed. Data file and notebook are posted with this lecture.
Answers to the why questions
The four puzzles, solved
1 · Tuning flatters the model
The best of 50 noisy CV scores is partly luck: 1.03 reported versus 1.21 true in our simulation. Report a nested CV score, or a test set used once.
2 · Tiny error, new family fails
Near-duplicates and polymorphs sit on both sides of a random split, so a look-up model scores 0.06 eV/atom. Grouped by family it scores 0.44, close to the 0.42 on truly new families.
3 · No recall in some folds
With a random 5-fold split, the chance that some fold has no stable compound is 95 %: recall is undefined there. Stratified folds put one stable compound in each fold; report recall, F1 or balanced accuracy.
4 · CV cannot see a 2 eV error
CV compares predictions with the labels. If the labels are PBE gaps, about 2.2 eV too low here, a perfect CV score inherits the bias. Check against measurements.
Check your understanding · click a card to reveal
Concept check
Q1. You try 200 descriptor sets and report the best 5-fold CV MAE, 0.08 eV/atom. Why is this too good, and what should you report?
The minimum of 200 noisy scores is biased low. Report a nested CV score, or the score on a test set used only once.
Q2. Your data hold 12 LiFePO₄ entries from different papers. Random CV gives a tiny error. Which split?
A group split by composition (or chemical system), so all 12 entries fall on the same side; merge true duplicates first.
Q3. 2 % of your compounds are superconductors. A model has 98 % accuracy. Is it useful?
Not necessarily: "never superconducting" also scores 98 %. Check recall, precision, F1 or balanced accuracy, with stratified folds.
Q4. To predict the hardness of new alloys, you use as a feature the indentation modulus measured in the same nanoindentation test. Leak? Fix?
Target leakage: the feature is measured together with the target and is unknown for an alloy not yet made. Drop it; use only features available before the measurement.
Wrap-up
Summary and next lecture
1
A test score is a noisy measurement. k-fold CV tests every material once; report the mean ± s/√k.
2
The best of many tuned CV scores is optimistic. Tune inside, test outside: nested CV.
3
Materials come in families: split by composition, system or prototype. Random splits reward memory.
4
Leaks: duplicates, families, preprocessing before the split, target leakage. They show up as scores that are too good.
5
Match the test to the use: extrapolation tests, stratified folds and balanced metrics, baselines, and labels checked against measurements.
This week
Lab 6: random, grouped and nested CV. Problem set 2 (weeks 4–6) is out today, due in week 7.
Next lecture · Unsupervised learning
No labels at all: principal component analysis derived as an eigenvalue problem, k-means clustering, and maps of data such as t-SNE. Examples: phase mapping of an X-ray diffraction library, and the periodic table rediscovered from element properties.
References and image credits
Further reading
Reading for this week
G. James, D. Witten, T. Hastie, R. Tibshirani, J. Taylor, An Introduction to Statistical Learning with Applications in Python, Springer (2023), Ch. 5 (resampling methods).
K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): sections on model selection and cross-validation.
S. Sandfeld, Materials Data Science, Springer (2024): chapters on data quality and validation.
S. Varma, R. Simon, "Bias in error estimation when using cross-validation for model selection," BMC Bioinformatics 7, 91 (2006); G. C. Cawley, N. L. C. Talbot, J. Mach. Learn. Res. 11, 2079 (2010).
B. Meredig et al., "Can machine learning identify the next high-temperature superconductor? Examining extrapolation performance for materials discovery," Mol. Syst. Des. Eng. 3, 819 (2018) (leave-cluster-out CV).
A. Dunn, Q. Wang, A. Ganose, D. Dopp, A. Jain, "Benchmarking materials property prediction methods: the Matbench test set and Automatminer reference algorithm," npj Comput. Mater. 6, 138 (2020).
M. D. Wilkinson et al., "The FAIR Guiding Principles for scientific data management and stewardship," Sci. Data 3, 160018 (2016).
Rutile crystals, Binn Valley, Switzerland: Robert M. Lavinsky (iRocks.com), CC BY-SA 3.0 — File page
Rear of rack at NERSC data center: Derrick Coetzee, CC0 — File page
All schematics and plots were drawn for this course. Data on slides 4, 8, 9, 12 and 15 are simulated (seeded; scripts posted with Lab 6). The PBE and measured band gaps are typical values, rounded, as in lecture 1. Fold scores in worked problem 1 and the confusion matrix on slide 16 are illustrative numbers.