ML for Materials Science · Week 1 · Lecture 1

Learning from Materials Data

What it means for a computer to "learn" a property, how to measure whether it really did, and why clean data come first.
Undergraduate course · 16 weeks
feature x (what we know about the material) property y new material: predict y
Where this course fits

Data is the fourth tool of the materials scientist

ThermodynamicsWhich phase is stable?
+
KineticsHow fast does it form?
+
ElectrochemistryHow does it store and convert energy?
+
Data (this course)Learn a property from examples, when no equation exists

Weeks 1–7 · the classical toolkit

data → linear models → describing a material → uncertainty → classification → honest testing → finding structure in data

Weeks 9–15 · deep learning and discovery

neural networks for images and crystals → machine-learned interatomic potentials → choosing the next experiment → inverse design → interpreting and checking models

Every week: derive the method step by step → ask what the model actually learned → test it on a real materials problem → lab notebook.

Robot arm loading powder samples into an X-ray diffractometer in an autonomous laboratory
An autonomous lab: a robot arm brings annealed powders to an X-ray diffractometer.
N. J. Szymanski et al. (A-Lab), CC BY 4.0

Assessment: a lab every week · 5 problem sets · team project (teams wk 9, proposal wk 10, progress check wk 12, poster + 6-page report wk 15) · midterm wk 8 · final wk 16.

Why questions · answered at the end

Four puzzles for today

WHY 1

Why can a model reproduce every training point perfectly, and still be useless?

WHY 2

Why does one database list the band gap of ZnO as 3.37 eV, and another as 0.73 eV?

WHY 3

Why is a small error on your own data no proof that the model works on the next new compound?

WHY 4

When is machine learning the wrong tool for a materials question?

Motivation

Sometimes an equation is enough. Often it is not.

An equation works: band gap of an In1−xGaxAs alloy

\[ E_g(x) = (1-x)\,0.354 + x\,1.424 - 0.477\,x(1-x)\ \text{eV} \]

Linear mixing of the two end members plus a "bowing" term. Three numbers describe every composition. (300 K values)

What this tells us

Use ML where the property is expensive to get and has no reliable equation, and where we need many predictions.

No equation: a property of any new compound

Choose 4 elements from about 80 usable ones:

\[ \binom{80}{4} = \frac{80\cdot 79\cdot 78\cdot 77}{4\cdot 3\cdot 2\cdot 1} = 1\,581\,580 \]

quaternary systems, each with many compositions and structures.

routetime per compound
synthesis and measurementdays to weeks
DFT calculationhours of computer time
trained ML modelmilliseconds
Where the data come from

Computed and measured data: two kinds of label

sourcelabelsizestrength / weakness
Materials ProjectDFT~10⁵consistent, free API / DFT biases
OQMDDFT~10⁶very large / same method biases
JARVIS-DFTDFT~10⁵many property types
Handbooks, papers, ICSDmeasured10²–10⁵ per propertyreal values / scattered, mixed units and conditions

Physical meaning

A computed label is consistent but biased (one method, one set of approximations). A measured label is real but noisy (different samples, temperatures, techniques). Never mix them without a flag.

Rows of supercomputer cabinets
Supercomputer racks: computed data. NASA Ames Research Center, public domain
Silicon wafers from 2 to 8 inch
Silicon wafers: measured data come from real samples. Stahlkocher, CC BY-SA 3.0
Math primer 1 · vectors and matrices

A dataset is a matrix, a material is a row

1
One material → a feature vector of d numbers:\[ \mathbf{x} = [x_1, x_2, \dots, x_d]^{\mathsf T} \]
e.g. x₁ = electronegativity difference Δχ, x₂ = mean atomic mass, …
2
n materials → a matrix X with n rows and d columns, and a target vector y:\[ X \in \mathbb{R}^{n\times d},\qquad \mathbf{y} \in \mathbb{R}^{n} \]
One row per material, one column per feature.
3
A linear model is one product:\[ \hat{y}_i = \mathbf{x}_i^{\mathsf T}\mathbf{w} = \sum_j x_{ij}w_j \quad\Rightarrow\quad \hat{\mathbf{y}} = X\mathbf{w} \]
The dot product of a row with the weights gives that material's prediction.
material1ΔχEg measured (eV)
GaAs10.371.42
GaN11.233.40
ZnO11.793.37
\[ \hat{y}_{\text{GaN}} = [1,\ 1.23]\begin{bmatrix}0.6\\2.6\end{bmatrix} = 0.6 + 2.6\times1.23 = 3.80\ \text{eV} \]

Why the column of ones?

It lets the first weight w₀ act as an intercept, so the line need not pass through zero. Measured value: 3.40 eV, so this model is 0.4 eV too high for GaN.

Math primer 2 · gradients

The gradient points uphill, so step the other way

1
Gradient = vector of partial derivatives:\[ \nabla_{\mathbf w} L = \left[\frac{\partial L}{\partial w_1},\dots,\frac{\partial L}{\partial w_d}\right]^{\mathsf T} \]
It points in the direction where L grows fastest.
2
Two rules we will use all term:\[ \nabla_{\mathbf w}(\mathbf a^{\mathsf T}\mathbf w) = \mathbf a, \qquad \nabla_{\mathbf w}(\mathbf w^{\mathsf T}\mathbf w) = 2\mathbf w \]
Vector versions of d(ax)/dx = a and d(x²)/dx = 2x.
3
Gradient descent: step downhill with learning rate η:\[ \mathbf w \leftarrow \mathbf w - \eta\,\nabla_{\mathbf w} L \]
Repeat until the gradient is (almost) zero.
weight w loss L(w) L(w) = (w − 2)² + 1

Worked example · η = 0.3

dL/dw = 2(w − 2). From w = −1: −1 → 0.80 → 1.52 → 1.81 → 1.92. The distance to the minimum shrinks by 1 − 2η = 0.4 each step: 3 → 1.2 → 0.48 → 0.19.

Definition · the learning problem

Learning = five choices and one minimization

1
Inputs and target: features x of each material, the property y we want.
Example: x = composition features, y = band gap.
2
Model family: a formula with adjustable weights, \(\hat y = f(\mathbf x;\mathbf w)\).
Example: \(\hat y = w_0 + w_1\,\Delta\chi\).
3
Loss for one example: squared \((\hat y - y)^2\) or absolute \(|\hat y - y|\).
It says how much each kind of mistake costs.
4
Training: minimize the average loss on the training set,\[ L(\mathbf w) = \frac{1}{n}\sum_{i=1}^{n} \ell\big(f(\mathbf x_i;\mathbf w),\,y_i\big) \]
This average is called the empirical risk.
5
Testing: compute the same error on materials never used in training.
Only this number tells us how the model will do on new materials.
symbolmeaning (fixed for the course)
\(\mathbf x\)feature vector
\(y,\ \hat y\)target, prediction
\(\mathbf w\)weights
\(\ell,\ L\)loss per example, average loss
MAE, RMSEmean absolute error, root mean square error

Physical meaning

Training is just an optimization on data we have. What we really want, the error on materials we have not seen, can only be estimated with data held back.

Derivation · the simplest model

The best constant: the mean for squared loss, the median for absolute loss

1
Model: predict the same value c for every material, \(\hat y = c\).
The simplest possible model: our baseline.
2
Squared loss: \(L(c) = \frac1n\sum_i (y_i - c)^2\). Set the derivative to zero:\[ \frac{dL}{dc} = -\frac{2}{n}\sum_i (y_i - c) = 0 \;\Rightarrow\; \sum_i y_i = n\,c \;\Rightarrow\; c^* = \bar y \]
Chain rule on each square; then solve the linear equation for c.
3
Check it is a minimum: \(\dfrac{d^2L}{dc^2} = 2 > 0\).
The loss is a bowl, so the flat point is the bottom.
4
Absolute loss: \(L(c) = \frac1n\sum_i |y_i - c|\). Each term has slope −1 if \(y_i > c\), +1 if \(y_i < c\):\[ \frac{dL}{dc} = \frac{1}{n}\big[\#(y_i < c) - \#(y_i > c)\big] = 0 \;\Rightarrow\; c^* = \text{median} \]
Balance: as many points below c as above.

What the model learned

Nothing about the material, only the centre of the data. Yet every real model must beat it. If your model cannot beat "predict the mean", it has learned nothing.

Physical meaning of the loss

Squared loss punishes one big mistake more than many small ones, so one wrong entry pulls the mean. Absolute loss treats all errors alike; the median ignores a single wild value. The choice of loss is a statement about your data.

Worked problem 1 · by hand

Baselines for six band gaps

materialΔχ (Pauling)Eg measured (eV)
Si0.001.12
GaAs0.371.42
GaN1.233.40
ZnO1.793.37
MgO2.137.8
NaCl2.238.5

Room-temperature gaps, rounded; Δχ from Pauling electronegativities.

1
Mean, and median (sort, average the middle two):\[ \bar y = \frac{25.61}{6} = 4.27\ \text{eV}, \qquad \tilde y = \frac{3.37 + 3.40}{2} = 3.39\ \text{eV} \]
2
Errors of each baseline on the six materials:
predictRMSE (eV)MAE (eV)
mean 4.272.892.59
median 3.393.022.30

Check and meaning

Each baseline wins under its own loss, as derived. An error of about 2.5 eV is the bar: a useful model of band gaps must do much better.

Training error versus test error · 1

More flexible is not always better

no training data Ga fraction x in In₁₋ₓGaₓAs band gap Eg (eV)

The experiment

10 training "measurements" of the alloy band gap (dots), simulated from the bowing equation with 0.05 eV noise. 40 more held back as a test set (open circles). Fit polynomials of degree 0 to 9 by least squares.

degree 1degree 2degree 9true curve

Try it (outside the video)

degree 2
train RMSE — · test RMSE —
Training error versus test error · 2

Training error always falls; test error has a minimum

noise level 0.05 eV polynomial degree (model flexibility) RMSE (eV, log scale) test training
degreetrain RMSEtest RMSE
00.2770.323
20.0330.049
60.0210.107
9≈ 0116

What the model learned

Too simple (degree 0): misses the trend, both errors large: underfitting. Too flexible (degree ≥ 6): fits the noise, test error grows: overfitting. At the best degree the test error is close to the noise, 0.05 eV: we cannot beat the noise in the data.

Worked problem 2 · train on five, test on one

A line in Δχ: training error versus test error by hand

Given: a line fitted by least squares (derived next week) to Si, GaAs, GaN, ZnO and MgO: \(\hat E_g = 0.6 + 2.6\,\Delta\chi\) eV. NaCl is kept out as the test material.

materialΔχÊgEg|error|
Si0.000.601.120.52
GaAs0.371.561.420.14
GaN1.233.803.400.40
ZnO1.795.253.371.88
MgO2.136.147.81.66
1
Training MAE (average of the five absolute errors):\[ \frac{0.52+0.14+0.40+1.88+1.66}{5} = 0.92\ \text{eV} \]
2
Test on NaCl (Δχ = 2.23): \(\hat E_g = 0.6 + 2.6\times2.23 = 6.40\) eV, measured 8.5 eV → error 2.1 eV.
More than twice the training error.
3
Compare with the baseline: the mean of the five training gaps, 3.42 eV, misses NaCl by 5.1 eV.
The line has learned something real, but less than its training error suggests.

Why the test is worse

Δχ = 2.23 lies just beyond the training range (0 to 2.13): an extrapolation. And one feature cannot tell ZnO from GaN: the gap also depends on bonding and structure.

The hidden assumption

A test set is honest only if it looks like the future

training data (e.g. oxides) feature 1 feature 2

Interpolation

A new material inside the cloud of training data. Errors are usually close to the test error.

Extrapolation

A new chemistry outside the cloud (say, a nitride). The model has never seen anything like it; errors can be far larger, and the model does not warn you.

Duplicates leak

If the same compound sits in both the training and the test set, the test becomes a memory test. Week 6 shows how to split honestly.

Data cleaning · 1

A raw table, as you will really find it

#formulastructuregapunitsourceproblem → action
1ZnOwurtzite3.37eVhandbookkeep
2ZnOwurtzite3.37eVreview papersame compound, same structure → merge with #1
3GaNwurtzite3400meVpaperunit → convert to 3.40 eV
4MgOrock salt—eVhandbookmissing → find the value, or drop the row
5Sidiamond11.2eVstudent notesimplausible (Si is 1.12) → decimal slip: check the source
6TiO₂rutile3.0eVhandbookkeep
7TiO₂anatase3.2eVhandbookkeep: a different polymorph, not a duplicate
8ZnOwurtzite0.73eVDFT (PBE)computed, not measured → separate column or flag
Every action is written down. Cleaning that is not documented cannot be checked or repeated.
Data cleaning · 2

Four rules, and why statistics alone are not enough

1
Duplicates: same composition and same structure. Polymorphs are different materials.
Otherwise one compound counts twice, and may land in train and test.
2
Units and physical bounds: one unit per column; check limits (a gap is ≥ 0, a fraction lies in 0–1).
Cheap checks that catch most errors.
3
Outliers: flag, check the source, then decide. Never delete silently.
An "outlier" may be the most interesting material.
4
Missing values: drop, or fill in (impute) with statistics from the training set only.
Using test data to fill gaps leaks information.
\[ M_i = \frac{0.6745\,(y_i - \tilde y)}{\text{MAD}}, \quad \text{MAD} = \text{median}\,|y_i - \tilde y| \]
robust (modified) z-score; flag if |Mi| > 3.5. ỹ = median

Try it on the slip

Take the six correct gaps of worked problem 1 and add the slipped entry 11.2 eV: median 3.40, MAD 2.28, so \(M = 0.6745\times7.8/2.28 = 2.3\). Not flagged.

Physical meaning

Band gaps really do span 0 to over 10 eV, so 11.2 eV looks normal to a statistic. Only materials knowledge (silicon is 1.12 eV) catches it. Use both.

Label bias · computed versus measured

DFT band gaps are consistently too small

perfect agreement measured band gap (eV) DFT (PBE) band gap (eV)

A systematic bias

The common PBE functional underestimates gaps by about 25–80 % here (ZnO worst: 0.7 vs 3.37 eV). Typical database values, rounded.

What a model learns from these labels

A model trained on PBE gaps predicts PBE gaps, bias included, however accurate it is. This is the answer to Why 2: same compound, different label types.

What to do: keep computed and measured in separate columns; train on one type; if you must combine, add the source as a feature or learn the correction.

Link to Thermodynamics · the stability target we use all term

Energy above the convex hull, Ehull

fraction of B in A₁₋ₓBₓ formation energy (eV/atom)
1
Hull = lowest line joining the compounds (the stable set at 0 K).
As in the Thermodynamics lectures on phase diagrams.
2
Ehull = vertical distance of a compound above the hull. \(E_{\text{hull}} = 0\): stable.
Energy gained by decomposing into the hull phases.
3
Example: at x = 0.6, the hull lies at −0.34 eV/atom, the compound at −0.30 → \(E_{\text{hull}} = 40\) meV/atom. At x = 0.25: 10 meV/atom.
Week 5 uses 25 meV/atom as a "likely synthesizable" cut.
Decision · before any code

Is machine learning the right tool?

1

Does a trusted equation already work? (Vegard, bowing, Arrhenius, Nernst) → use the equation.

2

Is the property expensive, and do you need many predictions? If not, just measure or compute it.

3

Do you have enough clean, consistent data? Tens of points: a simple model with few weights. Thousands: flexible models become possible.

4

Will you predict inside the data? If you need new chemistry, plan for extrapolation, uncertainty and checks.

Always beat a baseline

Report your model next to (a) the mean, and (b) the simplest physical model. If it does not win clearly on the test set, it has not earned its complexity.

Physical meaning

Machine learning does not replace physics; it fills the gaps where physics is too expensive or too incomplete. A good model often uses physics, as the parabola did.

Lab 1 · this week in Colab

Load, clean and plot a band-gap table

import pandas as pd
df = pd.read_csv("bandgaps_raw.csv")
meV = df.unit == "meV"
df.loc[meV, "gap"] /= 1000      # one unit: eV
df["unit"] = "eV"
key = ["formula", "structure", "label_type"]
df = df.drop_duplicates(subset=key)
df = df.dropna(subset=["gap"])
print(df.query("gap < 0 or gap > 15"))  # inspect
exp = df[df.label_type == "measured"]
exp.plot.scatter("dchi", "gap")
mae = (exp.gap - exp.gap.median()).abs().mean()
print("median baseline MAE:", mae)

Exercises

  • Find and fix the unit, duplicate and decimal errors; log every change.
  • Compare the measured and PBE gaps on a parity plot.
  • Compute the mean and median baselines and their MAE and RMSE.
  • Repeat the polynomial experiment with 10 and with 40 training points.

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 · Perfect fit, useless model

With as many weights as points (degree 9, 10 points) a model memorizes the noise: training error 0, test error 116 eV. Judge models only on data they have not seen.

2 · ZnO: 3.37 or 0.73 eV?

3.37 eV is measured; 0.73 eV is a DFT (PBE) value, which underestimates gaps. Same compound, different label type: flag and separate them.

3 · Small error, new compound fails

Training error is optimistic (0.92 vs 2.1 eV for NaCl). A test set must hold unseen, non-duplicated materials like those you will predict; new chemistry is extrapolation.

4 · When ML is the wrong tool

When a trusted equation works (the alloy bowing law), when data are few or inconsistent, or when a model cannot beat a simple baseline.

Check your understanding · click a card to reveal

Concept check

Q1. A model has a training MAE of 0.01 eV and a test MAE of 0.9 eV. What happened, and what would you try?
Overfitting: it memorized the training set. Use a simpler model (fewer weights), more data, or regularization (next week).
Q2. Five band gaps: 1.1, 1.4, 3.4, 3.4, 30 eV (the last is a typo). Which constant baseline is less affected, and why?
The median (3.4 eV) ignores the single wild value; the mean (7.9 eV) is pulled up by it. Squared loss → mean, absolute loss → median.
Q3. TiO₂ appears twice, with gaps 3.0 and 3.2 eV. Duplicate?
Check the structure: rutile (3.0) and anatase (3.2) are different polymorphs, so keep both. A duplicate needs the same composition and structure.
Q4. You fill missing values with the mean of the whole dataset, then split into train and test. What is wrong?
Leakage: test values influenced the training data. Split first, then compute the fill-in mean from the training set only.
Wrap-up

Summary and next lecture

1
Learning = choose x, y, a model f(x; w) and a loss; minimize the average training loss; then measure the error on held-back data.
2
Baselines: the mean minimizes squared loss, the median absolute loss. Every model must beat them.
3
Training error falls with flexibility; test error has a minimum near the noise level. Too simple = underfitting, too flexible = overfitting.
4
Clean before you model: duplicates (not polymorphs), units, bounds, outliers, missing values; document every step. Statistics plus materials knowledge.
5
Computed (DFT) and measured labels differ systematically: never mix them unflagged.

This week

Lab 1: load, clean and plot a band-gap table; baselines; the polynomial experiment.

Next lecture · Linear regression and regularization

We derive the least-squares line of worked problem 2 from the gradient rules of today (the normal equations), solve it by gradient descent, and tame overfitting with ridge and lasso. Example: melting points of 37 metals from elemental properties, ridge versus plain least squares.

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. 1–2 (free online).
  • S. Sandfeld, Materials Data Science, Springer (2024): chapters on materials data and data quality.
  • K. T. Butler, D. W. Davies, H. Cartwright, O. Isayev, A. Walsh, "Machine learning for molecular and materials science," Nature 559, 547 (2018).
  • A. Jain et al., "The Materials Project," APL Mater. 1, 011002 (2013); J. E. Saal et al., OQMD, JOM 65, 1501 (2013); K. Choudhary et al., JARVIS, npj Comput. Mater. 6, 173 (2020).
  • I. Vurgaftman, J. R. Meyer, L. R. Ram-Mohan, "Band parameters for III–V compound semiconductors," J. Appl. Phys. 89, 5815 (2001) (InGaAs gaps and bowing).
  • B. Iglewicz, D. C. Hoaglin, How to Detect and Handle Outliers, ASQC (1993) (modified z-score).

Image credits (Wikimedia Commons)

  • Autonomous lab (A-Lab) robot arm and X-ray diffractometer: N. J. Szymanski, B. Rendy et al., CC BY 4.0 — File page; study: N. J. Szymanski et al., Nature 624, 86 (2023).
  • Pleiades supercomputer racks: NASA Ames Research Center, public domain — File page
  • Silicon wafers 2 to 8 inch: Stahlkocher, CC BY-SA 3.0 — File page

All schematics and plots were drawn for this course. The alloy data are simulated from the bowing equation; the PBE band gaps are typical database values, rounded; the hull compounds are illustrative.