A prediction is only useful if we know how far to trust it. Today models learn to say "I am not sure".
Undergraduate course · 16 weeks
Recap · lecture 3
Last time: turning a material into numbers
1
Invariance: a descriptor must not change when we shift, rotate or relabel the atoms.
So raw coordinates fail as features.
2
Composition features: fraction-weighted mean, mean absolute deviation and range of elemental properties.
Cheap, and available before the structure is known.
3
Structure and processing: radial distribution function, Coulomb-matrix eigenvalues, SOAP; grain size via Hall–Petch \(d^{-1/2}\).
4
Scaling: standardize with the mean and spread of the training set only.
What it left open
Every model so far returns one number. A new compound far from the training data gets an answer that looks just as confident as one in the middle of the data.
Lecture 1 promised: "in week four, we will build models that warn us." Today we keep that promise.
Why questions · answered at the end
Four puzzles for today
WHY 1
Where does the square in least squares come from? Why not the cube, or the absolute value?
WHY 2
In ridge regression λ looked like a knob to tune. Does it have a meaning we could estimate?
WHY 3
Why does an error bar not shrink to zero exactly at a measured point, and why does it grow far from the data?
WHY 4
A model trained on oxides predicts the gap of LiF. Its error bar is honest, yet it still misses badly. Why?
Math primer 1 · probability and Bayes' rule
Two rules, and one famous consequence
1
Sum and product rules for two quantities a and b:\[ p(a) = \sum_b p(a,b), \qquad p(a,b) = p(a\,|\,b)\,p(b) \]
Everything today follows from these two rules.
2
Bayes' rule: write the product rule both ways, \(p(a|b)p(b) = p(b|a)p(a)\), and divide:\[ \underbrace{p(a\,|\,b)}_{\text{posterior}} = \frac{\overbrace{p(b\,|\,a)}^{\text{likelihood}}\ \overbrace{p(a)}^{\text{prior}}}{p(b)} \]
It turns "how likely is the data if a is true" into "how likely is a, given the data".
3
For model weights: \(p(\mathbf w\,|\,\text{data}) \propto p(\text{data}\,|\,\mathbf w)\;p(\mathbf w)\)
p(data) does not depend on w, so for finding w it is just a constant.
Example: a cheap stability screen
10 % of candidate compounds are really stable. A fast screening calculation flags 90 % of the stable ones, but also 20 % of the unstable ones. A candidate is flagged. Is it stable?
The flag raises the chance from 10 % to only 33 %, because unstable candidates are so common. The prior matters. A second, independent flag raises it to 69 %.
Math primer 2 · the Gaussian distribution
The bell curve, in one and in many dimensions
1
One variable, mean μ, standard deviation σ:\[ \mathcal N(x\,|\,\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right) \]
This 1.96 gives every 95 % error bar in this lecture.
3
d variables, mean vector μ, covariance matrix Σ:\[ \mathcal N(\mathbf x\,|\,\boldsymbol\mu,\Sigma) = \frac{\exp\!\left(-\tfrac12(\mathbf x-\boldsymbol\mu)^{\mathsf T}\Sigma^{-1}(\mathbf x-\boldsymbol\mu)\right)}{(2\pi)^{d/2}\,|\Sigma|^{1/2}} \]
Variances on the diagonal of Σ, covariances off the diagonal.
C. F. Gauss, 1840. C. A. Jensen, public domain
Why Gaussians?
Many small independent effects add up to a bell curve. Gauss used it for errors in astronomical measurements. Gaussians are also easy: sums and slices of Gaussians are again Gaussian.
Math primer 3 · conditioning a Gaussian
Measure one variable, and the other becomes more certain
1
Joint Gaussian of two blocks a and b (zero mean):\[ \begin{bmatrix}\mathbf a\\ \mathbf b\end{bmatrix} \sim \mathcal N\!\left(\mathbf 0,\ \begin{bmatrix}\Sigma_{aa} & \Sigma_{ab}\\ \Sigma_{ba} & \Sigma_{bb}\end{bmatrix}\right) \]
Σab says how a and b vary together.
2
Observe b. Then a is still Gaussian, with\[ \text{mean} = \Sigma_{ab}\Sigma_{bb}^{-1}\,\mathbf b, \qquad \text{cov} = \Sigma_{aa} - \Sigma_{ab}\Sigma_{bb}^{-1}\Sigma_{ba} \]
Found by completing the square in the exponent; we use it as a tool.
Standard deviation 0.6; 95 % interval 1.2 ± 1.96 × 0.6 = 0.02 to 2.38.
What this means
Measuring a correlated quantity moves our best guess and shrinks the uncertainty, here from 1 to 0.6. A Gaussian process is just this formula.
Derivation 1 · least squares from probability
Least squares = maximum likelihood with Gaussian noise
1
Model the noise: \(y_i = \mathbf x_i^{\mathsf T}\mathbf w + \varepsilon_i\), with \(\varepsilon_i \sim \mathcal N(0,\sigma^2)\), independent.
Measurement scatter around the true trend, assumed Gaussian.
2
Likelihood of all n data: a product of Gaussians,\[ p(\mathbf y\,|\,X,\mathbf w) = \prod_{i=1}^{n}\frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left(-\frac{(y_i-\mathbf x_i^{\mathsf T}\mathbf w)^2}{2\sigma^2}\right) \]
Independent errors, so their probabilities multiply.
3
Take the log (same maximum, sums are easier):\[ \log p = -\frac n2\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^{n}(y_i-\mathbf x_i^{\mathsf T}\mathbf w)^2 \]
4
Maximize over w: the first term has no w, so\[ \hat{\mathbf w}_{\text{ML}} = \arg\min_{\mathbf w}\ \lVert \mathbf y - X\mathbf w\rVert^2 \quad\text{(least squares)} \]
\(\hat E_g = 0.5875 + 2.5675\,\Delta\chi\) on five semiconductors: sum of squared residuals 6.75 eV², so \(\hat\sigma = \sqrt{6.75/5} = 1.16\) eV. The line is uncertain by about 1 eV per material.
What the model learned
The square is an assumption: Gaussian noise. If a few entries are badly wrong (heavy tails), a Laplace noise model gives the absolute loss instead, and a fit as robust as the median of lecture 1.
Derivation 2 · ridge regression from probability
Ridge = most probable weights with a Gaussian prior
1
Prior: before seeing data, each weight \(w_j \sim \mathcal N(0,\tau^2)\).
"Small weights are more likely"; τ says how large a weight can plausibly be.
2
Bayes: \(p(\mathbf w\,|\,\mathbf y) \propto p(\mathbf y\,|\,\mathbf w)\,p(\mathbf w)\). Take minus the log:\[ -\log p(\mathbf w|\mathbf y) = \frac{1}{2\sigma^2}\lVert\mathbf y - X\mathbf w\rVert^2 + \frac{1}{2\tau^2}\lVert\mathbf w\rVert^2 + \text{const} \]
Likelihood term from derivation 1, plus one term from the prior.
3
Multiply by 2σ² (does not move the minimum):\[ \hat{\mathbf w}_{\text{MAP}} = \arg\min_{\mathbf w}\ \lVert\mathbf y - X\mathbf w\rVert^2 + \frac{\sigma^2}{\tau^2}\lVert\mathbf w\rVert^2 \]
MAP = maximum a posteriori, the most probable weights.
4
This is ridge (lecture 2), with \(\lambda = \sigma^2/\tau^2\):\[ \hat{\mathbf w}_{\text{MAP}} = (X^{\mathsf T}X + \lambda I)^{-1}X^{\mathsf T}\mathbf y \]
τ → ∞ (no prior belief): λ → 0, plain least squares. τ → 0: all weights forced to 0. Noisier data (larger σ): stronger regularization.
Number · the band-gap line
σ̂ = 1.16 eV, prior τ = 1 eV per unit Δχ → λ = 1.35. On centred data the slope shrinks from 2.57 to 1.82 eV.
What the model learned
λ is not a magic knob: it is a noise-to-prior ratio. A Laplace prior gives the lasso in the same way.
Worked problem 1 · by hand
A thermal expansion coefficient with an error bar
Given (simulated): a copper rod is heated by ΔT; its strain y is measured. Model y = w x with x = ΔT in units of 100 K and y in units of 10⁻⁴, so w is α in 10⁻⁶ K⁻¹. Noise σ = 0.1, prior τ = 1, so λ = σ²/τ² = 0.01.
ΔT (K)
x
strain y (10⁻⁴)
x²
x y
100
1
1.6
1
1.6
200
2
3.3
4
6.6
300
3
5.1
9
15.3
sum
14
23.5
Check and meaning
Handbook α of copper ≈ 16.5 × 10⁻⁶ K⁻¹: inside our interval. The error bar shrinks as \(1/\sqrt{\sum x^2}\): more and wider-spread data. Here λ = 0.01 ≪ 14, so the prior hardly matters.
1
Posterior of one weight: complete the square in w,\[ -\log p(w|\mathbf y) = \frac{\sum x^2 + \lambda}{2\sigma^2}\Big(w - \frac{\sum xy}{\sum x^2+\lambda}\Big)^2 + \text{const} \]
A Gaussian in w: read off its mean and variance.
2
Mean and standard deviation:\[ \bar w = \frac{23.5}{14.01} = 1.677, \qquad s_w = \frac{0.1}{\sqrt{14.01}} = 0.027 \]
Only the 100 K point: \(\bar w = 1.6/1.01 = 1.58\), \(s_w = 0.1/\sqrt{1.01} = 0.0995\): \(\alpha = (15.8 \pm 2.0)\times10^{-6}\) K⁻¹.
One point: four times wider.
Gaussian processes · 1 · a prior over functions
Skip the weights: put the Gaussian on the function itself
1
Idea: the values \(f(x_1),\dots,f(x_n)\) at any set of inputs are jointly Gaussian (mean 0 after subtracting the training mean).
A "Gaussian process": infinitely many Gaussian variables, one per x.
2
The kernel is the covariance (squared exponential):\[ k(x,x') = \sigma_f^2\exp\!\left(-\frac{(x-x')^2}{2\,l^2}\right) \]
σf: typical size of the variations. l: length scale, how far correlation reaches.
3
Correlation versus distance:
|x − x′|
0
l
2 l
3 l
k / σf²
1
0.61
0.14
0.011
3 random functions from the prior, length scale l = 0.05
3 random functions from the prior, length scale l = 0.3
What the kernel encodes
Only "similar inputs give similar outputs": no trend, no physics. Far from data a GP falls back to its mean. (Also called kriging, after the mining engineer Danie Krige.)
Gaussian processes · 2 · derivation
Prediction = conditioning the joint Gaussian on the data
1
Noisy data: \(y_i = f(x_i) + \varepsilon_i\), \(\varepsilon_i\sim\mathcal N(0,\sigma^2)\). The kernel matrix \(K_{ij} = k(x_i,x_j)\) is n × n.
Noise adds σ² to the variance of each measurement only.
2
Joint Gaussian of the data and the value \(f_* = f(x_*)\) at a new input:\[ \begin{bmatrix}\mathbf y\\ f_*\end{bmatrix} \sim \mathcal N\!\left(\mathbf 0,\ \begin{bmatrix}K + \sigma^2 I & \mathbf k_*\\ \mathbf k_*^{\mathsf T} & k(x_*,x_*)\end{bmatrix}\right) \]
\(\mathbf k_*\) = kernel between x* and each training input.
3
Condition on y (primer 3 with a = f*, b = y):\[ \mu_* = \mathbf k_*^{\mathsf T}(K+\sigma^2 I)^{-1}\mathbf y, \qquad \sigma_*^2 = k(x_*,x_*) - \mathbf k_*^{\mathsf T}(K+\sigma^2 I)^{-1}\mathbf k_* \]
Predictive mean and variance: one formula each.
Sanity checks
Far from all data: \(\mathbf k_*\to\mathbf 0\), so \(\mu_*\to 0\) (the mean) and \(\sigma_*^2\to\sigma_f^2\) (the prior). One point, no noise, x* = x1: \(\mu_* = y_1\), \(\sigma_*^2 = 0\). Units: \(\mu_*\) has the units of y.
What the model learned
With \(\boldsymbol\alpha = (K+\sigma^2I)^{-1}\mathbf y\), the prediction is \(\mu_* = \sum_i \alpha_i\,k(x_i,x_*)\): a weighted sum of bumps centred on the training points. It stores the data. Cost grows as n³, fine up to a few thousand points.
Worked problem 2 · by hand
A Gaussian process with one data point
Given: σf = 1, length scale l = 1, noise σ = 0.1. One measurement y₁ = 1 at x₁ = 0 (already centred). With one point, \(K+\sigma^2 I\) is the number 1.01:
Given: same kernel (σf = 1, l = 1, σ = 0.1). Two centred measurements: y = 1 at x = 0 and y = 0.5 at x = 1.
Compare at x* = 0.5
data
μ*
σ*
one point
0.874
0.478
two points
0.819
0.191
What this shows
A second nearby point shrinks the error bar 2.5 times. α₂ is negative: the second value is lower than the first point "expects", so the GP bends down between them.
Gaussian processes · 3 · back to the alloy of lecture 1
A GP fits the curve and knows where the data end
Setup
The 10 simulated training points of lecture 1 (noise 0.05 eV) and the 40 test points. Kernel fitted from the data: σf = 0.46 eV, length scale l = 0.72; noise σ = 0.05 eV. Shaded: 95 % band for the true curve.
GP mean95 % bandtrue curve
model
test RMSE (eV)
error bar?
polynomial, degree 2
0.049
no
polynomial, degree 9
116
no
GP
0.052
yes
What the model learned
A smooth curve, without being told it is a parabola. It cannot know the physics, but it does know where it has seen data.
Gaussian processes · 4 · the two settings that matter
Length scale and noise decide how the GP behaves
And the noise σ?
Length scale 0.72, but assume σ = 0.01 eV instead of 0.05: the band becomes far too narrow, and only 17 of the 40 test points lie inside the "95 %" band. Assume σ = 0.2 eV: the fit gets flatter (test RMSE 0.077 eV) and the band too wide.
What the settings mean
Length scale = how far one measurement reaches. Too short: the GP memorizes the points and falls back to the mean between them (overfitting). Too long: too stiff (underfitting). Noise = how much we trust each point.
Gaussian processes · 5 · fitting the settings
Choose l and σf by maximizing the marginal likelihood
Data fit rewards short length scales that follow every point.
Penalty punishes flexible models that could fit almost anything.
Try it (outside the video)
length scale 0.7
noise σ (eV) 0.05
—
Using the error bar · prediction intervals
A 95 % interval should miss about 1 time in 20
1
Two kinds of interval:\[ f_*:\ \ \mu_* \pm 1.96\,\sigma_*, \qquad y_*:\ \ \mu_* \pm 1.96\sqrt{\sigma_*^2 + \sigma^2} \]
The true curve, or a new noisy measurement of it: add the noise variance.
2
Alloy at x = 0.5: σ* = 0.027 eV, so the curve lies within ±0.054 eV. A new measurement: \(\sqrt{0.027^2 + 0.05^2} = 0.057\) eV, so ±0.11 eV.
Here the measurement noise dominates.
3
Check calibration on held-out data: count the points inside the 95 % interval for y.
data
inside
expected
alloy, 40 test points
40 of 40
about 38
oxides (next slide), leave-one-out
29 of 32
about 30
A UV–visible spectrophotometer: optical gaps come from absorption spectra like these. TimVickers, public domain
What this means
Far fewer misses than 5 %: too cautious. Far more: overconfident, and that is the dangerous case. An error bar is a claim; always test it on data the model has not seen.
Materials example · small data
Band gaps of 32 oxides from one descriptor
TiO₂, 3.0 eV: white. Walkerma, public domainFe₂O₃, 2.1 eV: red. Benjah-bmm27, public domain
leave-one-out
MAE (eV)
predict the mean (4.55 eV)
1.86
straight line in Δχ
1.58
GP (refitted in each fold)
1.89
What the model learned
Fitted noise σ = 2.1 eV against a signal σf = 0.5 eV: the GP says Δχ explains little. It does not even beat the mean (1.89 vs 1.86 eV), but its error bar tells us so. SiO₂ and CuO share Δχ = 1.54 but differ by 7.7 eV. Better features are needed.
Applicability domain · when to distrust a prediction
Far from the data, the error bar warns, but cannot rescue
test
Δχ
dist.
GP (95 %)
σ*/σf
meas.
Si
0.00
1.08
4.6 ± 4.3
1.00
1.12
LiF
3.00
0.45
4.6 ± 4.3
0.99
≈ 13.6
CaF₂
2.98
0.43
4.6 ± 4.3
0.99
≈ 12
NaCl
2.23
0.01
4.9 ± 4.3
0.81
8.5
Three warning signs
1. Distance to the nearest training point > length scale (0.33). 2. σ*/σf near 1: back to the prior (inside the oxides: 0.77). 3. A different chemistry, even inside the range (NaCl).
What the model learned
Beyond the data a GP returns to the oxide mean. LiF lies 4.1 standard deviations above it: the variance says "I know nothing here", but cannot know the trend continues.
Lab 4 · this week in Colab
Gaussian process regression with scikit-learn
import numpy as np, pandas as pd
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import (
ConstantKernel as C, RBF, WhiteKernel)df = pd.read_csv("oxide_gaps.csv")
X, y = df[["dchi"]].values, df["gap"].valueskernel = C(1.0) * RBF(length_scale=0.5) + WhiteKernel(0.5)
gp = GaussianProcessRegressor(kernel, normalize_y=True,
n_restarts_optimizer=5)
gp.fit(X, y)
print(gp.kernel_) # fitted sigma_f, l, noiseXg = np.linspace(0, 3.2, 200).reshape(-1, 1)
mu, sd = gp.predict(Xg, return_std=True)
lo, hi = mu - 1.96*sd, mu + 1.96*sd # 95 % band
Exercises
Check worked problem 3 with numpy: build K + σ²I, solve for α, predict at 0.5 and 3.
Alloy data: vary l and σ; record test RMSE and how many test points lie in the 95 % band.
Oxides: leave-one-out MAE of the mean, a line and the GP. Add a second feature: does the GP win now?
Predict LiF and Si; flag them with the distance and σ*/σf rules.
Runs in Google Colab; no GPU needed. With a WhiteKernel, return_std includes the noise: it is the band for a new measurement.
Answers to the why questions
The four puzzles, solved
1 · Where the square comes from
Least squares maximizes the likelihood when the noise is Gaussian. The square is an assumption about the errors. Heavy-tailed errors (wrong entries) call for the absolute loss.
2 · The meaning of λ
Ridge is the most probable fit with a Gaussian prior on the weights: λ = σ²/τ², noise variance over prior variance. Noisy data or a tight prior: larger λ.
3 · Error bars at and away from data
At a measured point the GP standard deviation is limited by the noise (0.0995 for σ = 0.1). Away from data, k* → 0 and the variance grows back to the prior σf².
4 · LiF: honest, yet wrong
Beyond the oxides the GP returns to the oxide mean, 4.6 eV, with σ* ≈ σf. The variance flags "no knowledge", but cannot predict that the trend continues to 13.6 eV.
Check your understanding · click a card to reveal
Concept check
Q1. Measurement noise σ = 0.1 eV and a prior τ = 0.5 on the weights. What ridge λ does this imply?
λ = σ²/τ² = 0.01/0.25 = 0.04.
Q2. A GP with length scale 0.2 predicts at a point 1.0 away from every training point. What mean and standard deviation do you expect?
k ≈ σf² e−12.5 ≈ 0: the mean returns to the training mean and the standard deviation to σf. The GP has nothing to say there.
Q3. Your "95 %" intervals contain only 30 of 50 test materials. What is wrong, and what would you try?
Overconfident (expected about 47–48). The noise or σf is too small, or the length scale too long. Refit by marginal likelihood and check again on held-out data.
Q4. Why can a GP not tell you that LiF has a larger gap than every oxide in the training set?
The squared-exponential kernel has no trend: beyond the data the mean returns to the prior mean. Extrapolation needs physics or a trend in the model (e.g. a linear mean function).
Wrap-up
Summary and next lecture
1
Bayes' rule: posterior ∝ likelihood × prior. Gaussians stay Gaussian when we condition on part of them.
2
Least squares = maximum likelihood with Gaussian noise; ridge = most probable weights with a Gaussian prior, λ = σ²/τ².
3
A GP puts a Gaussian on the function. The kernel (σf, length scale l) encodes "similar inputs, similar outputs". Mean and variance come from one conditioning formula.
4
Fit l and σf by the marginal likelihood. 95 % ≈ ±1.96σ; check the coverage on held-out data.
5
Error bars grow away from the data, but cannot rescue an extrapolation. Use distance, σ*/σf and chemistry to judge the applicability domain.
This week
Lab 4: GP regression on the alloy and oxide data. Problem set 1 (weeks 1–3) is due this week.
Next lecture · Classification and tree ensembles
From numbers to classes: metal or insulator, stable or unstable (Ehull below 25 meV/atom). We derive logistic regression from today's maximum-likelihood idea, then build decision trees and random forests.
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 (regression) and Ch. 5 (marginal likelihood). Free online.
K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): probability, Gaussians, Bayesian linear regression, Gaussian processes.
C. M. Bishop, H. Bishop, Deep Learning: Foundations and Concepts, Springer (2024): probabilities and the Gaussian distribution.
G. James, D. Witten, T. Hastie, R. Tibshirani, J. Taylor, An Introduction to Statistical Learning with Applications in Python, Springer (2023), Ch. 6 (ridge and lasso).
S. Sandfeld, Materials Data Science, Springer (2024).
Data: oxide gaps are approximate measured values, rounded (sources differ by a few tenths of an eV); Pauling electronegativities; alloy and thermal-expansion data are simulated.
Image credits (Wikimedia Commons)
Carl Friedrich Gauss, portrait 1840: Christian Albrecht Jensen, public domain — File page
DU640 spectrophotometer: TimVickers, public domain — File page