It is d × d and symmetric. Its entries are sums over materials: \((X^{\mathsf T}X)_{jk} = \sum_i x_{ij}x_{ik}\). With a column of ones and one feature x:\[ X^{\mathsf T}X = \begin{bmatrix} n & \sum x_i\\ \sum x_i & \sum x_i^2\end{bmatrix} \]
Why we need this
The loss is a quadratic bowl in w. Rule 3 gives its slope in one line, and setting the slope to zero gives the best weights.
Derivation · least squares
The normal equations: XTX w = XTy
1
Loss: sum of squared residuals \(L(\mathbf w) = \lVert X\mathbf w - \mathbf y\rVert^2\).
Dividing by n would not move the minimum, so we drop it.
2
Expand (primer): \(L = \mathbf w^{\mathsf T}X^{\mathsf T}X\mathbf w - 2\mathbf w^{\mathsf T}X^{\mathsf T}\mathbf y + \mathbf y^{\mathsf T}\mathbf y\).
A quadratic bowl in w.
3
Gradient, term by term with the three rules:\[ \nabla_{\mathbf w}L = 2X^{\mathsf T}X\mathbf w - 2X^{\mathsf T}\mathbf y = 2X^{\mathsf T}(X\mathbf w - \mathbf y) \]
Quadratic term → 2Aw; cross term → constant vector; yᵀy has no w.
4
Set it to zero:\[ X^{\mathsf T}X\,\mathbf w^* = X^{\mathsf T}\mathbf y \quad\Rightarrow\quad \mathbf w^* = (X^{\mathsf T}X)^{-1}X^{\mathsf T}\mathbf y \]
d linear equations for d weights: the "normal equations".
Sanity check: only a column of ones
Then \(X^{\mathsf T}X = n\) and \(X^{\mathsf T}\mathbf y = \sum_i y_i\), so \(w_0 = \bar y\): the mean baseline of lecture 1 comes out again.
What the model learned
At the optimum \(X^{\mathsf T}(\mathbf y - X\mathbf w^*) = 0\): the residuals are orthogonal to every feature column. They sum to zero and keep no linear trend in any feature. What is left is what a line in these features cannot see.
When it fails
If two features are (nearly) copies of each other, XTX cannot be inverted (or nearly so): the weights become huge and unstable. Ridge fixes this.
Worked problem 1 · by hand
A three-point regression you can check with a calculator
1
Data (toy numbers): x = 0, 1, 2 and y = 2, 3, 7. With a column of ones:\[ X^{\mathsf T}X = \begin{bmatrix}3&3\\3&5\end{bmatrix},\quad X^{\mathsf T}\mathbf y = \begin{bmatrix}12\\17\end{bmatrix} \]
Check: residuals sum to 0. Training MAE 0.91 eV (0.92 with the rounded line). NaCl: \(\hat E_g\) = 6.31 eV vs 8.5 measured, error 2.2 eV.
Same conclusion as lecture 1: extrapolation is worse.
Filled: the five training materials. Open: NaCl, held out as the test material.
Same problem, another route · gradient descent
Gradient descent finds the same line, if the step is not too large
1
Update for the average loss \(L = \lVert X\mathbf w-\mathbf y\rVert^2/n\):\[ \mathbf w \leftarrow \mathbf w - \eta\,\tfrac{2}{n}X^{\mathsf T}(X\mathbf w - \mathbf y) \]
The gradient we just derived, divided by n.
2
First step by hand from w = 0: gradient \(= -\tfrac25[17.11,\ 27.35] = [-6.84,\ -10.94]\). With η = 0.05: w = [0.34, 0.55].
Downhill, towards [0.59, 2.57].
3
Stability: near the minimum, the error along each direction is multiplied by \(1 - \eta h\) per step, where h = curvature (eigenvalue of \(\tfrac2n X^{\mathsf T}X\): 0.50 and 5.25).\[ |1-\eta h| < 1 \;\Rightarrow\; \eta < \frac{2}{h_{\max}} = 0.38 \]
h = how steeply the bowl curves along each of its two main directions (these are the eigenvalues of the matrix; the lecture 3 primer explains them). Lecture 1's bowl had h = 2.
What the model learned
Exactly the normal-equation weights, just more slowly. We need this route when d is huge (neural networks, week 9), where XTX is too big to invert.
Materials example 1 · when a one-feature line is physics
Vegard's law: the lattice parameter of Si1−xGex
Silicon. Enricoros, public domainGermanium. Jurii, CC BY 3.0
Simulated data: 9 alloys from the measured curve of Dismukes et al. (1964) plus 0.002 Å noise. Fit: \(\hat a = 5.426 + 0.229\,x\) Å. RMSE 0.0034 Å, vs 0.074 Å for the mean baseline (22 × larger).
What the model learned
The weights are physics: w₀ ≈ aSi = 5.431 Å and w₀ + w₁ = 5.655 ≈ aGe = 5.658 Å. A tiny bowing (about −0.007 Å at x = 0.5) is left in the residuals. Outside 0 ≤ x ≤ 1 the line means nothing.
λ ≥ 0 sets the price. Standardize features first; do not penalize the intercept.
2
Gradient (same rules, plus \(\nabla\,\mathbf w^{\mathsf T}\mathbf w = 2\mathbf w\)):\[ \nabla L = 2X^{\mathsf T}(X\mathbf w-\mathbf y) + 2\lambda\mathbf w \]
3
Set to zero and collect the w terms:\[ (X^{\mathsf T}X + \lambda I)\,\mathbf w = X^{\mathsf T}\mathbf y \;\Rightarrow\; \mathbf w_{\text{ridge}} = (X^{\mathsf T}X+\lambda I)^{-1}X^{\mathsf T}\mathbf y \]
4
Always solvable: eigenvalues of XTX are ≥ 0; adding λI makes every one ≥ λ > 0.
λ = 0 gives back the normal equations. A huge λ drives all weights to 0, so the model predicts the mean: the lecture 1 baseline. Units: λ has the units of Σx², so features must be on a common scale.
What the model learned
The smallest weights that still fit. When two features carry the same information, ridge shares the weight between them instead of +huge and −huge. It cannot learn a trend that the features do not contain. Choose λ by validation, never on the test set.
Ridge in action · lecture 1's degree-9 polynomial
Same ten points, same degree 9: λ decides overfit or underfit
λ
train RMSE
test RMSE
0 (least squares)
≈ 0
116 eV
0.01
0.020
0.073
10
0.198
0.250
Try it (outside the video)
log₁₀ λ −2
train RMSE — · test RMSE —
What the model learned
Ridge cut the test error from 116 to 0.073 eV without removing a single term. But the parabola of lecture 1 (0.049 eV) still wins: the right shape beats a penalty.
Derivation · lasso and the soft threshold
Lasso: an absolute-value price sets small weights to exactly zero
One feature: with \(s = \sum x_i^2\) and the least-squares weight \(z = \sum x_i y_i / s\), complete the square:\[ L(w) = \tfrac{s}{2}(w - z)^2 + \lambda|w| + \text{const} \]
3
Smooth pieces: if w > 0, \(s(w-z)+\lambda = 0 \Rightarrow w = z - \lambda/s\), valid only if \(z > \lambda/s\). If w < 0, \(w = z + \lambda/s\), valid only if \(z < -\lambda/s\).
4
Otherwise the minimum sits on the kink at 0:\[ w_{\text{lasso}} = \operatorname{sign}(z)\,\max\!\big(|z| - \lambda/s,\ 0\big) \]
The "soft threshold". Compare ridge: w = z·s/(s + λ), never exactly 0.
Why exactly zero?
The slope of λ|w| is ±λ however small w is: the pull towards 0 never fades. Ridge's pull, 2λw, fades as w → 0. So lasso selects features; ridge only shrinks them.
Worked problem 3 · by hand
Gradient descent, ridge and lasso on the three points
1
Centre the data of problem 1 (x̄ = 1, ȳ = 4): x = −1, 0, 1 and y = −2, −1, 3. Then s = Σx² = 2, Σxy = 5, z = 2.5.
Centring removes the intercept; only the slope w is left.
2
Gradient descent on \(L = \sum(y_i - w x_i)^2\): dL/dw = 4w − 10. With η = 0.1 from w = 0: w = 1, 1.6, 1.96, … The gap to 2.5 shrinks 2.5 → 1.5 → 0.9 → 0.54, a factor 1 − 4η = 0.6.
(Ridge was written without ½, lasso with ½: equal λ are not equally strong.)
method
slope w
ŷ at x = 3
least squares
2.5
9.0
ridge, λ = 2
1.25
6.5
lasso, λ = 2
1.5
7.0
lasso, λ = 6
0
4.0
ŷ = ȳ + w (x − x̄) = 4 + 2w at x = 3.
Meaning
Every penalty pulls the prediction towards the mean, 4. The strongest lasso returns exactly the lecture 1 baseline: no feature is worth its price.
Materials example 2 · melting points of 37 metals
Ridge versus plain least squares on real elemental data
Data: Tm of 37 metals with cohesive energy Ecoh, bulk modulus B, molar volume Vm, Pauling χ (rounded handbook values). Features: the 4 plus their 10 pairwise products = 14, standardized. 18 metals train, 19 test, 500 random splits; ridge λ chosen by leave-one-out on the training set (fit on 17 metals, test on the 18th, rotate, average; lecture 6 treats this properly); median λ ≈ 2.5.
W filament, Tm ≈ 3695 K. Yakushev.dim, CC BY 4.0Ga, melts near 303 K. foobar, CC BY-SA 3.0
What the model learned
With 15 weights and 18 metals, least squares fits noise: it loses to the mean baseline in 41 % of splits. Ridge rescues it (312 K). But one physical feature does as well: strong bonds melt late, \(T_m \approx 32 + 392\,E_{\text{coh}}\) K, correlation 0.96.
Inside the weights · ridge and lasso paths
As λ grows, ridge shrinks every weight; lasso drops them one by one
Ridge
Lasso
All 37 metals, 4 standardized features. Least-squares weights: Ecoh +729, B +293, Vm −75, χ −210 K. Lasso keeps Ecoh to the end: a learned feature ranking.
Derivation · the bias–variance decomposition
Expected test error = bias² + variance + noise
1
Set-up: \(y = f(x) + \varepsilon\), with \(\mathbb E[\varepsilon]=0\), \(\operatorname{Var}\varepsilon = \sigma^2\). The prediction ŷ(x) depends on the random training set D; a new ε is independent of D.
2
Split off the noise: \(y-\hat y = (f-\hat y) + \varepsilon\), square and average:\[ \mathbb E[(y-\hat y)^2] = \mathbb E[(f-\hat y)^2] + 2\,\underbrace{\mathbb E[(f-\hat y)\,\varepsilon]}_{=\,0} + \sigma^2 \]
The cross term vanishes: ε is independent of ŷ and has mean 0.
3
Add and subtract the average prediction \(\bar{\hat y} = \mathbb E_D[\hat y]\):\[ \mathbb E[(f-\hat y)^2] = (f-\bar{\hat y})^2 + 2(f-\bar{\hat y})\underbrace{\mathbb E[\bar{\hat y}-\hat y]}_{=\,0} + \mathbb E[(\hat y-\bar{\hat y})^2] \]
Error of the average model over many training sets. Large when the model is too simple or λ too large: it cannot bend to the truth.
Variance
How much the model jumps when the training set changes. Large when the model is too flexible or λ too small.
Noise σ²
The floor. No model can beat it (lecture 1: σ = 0.05 eV).
Sanity check
All terms ≥ 0, units of y². Even a perfect model pays σ².
Bias and variance in numbers · degree-9 ridge on the alloy
Small λ: variance wins. Large λ: bias wins. The best λ balances them.
λ
bias²
variance
total
10⁻⁴
0.0020
0.96
0.97
0.1
0.0074
0.0024
0.0123
10
0.063
0.0003
0.065
Simulated: lecture 1's 10 training x, new noise (σ = 0.05 eV) each time; errors averaged over 0 ≤ x ≤ 1. Best λ for the error averaged over many training sets: 0.1; on the one lecture-1 set: 0.01. The best λ depends on the data at hand, which is why it is chosen by validation.
What this means
Regularization trades a little bias for a big cut in variance. It cannot touch σ². The total error at the best λ is about 5 × the noise, mostly from x beyond the last training point (0.88).
Diagnosis · learning curves
Will more data help? Plot the error against the training-set size
line (degree 1)degree 9, ridge λ = 10⁻³solid: test · dashed: training · simulated, median of 300 sets
High bias (the line)
Curves meet early, at about 0.064 eV, above the noise. More data will not help: change the model or features.
High variance (degree 9)
Big gap at n = 10 (test 0.20, training 0.02 eV) that closes with data: 0.053 eV at n = 200. More data does help.
Practical rule
Below about 30–50 points the line wins; above, the flexible model wins.
Lab 2 · this week in Colab
Least squares, gradient descent, ridge and lasso in Python
import numpy as np
X = np.c_[np.ones(5), dchi] # lecture-1 data
w = np.linalg.solve(X.T @ X, X.T @ eg) # normal equationsw_gd = np.zeros(2)
for it in range(200):
w_gd -= eta * 2/5 * X.T @ (X @ w_gd - eg)from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import RidgeCV, LassoCV
ridge = make_pipeline(StandardScaler(),
RidgeCV(alphas=np.logspace(-3, 3, 31)))
ridge.fit(X_train, y_train)lasso = make_pipeline(StandardScaler(), LassoCV(cv=5))
lasso.fit(X_train, y_train)
print(lasso[-1].coef_) # which weights are 0?# sklearn Lasso alpha = our λ / n
Exercises
Solve the band-gap line with the normal equations and with gradient descent; find the η where descent diverges (≈ 0.38).
Melting points: least squares vs ridge with 14 features, 18 train / 19 test, many random splits.
Plot the lasso path for the 4 raw features. Which survives longest?
Learning curves for the line and the degree-9 ridge model on the alloy. Where do they cross?
Runs in Google Colab; no GPU needed. Data files and notebook are posted with this lecture.
Answers to the why questions
The four puzzles, solved
1 · Gradient descent runs away
Each step multiplies the error along a direction of curvature h by 1 − ηh. If η > 2/hmax, that factor is below −1: every step overshoots further. Band-gap line: limit 0.38; η = 0.45 diverged.
2 · Lasso zeros, ridge shrinks
|w| has a corner at 0 with slope ±λ that never fades, so the soft threshold returns exactly 0 when |z| ≤ λ/s. Ridge's pull 2λw vanishes near 0: w = z·s/(s+λ) is never exactly 0.
3 · 14 features lose to the mean
15 weights from 18 metals: least squares fits the noise and the weights swing between splits (test RMSE 811 K vs 976 K for the mean). Ridge with λ ≈ 2.5 tames the variance: 312 K. One physical feature, Ecoh, does as well: 286 K.
4 · Will more data help?
Read the learning curve. Training and test errors meet above the noise → high bias: more data will not help; change the model or features. A large gap that is still closing → high variance: more data helps.
Check your understanding · click a card to reveal
Concept check
Q1. A loss has curvatures (steepness along the two main directions of the bowl) 1 and 20. What is the largest safe learning rate?
η < 2/20 = 0.1. Even then, the flat direction shrinks only by 1 − 0.1 × 1 = 0.9 per step: slow.
Q2. You include density in g/cm³ and again in kg/m³. What happens to least squares, and to ridge?
The columns are copies (after scaling): XTX is singular and the weights are not unique. Ridge gives a unique answer and shares the weight.
Q3. One feature: Σx² = 4, Σxy = 6, λ = 8. Find the lasso weight (½ convention) and the ridge weight.
z = 1.5 and λ/s = 2 > 1.5, so lasso w = 0. Ridge: w = 6/(4 + 8) = 0.5.
Q4. Training RMSE 0.30 eV, test RMSE 0.31 eV, noise about 0.05 eV. Bias or variance? Collect more data?
High bias: the curves have met far above the noise. More data will not help; add features, use a more flexible model, or lower λ.
Wrap-up
Summary and next lecture
1
Least squares: \(\nabla\lVert X\mathbf w-\mathbf y\rVert^2 = 2X^{\mathsf T}(X\mathbf w-\mathbf y) = 0 \Rightarrow X^{\mathsf T}X\mathbf w = X^{\mathsf T}\mathbf y\). Residuals are orthogonal to every feature.
2
Gradient descent reaches the same weights if η < 2/hmax; otherwise it diverges.
Expected test error = bias² + variance + σ². λ trades one for the other; learning curves tell which one you have.
5
Physics first: Vegard's law and Tm ∝ Ecoh beat or match bigger models.
This week
Lab 2: normal equations, gradient descent, ridge and lasso, learning curves. Problem set 1 (weeks 1–3) comes out next week.
Next lecture · Representing a material
Today the features were handed to us. Next week we build them: why raw atomic coordinates fail, composition descriptors from elemental properties, structure descriptors, feature scaling, and feature selection with today's lasso. Lab 3 uses pymatgen and matminer.
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. 2 (bias–variance), Ch. 3 (linear regression), Ch. 6 (ridge and lasso).
K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): chapter on linear regression.
C. M. Bishop, H. Bishop, Deep Learning: Foundations and Concepts, Springer (2024): chapter on single-layer networks for regression.
A. E. Hoerl, R. W. Kennard, "Ridge regression," Technometrics 12, 55 (1970). R. Tibshirani, "Regression shrinkage and selection via the lasso," J. R. Stat. Soc. B 58, 267 (1996).
L. Vegard, Z. Phys. 5, 17 (1921). J. P. Dismukes, L. Ekstrom, R. J. Paff, "Lattice parameter and density in germanium-silicon alloys," J. Phys. Chem. 68, 3021 (1964).
C. Kittel, Introduction to Solid State Physics, 8th ed., Wiley (2005): cohesive energies and bulk moduli of the elements.
Image credits (Wikimedia Commons)
Silicon: Enricoros at English Wikipedia, public domain — File page
Polycrystalline germanium: Jurii, CC BY 3.0 — File page
Tungsten filament: Yakushev.dim, CC BY 4.0 — File page
Gallium crystals: foobar (en.wikipedia), CC BY-SA 3.0 — File page
All schematics and plots were drawn for this course from numbers computed in Python. The Si–Ge points and the In₁₋ₓGaₓAs points are simulated (labelled on the slides); the 37-metal data are rounded handbook values; three-point problems use toy numbers.