ML for Materials Science · Week 13 · Lecture 13

Active Learning and Bayesian Optimization

Let the model choose the next experiment: find a good material with as few syntheses and calculations as possible.
Undergraduate course · 16 weeks
hardness score alloy composition x next experiment
Recap · lecture 12

Last time: machine-learned interatomic potentials

1
Energy and forces: \(\mathbf F_i = -\nabla_i E\), and locality \(E = \sum_i E_i\).
One structure gives 3N force labels, not just one energy.
2
Models: Behler–Parrinello symmetry functions, Gaussian approximation potentials (a GP, lecture 4), equivariant NequIP and MACE, universal M3GNet, CHGNet, MACE-MP.
3
Use: molecular dynamics, diffusion from \(\langle r^2\rangle = 6Dt\) and Arrhenius \(D = D_0\,e^{-E_a/k_BT}\).
4
Check against DFT: parity of energies and forces, phonons; a potential extrapolates badly.

What it left open

Every new DFT label costs hours of computer time; every synthesis and test costs a day or more. We can afford only a few. Which structure, composition or recipe should we try next?

The tool we already have

The Gaussian process of lecture 4 gives a prediction and an error bar. Today we use the error bar to decide where to look.

This week: PS4 (weeks 11–12) is due. PS5 covers weeks 13–14.

Why questions · answered at the end

Four puzzles for today

WHY 1

Why would a smart optimizer choose to make an alloy that it predicts to be softer than the best one so far?

WHY 2

Why does "always make the alloy with the best prediction" often get stuck on a second-rate material?

WHY 3

Why is the best hydrogen-evolution catalyst not the one that binds hydrogen most strongly, and how should a search use that?

WHY 4

A robot can run four syntheses at once. Why not simply run the four candidates with the highest scores?

The idea · a closed loop

Model → choose → measure → update, and repeat

1 · ModelGP: μ(x) and σ(x) 2 · Choosemax acquisition a(x) 3 · Measuresynthesis or DFT 4 · Updateadd (x, y) to data milliseconds of computing to save days in the lab

Active learning

Goal: a good model everywhere. Measure where the model is least sure (largest σ).

Bayesian optimization

Goal: the best material. Balance a high prediction μ against a large σ.

Automated liquid-handling robot with a 96-channel pipetting head
An automated liquid-handling workstation: robots can run step 3 day and night; the model runs steps 1 and 2.
NIAID, public domain
Recap · the Gaussian process of lecture 4

The model in step 1: a prediction and an error bar

1
Kernel (squared exponential):\[ k(x,x') = \sigma_f^2\exp\!\left(-\frac{(x-x')^2}{2\,l^2}\right) \]
σf: typical size of variations. l: length scale, how far one measurement reaches.
2
Predictive mean (data centred on their mean m):\[ \mu_* = m + \mathbf k_*^{\mathsf T}(K+\sigma^2 I)^{-1}(\mathbf y - m) \]
\(\mathbf k_*\): kernel between the candidate x* and each measured alloy.
3
Predictive variance:\[ \sigma_*^2 = k(x_*,x_*) - \mathbf k_*^{\mathsf T}(K+\sigma^2 I)^{-1}\mathbf k_* \]
Small near the data, back to σf² far away.

Simulated alloy A₁₋ₓBₓ, hardness in GPa, three alloys already tested (x = 0.1, 0.4, 0.9). Kernel σf = 1 GPa, length scale l = 0.08, noise σ = 0.1 GPa.

What the model learned

μ is the best guess, σ says how much we still do not know. Neither alone tells us where to measure: we need both.

Math primer · the standard normal distribution

Three facts about φ and Φ that we need today

1
Standardize: if \(f\sim\mathcal N(\mu,\sigma^2)\), then \(z = (f-\mu)/\sigma \sim \mathcal N(0,1)\), with density and cumulative probability\[ \varphi(z) = \frac{e^{-z^2/2}}{\sqrt{2\pi}}, \qquad \Phi(z) = \int_{-\infty}^{z}\varphi(t)\,dt \]
Every Gaussian question becomes a question about one table.
2
Symmetry: \(P(z > a) = 1-\Phi(a) = \Phi(-a)\).
The bell curve is symmetric about zero.
3
A useful integral: since \(\dfrac{d\varphi}{dz} = -z\,\varphi(z)\),\[ \int_{a}^{\infty} z\,\varphi(z)\,dz = \big[-\varphi(z)\big]_a^{\infty} = \varphi(a) \]
Chain rule on \(e^{-z^2/2}\); this gives the second term of expected improvement.
P(z > 1) = 1 − Φ(1) = 0.159 z
zφ(z)Φ(z)
00.3990.500
10.2420.841
1.960.0580.975

Why we need this

At every candidate the GP says \(f \sim \mathcal N(\mu_*,\sigma_*^2)\). Every score today is an integral over this Gaussian.

Acquisition function 1 · derivation

Probability of improvement (PI)

1
Improvement event: the new alloy beats the best measured so far, \(f(x_*) > y_{\text{best}}\).
We are maximizing hardness.
2
The GP says \(f(x_*) \sim \mathcal N(\mu_*,\sigma_*^2)\). Standardize:\[ f > y_{\text{best}} \iff z > \frac{y_{\text{best}}-\mu_*}{\sigma_*} = -Z, \qquad Z = \frac{\mu_*-y_{\text{best}}}{\sigma_*} \]
3
Use symmetry (primer step 2):\[ \text{PI}(x_*) = P(z > -Z) = \Phi(Z) \]
Z counts how many error bars the prediction lies above the best.

What the score rewards

Sanity check: if \(\mu_* = y_{\text{best}}\), PI = 0.5 whatever σ*. PI asks only whether we improve, not by how much, so a tiny but sure gain wins: PI is greedy.

Acquisition function 2 · derivation

Expected improvement (EI) in closed form

1
Improvement as a number: \(I = \max(0,\ f - y_{\text{best}})\).
Zero if worse; the size of the gain if better.
2
Write \(f = \mu_* + \sigma_* z\). Then I > 0 when z > −Z, and\[ \text{EI} = \int_{-Z}^{\infty} (\mu_* - y_{\text{best}} + \sigma_* z)\,\varphi(z)\,dz \]
Average the gain over the Gaussian, only where there is a gain.
3
Split into two integrals:\[ (\mu_*-y_{\text{best}})\underbrace{\int_{-Z}^{\infty}\varphi\,dz}_{\Phi(Z)} \;+\; \sigma_*\underbrace{\int_{-Z}^{\infty} z\,\varphi\,dz}_{\varphi(-Z)\,=\,\varphi(Z)} \]
Primer steps 2 and 3, and φ is symmetric.
4
Result:\[ \text{EI}(x_*) = (\mu_* - y_{\text{best}})\,\Phi(Z) + \sigma_*\,\varphi(Z) \]

Sanity checks

No uncertainty, σ* → 0: EI → max(0, μ* − ybest), the sure gain.
Prediction equals the best: EI = σ* φ(0) = 0.399 σ*.
Units: GPa, like y. EI is never negative.

μ* − ybestσ* (GPa)EI (GPa)
−0.50.50.04
−0.51.00.20
−0.52.00.57

What the score rewards

First term: exploitation, a high mean. Second term: exploration, a large σ. One formula, no tuning knob.

Acquisition function 3 · and all three side by side

Upper confidence bound, and where each score points

\[ \text{UCB}(x_*) = \mu_* + \kappa\,\sigma_* \]

κ = 0: pure exploitation, measure the best mean.
κ large: pure exploration, measure the largest σ.
κ ≈ 2: the top of the 95 % band of lecture 4: "optimism in the face of uncertainty".

Minimizing (Ehull, cost)? Use μ* − κσ*, or maximize −y.

What the scores learned

All three use only μ and σ of the GP. They differ in how much they value σ.

Worked problem 1 · by hand

Safe bet or long shot? Two candidate alloys

Given: best hardness so far ybest = 10.0 GPa. The GP predicts
A: μ = 10.5, σ = 0.25 GPa (close to tested alloys)
B: μ = 9.5, σ = 2.0 GPa (an untested region)

zφ(z)Φ(z)
20.05400.9772
−0.250.38670.4013

What if B were less uncertain? EI of B = 0.20 for σ = 1.0 and 0.38 for σ = 1.5 GPa: then the safe bet A (0.50) wins.

What this shows

PI picks the safe bet A; EI and UCB pick the long shot B, because a possible gain of several GPa outweighs a sure gain of 0.5 GPa.

1
Standardized gaps:\[ Z_A = \frac{10.5-10}{0.25} = 2, \qquad Z_B = \frac{9.5-10}{2} = -0.25 \]
2
PI: \(\Phi(2) = 0.977\) for A, \(\Phi(-0.25) = 0.401\) for B → A.
3
EI:\[ \text{A: } 0.5(0.9772) + 0.25(0.0540) = 0.502 \]\[ \text{B: } -0.5(0.4013) + 2.0(0.3867) = 0.573 \]
→ B, by a small margin.
4
UCB, κ = 2: A: 10.5 + 0.5 = 11.0; B: 9.5 + 4.0 = 13.5 → B.
Worked problem 2 · by hand

Where should lecture 4's two-point GP measure next?

Given (lecture 4, worked problem 3): σf = 1, l = 1, σ = 0.1; two centred measurements (m = 0), y = 1 at x = 0 and y = 0.5 at x = 1; \(\boldsymbol\alpha = (K+\sigma^2I)^{-1}\mathbf y = (1.084,\ -0.156)\). So ybest = 1.

1
Candidate x* = −1: \(\mathbf k_* = (e^{-1/2},\,e^{-2}) = (0.607,\ 0.135)\), so \(\mu_* = 0.607(1.084) + 0.135(-0.156) = 0.636\) and \(\sigma_*^2 = 1 - \mathbf k_*^{\mathsf T}(K+\sigma^2I)^{-1}\mathbf k_* = 0.555\), \(\sigma_* = 0.745\).
2
EI at x* = −1: \(Z = (0.636-1)/0.745 = -0.489\):\[ \text{EI} = -0.364(0.313) + 0.745(0.354) = 0.150 \]
3
Compare and choose: EI is largest at x* = −1. UCB with κ = 2 agrees: 2.13 at −1, 1.97 at 3, 1.20 at 0.5.
Two different scores, same decision.
x*μ*σ*ZEI
−10.6360.745−0.490.150
0.5 (midway)0.8190.191−0.950.018
3 (far)−0.0090.987−1.020.079

What this shows

Midway is already well known and below the best. Far away is uncertain but predicted low. Next to the best point, on the unexplored side, we are both uncertain and hopeful.

Materials example 1 · simulated alloy hardness

Bayesian optimization in action, step by step

Simulated: hidden true hardness (dashed) has a small peak near x = 0.25 and the real peak, 5.1 GPa, at x = 0.72. Each test has 0.1 GPa noise. Shaded: 95 % band. Gold: EI (scaled). ▲ next alloy.

Diamond-shaped Vickers hardness indent seen in a microscope
A Vickers indent: one "measurement". Encik Tekateki, CC BY-SA 4.0

What the loop learned

With 5 alloys it found the real peak (measured 5.18 GPa at x = 0.71). Once the peak is pinned down, EI there drops and the loop turns to the unexplored small peak near 0.25. 5.18 is above the true 5.12 GPa because each test carries 0.1 GPa noise: the best measured value is optimistic, so we repeat the best point.

Exploration versus exploitation · 300 simulated campaigns

Greedy search gets stuck; balanced scores find the peak

strategy (3 random starts + 9 chosen)found the real peak
random search (baseline)50 %
greedy: best mean (κ = 0)56 %
pure exploration: largest σ53 %
probability of improvement82 %
expected improvement100 %
UCB, κ = 2100 %
UCB, κ = 594 %

"Found" = best alloy tested within 0.3 GPa of the true maximum after 12 tests. Same simulated alloy and GP as before.

What the numbers mean

Too greedy: stays on the first good hill. Too curious: spends tests on places that cannot win. Balance wins, and both extremes are barely better than random.

Try it (outside the video)

strategy
step 0
—
Materials example 2 · composition and ageing temperature

In two dimensions, random search falls far behind

Simulated hardness on 26 × 26 = 676 candidate (composition, ageing temperature) pairs; only 3 lie within 0.3 GPa of the best. 100 campaigns of 30 tests, 5 random starts. Lines: median; band: middle 50 %.

Baseline comparison

BO: within 0.3 GPa of the best after a median of 12 tests, in all 100 campaigns. Random: reached it in only 14 % of campaigns within 30 tests.

Practical issue 1 · batch selection

Four experiments at once: spread them out

1
Pick the maximum of EI.
As before.
2
Pretend its result equals the prediction μ*, and update the GP ("kriging believer").
σ shrinks there, so EI nearby collapses; the best value ybest does not change.
3
Pick again, until the batch has q members; then run all q for real.
Other names: constant liar, q-EI, local penalization.
batch of 4 (after the 3 starting alloys)compositions x
naive: top-4 EI values0.76, 0.77, 0.78, 0.79
kriging believer0.78, 1.00, 0.59, 0.26

What this buys

A batch of 4 takes one round instead of four. Per test it is a little less efficient than one-at-a-time, but much faster in days.

Practical issue 2 · when to stop, and active learning for a model

Stop when the expected gain is smaller than the noise

Stopping rules: the budget is spent · max EI below a threshold (here 0.01 GPa, a tenth of the noise) · no improvement for several rounds · the target property is reached.

Active learning for a model: measure the largest σ

Same alloy, goal: an accurate GP everywhere. RMSE of the GP over all compositions, median of 200 simulated campaigns:

alloys testedrandom choicelargest σ
30.71 GPa0.72 GPa
80.48 GPa0.33 GPa
150.25 GPa0.11 GPa

Link to lecture 12

On-the-fly training of interatomic potentials works this way: run MD, and call DFT only when the model's uncertainty for a new structure is large.

Link to Electrochemistry lecture 13 · the Sabatier principle

A volcano turns "maximize" into "hit a target"

Physical meaning

Too weak: hydrogen does not stick. Too strong: it does not leave. The best catalyst binds "just right", ΔGH* ≈ 0. Nickel, 0.3 eV too strong, sits about 2.2 decades below the top.

Portrait of Paul Sabatier
Paul Sabatier, Nobel 1912. Nobel Foundation, public domain
1
Descriptor: ΔGH*, the free energy of adsorbed H, one DFT calculation per surface.
2
Volcano (Electrochemistry lecture 13):\[ \log_{10}\frac{r_0}{r_{0,\max}} = -\log_{10}\cosh\frac{\Delta G_{H^*}}{2k_BT} \]
Wings: one decade per 0.118 eV at 25 °C.
3
Search target: a window, not a maximum. With the GP of ΔG:\[ P(|\Delta G| < w) = \Phi\!\left(\tfrac{w-\mu_*}{\sigma_*}\right) - \Phi\!\left(\tfrac{-w-\mu_*}{\sigma_*}\right) \]
Primer step 1, applied twice.
Materials example 3 · catalyst screening (simulated)

Finding ΔGH* ≈ 0 in a ternary surface alloy

Simulated: 231 compositions of an A–B–C surface alloy; an illustrative smooth ΔGH*; "DFT" noise 0.02 eV. Only 8 candidates have |ΔGH*| < 0.03 eV (gold rings). 200 campaigns, 3 random starts.

strategyDFT calcs to first hit (median)hit within 10
random1934 %
GP on activity + EI868 %
GP on ΔG + window probability772 %

What the model learned

Model the smooth descriptor, then apply the known physics (the volcano) in the score. ΔG is only a descriptor: stability, cost and real surfaces still need checking.

Closing the loop with robots · self-driving laboratories

The A-Lab: robots make, models decide

Robot arm loading powder samples into an X-ray diffractometer in the A-Lab
A-Lab: a robot arm brings annealed powders to an X-ray diffractometer.
N. J. Szymanski et al., CC BY 4.0
1
Targets predicted stable by DFT (Materials Project, Ehull).
2
Recipes from models trained on published syntheses.
3
Robots weigh, mix and heat powders; XRD + ML identify the phases.
4
Active learning proposes a new recipe when the yield is low.

Reported: 41 of 58 target compounds made in 17 days (Szymanski et al., Nature 2023). A mobile robot chemist ran about 700 experiments in about 8 days with BO over 10 variables (Burger et al., Nature 2020).

Careful: later analyses questioned how many products were truly new and correctly identified. Automation speeds up the loop; it does not replace careful characterization (Leeman et al., 2024).

When the loop fails · a practical checklist

Six ways a Bayesian optimization campaign goes wrong

problemsymptomwhat to do
Search space too narrowbest point sits on the boundarywiden the ranges; humans still choose the space
Wrong length scaleσ too small, loop stops exploringrefit by marginal likelihood every round (lecture 4)
Noisy, drifting measurements"best" alloy does not reproducerepeat the best points; keep the noise term σ honest
Wrong objectiveharder, but brittle or too costlyconstraints, or several objectives (Pareto front)
Too many variablesno better than random above ~10–20 knobsfewer, physical descriptors; PCA (lecture 7)
No baseline"BO found it" with nothing to comparealways report random search alongside
The loop is only as good as its search space, its noise model and its objective, and all three are chosen by people.
Lab 13 · this week in Colab

A Bayesian optimization loop in twenty lines of numpy

import numpy as np
from scipy.stats import norm
def kern(a, b, sf=1.0, l=0.08):      # lecture 4
    return sf**2*np.exp(-(a[:,None]-b[None,:])**2/(2*l**2))
def gp(X, y, xs, sn=0.1):
    m = y.mean(); K = kern(X, X) + sn**2*np.eye(len(X))
    ks = kern(xs, X); mu = m + ks @ np.linalg.solve(K, y - m)
    var = 1.0 - np.sum(ks*np.linalg.solve(K, ks.T).T, axis=1)
    return mu, np.sqrt(np.maximum(var, 1e-12))
def ei(mu, sd, best):
    z = (mu - best)/sd
    return (mu - best)*norm.cdf(z) + sd*norm.pdf(z)
xs = np.linspace(0, 1, 101)
X = np.array([0.1, 0.4, 0.9]); y = measure(X)  # simulated
for it in range(9):
    mu, sd = gp(X, y, xs)
    xn = xs[np.argmax(ei(mu, sd, y.max()))]
    X, y = np.append(X, xn), np.append(y, measure(xn))

Exercises

  • Check worked problems 1 and 2 with ei.
  • Run EI, greedy (mean only) and UCB with κ = 2 from 100 random starts; reproduce the success-rate table.
  • Choose a batch of 4 with the kriging believer and compare the number of rounds needed.
  • Catalyst: fit a GP to ΔGH* and use the window probability; compare with random search.

Runs in Google Colab; no GPU needed. measure() simulates the alloy with 0.1 GPa noise.

Answers to the why questions

The four puzzles, solved

1 · Make a "softer" alloy?

Because it might be much harder. B (μ = 9.5, σ = 2 GPa) has EI 0.57 vs 0.50 for the safe A (μ = 10.5, σ = 0.25). Uncertainty has value.

2 · Greedy gets stuck

It ignores σ, so it keeps testing next to its current best. It found the real peak in 56 % of campaigns; EI and UCB (κ = 2) in 100 %.

3 · Not the strongest binder

Sabatier: H must stick and leave, so activity peaks at ΔGH* ≈ 0 (Ni, 0.3 eV too strong: 2.2 decades lower). Search for a window: median 7 calculations vs 19 at random.

4 · Batch of four

The top-4 EI points sit at x = 0.76–0.79: one experiment, four times. The kriging believer spreads them to 0.78, 1.00, 0.59 and 0.26.

Check your understanding · click a card to reveal

Concept check

Q1. A candidate's prediction equals ybest, with σ* = 0.4 GPa. What are PI and EI?
Z = 0: PI = Φ(0) = 0.5; EI = σ*φ(0) = 0.4 × 0.399 = 0.16 GPa.
Q2. Your GP's length scale is far too long. How will the loop behave?
σ is too small between tested points, so it exploits too early and can miss a narrow peak. Refit l by marginal likelihood each round.
Q3. You want the lowest Ehull, not the highest. How do you change UCB and EI?
Use the lower bound μ − κσ and pick its minimum; for EI use the gain max(0, ybest − f), or simply maximize −Ehull.
Q4. Why always compare with random search, and when can random search tie?
It is the baseline. It ties with many variables, no smooth structure, very noisy data, or when tests are cheap and massively parallel.
Wrap-up

Summary and next lecture

1
Closed loop: model → choose → measure → update. Active learning improves the model; Bayesian optimization finds the best material.
2
The GP of lecture 4 gives μ and σ; acquisition functions turn them into a score: PI = Φ(Z), EI = (μ − ybest)Φ(Z) + σφ(Z), UCB = μ + κσ.
3
Exploration vs exploitation: greedy gets stuck (56 %), balanced scores win (100 %); random search is the baseline.
4
Batches need diversity (kriging believer); stop when max EI is below the noise; physics such as the volcano belongs in the score.

This week

Lab 13: a BO loop in numpy. PS4 due; PS5 (weeks 13–14) due in week 15. Posters and 6-page reports in week 15.

Next lecture · Generative models and inverse design

Instead of scoring candidates we list, can a model invent them? Screening funnels, variational autoencoders and their latent space, diffusion models, and how many generated crystals survive a DFT stability check.

References and image credits

Further reading

Reading for this week

  • C. E. Rasmussen, C. K. I. Williams, Gaussian Processes for Machine Learning, MIT Press (2006), Ch. 2 (free online).
  • R. Garnett, Bayesian Optimization, Cambridge University Press (2023) (free online).
  • K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): Gaussian distributions and GPs.
  • D. R. Jones, M. Schonlau, W. J. Welch, "Efficient global optimization of expensive black-box functions," J. Global Optim. 13, 455 (1998) (expected improvement).
  • N. Srinivas, A. Krause, S. Kakade, M. Seeger, "Gaussian process optimization in the bandit setting," ICML (2010) (UCB).
  • T. Lookman, P. V. Balachandran, D. Xue, R. Yuan, "Active learning in materials science with emphasis on adaptive sampling using uncertainties for targeted design," npj Comput. Mater. 5, 21 (2019).
  • N. J. Szymanski et al., "An autonomous laboratory for the accelerated synthesis of novel materials," Nature 624, 86 (2023); B. Burger et al., "A mobile robotic chemist," Nature 583, 237 (2020).
  • J. K. Nørskov et al., "Trends in the exchange current for hydrogen evolution," J. Electrochem. Soc. 152, J23 (2005); Electrochemistry for Materials Science, lecture 13.

Image credits (Wikimedia Commons)

  • BioMek FX liquid-handling robot: National Institute of Allergy and Infectious Diseases (NIAID), public domain — File page
  • Vickers hardness diamond indentation: Encik Tekateki, CC BY-SA 4.0 — File page
  • Paul Sabatier: Nobel Foundation, public domain — File page
  • A-Lab robot arm and X-ray diffractometer: N. J. Szymanski, B. Rendy et al., CC BY 4.0 — File page

All plots were computed for this course (numpy). The alloy hardness landscapes and the ternary catalyst are simulated; the volcano uses the one-parameter model of Electrochemistry lecture 13 with typical ΔGH* values for Pt, MoS₂ edges and Ni.

A critical look at the A-Lab

  • J. Leeman et al., "Challenges in high-throughput inorganic materials prediction and autonomous synthesis," PRX Energy 3, 011002 (2024).