ML for Materials Science · Week 7 · Lecture 7

Unsupervised Learning

Finding structure in materials data without labels: principal components, clusters and maps.
Undergraduate course · 16 weeks
principal component 1 principal component 2 231 simulated XRD patterns, no labels given
Recap · lecture 6

Last week we tested models honestly. Today there is nothing to test against.

1

k-fold cross-validation gives an error estimate and its spread.

2

Nested CV: a score tuned on the same folds is optimistic.

3

Grouped splits: hold out whole composition families or structure prototypes.

4

Leakage: duplicates, polymorph families, preprocessing before the split.

What it left open

Every method so far needed a label y for each material. But most materials data arrive without labels: thousands of XRD patterns, spectra and micrographs that nobody has indexed yet.

supervised (weeks 2–6)unsupervised (today)
dataX and yX only
goalpredict ycompress, group, visualize
checktest errorno single right answer: check with physics
Unsupervised learning finds structure in X; physics decides whether that structure is real.
Why questions · answered at the end

Four puzzles for today

WHY 1

A combinatorial wafer gives 231 XRD patterns that nobody has indexed. How can a computer draw the phase map without being told a single phase?

WHY 2

PCA of four elemental properties says PC1 is "melting point", with 99.7 % of the variance. Did PCA discover the most important property?

WHY 3

A t-SNE map puts two groups of compounds far apart. Are those compounds very different?

WHY 4

k-means always returns exactly k clusters, even when there are none. How do you choose k, and when should you distrust it?

Unsupervised learning · the big picture

Three jobs we can do with X alone

Key picture: one XRD pattern with 501 intensities is one point in a 501-dimensional space, one axis per 2θ angle. Similar patterns are nearby points.

1

Dimension reduction · PCA

Replace 501 numbers by a few new coordinates that keep most of the variation.

2

Clustering · k-means

Put similar samples into groups, for example phase regions on a wafer.

3

Maps · t-SNE and UMAP

Draw neighbours in 2-D for the human eye. Pictures, not measurements.

A laboratory X-ray diffractometer
X-ray diffractometer. Sufangxi, CC BY-SA 4.0
A benchtop Raman microscope
Benchtop Raman microscope. Ijon, CC BY-SA 4.0
Math primer · covariance and eigenvectors

The covariance matrix, and the directions it only stretches

1
Variance of feature j:\[ s_j^2 = \frac1n\sum_{i=1}^{n}(x_{ij}-\bar x_j)^2 \]
The average squared distance from the mean.
2
Covariance matrix of the centred data \(\tilde X\) (row i is \(\mathbf x_i-\bar{\mathbf x}\)):\[ C = \frac1n\tilde X^{\mathsf T}\tilde X,\qquad C_{jk}=\frac1n\sum_i \tilde x_{ij}\tilde x_{ik} \]
Diagonal: the variances. Off-diagonal: do two features rise together? C is symmetric.
3
Eigenvector v with eigenvalue μ, found from \(\det(C-\mu I)=0\):\[ C\mathbf v = \mu\,\mathbf v \]
A direction that C does not turn, only stretches by μ. For symmetric C: real μ, orthogonal v.
\[ C=\begin{bmatrix}2.5&2\\2&2.5\end{bmatrix} \]\[ C\begin{bmatrix}1\\1\end{bmatrix}=\begin{bmatrix}4.5\\4.5\end{bmatrix}=4.5\begin{bmatrix}1\\1\end{bmatrix} \]\[ C\begin{bmatrix}1\\-1\end{bmatrix}=\begin{bmatrix}0.5\\-0.5\end{bmatrix}=0.5\begin{bmatrix}1\\-1\end{bmatrix} \]

Notation: we write μ for an eigenvalue, because λ is our regularization strength. Many textbooks write λ. Software divides C by n − 1 instead of n; ratios of eigenvalues do not change.

Why we need this

PCA will turn out to be exactly this eigenvalue problem: the eigenvectors of C are the new axes.

Derivation · principal component analysis

Maximize the variance of a projection → an eigenvalue problem

1
Centre the data: \(\tilde{\mathbf x}_i = \mathbf x_i - \bar{\mathbf x}\).
Variance is measured about the mean.
2
Project on a unit direction u, \(\mathbf u^{\mathsf T}\mathbf u = 1\):\[ z_i = \mathbf u^{\mathsf T}\tilde{\mathbf x}_i \]
One number per material: its coordinate along u.
3
Variance of the projections:\[ \frac1n\sum_i z_i^2 = \mathbf u^{\mathsf T}\Big(\frac1n\sum_i\tilde{\mathbf x}_i\tilde{\mathbf x}_i^{\mathsf T}\Big)\mathbf u = \mathbf u^{\mathsf T}C\,\mathbf u \]
Write \(z_i^2 = \mathbf u^{\mathsf T}\tilde{\mathbf x}_i\,\tilde{\mathbf x}_i^{\mathsf T}\mathbf u\), pull u out of the sum.
4
Maximize with a Lagrange multiplier μ:\[ \mathcal L(\mathbf u,\mu) = \mathbf u^{\mathsf T}C\mathbf u - \mu(\mathbf u^{\mathsf T}\mathbf u - 1) \]
Without the constraint, a longer u would always give more "variance".
5
Set the gradient to zero:\[ \nabla_{\mathbf u}\mathcal L = 2C\mathbf u - 2\mu\mathbf u = 0 \;\Rightarrow\; C\mathbf u = \mu\mathbf u \]
Rules \(\nabla(\mathbf u^{\mathsf T}A\mathbf u)=2A\mathbf u\) (A symmetric, lecture 2) and \(\nabla(\mathbf u^{\mathsf T}\mathbf u)=2\mathbf u\) (lecture 1).
6
Which eigenvector? The variance is \(\mathbf u^{\mathsf T}C\mathbf u = \mu\,\mathbf u^{\mathsf T}\mathbf u = \mu\): take the largest μ₁.
PC 2: the best direction orthogonal to u₁ is the eigenvector of μ₂, and so on.
Sanity checks · what PCA learns

Eigenvalues share out the total variance

\[ \underbrace{\sum_j C_{jj}}_{\text{total variance}} = \operatorname{tr}C = \mu_1+\mu_2+\dots+\mu_d, \qquad \text{EVR}_j = \frac{\mu_j}{\sum_k \mu_k} \]
1
Limit, no correlation: two features with equal variance s² and zero covariance → \(C = s^2 I\). Every direction is an eigenvector.
Correct: a round cloud has no preferred direction.
2
Limit, perfect correlation: \(x_2 = x_1\) → μ₂ = 0, EVR₁ = 100 %.
Correct: the points lie on one line, one number describes them.
3
Units: z has the units of x, and μ the units of x².
Features in different units must be put on one scale first.

What the model learned

  • Loadings u₁, u₂, …: the recipe, how much of each feature goes into a new axis.
  • Scores z: each material's coordinates on those axes.
  • Only linear correlations. A curved band of data needs several components.
  • Large variance is not the same as relevant: the property you care about may hide in a small component.
  • Sensitive to units and to outliers (squares, as in lecture 1).
Worked problem 1 · by hand

PCA of four samples with two features

samplex₁x₂x̃₁x̃₂z₁
154212.12
245122.12
312−2−1−2.12
421−1−2−2.12

Two features measured on four samples; small numbers chosen to be checked with a calculator.

Check

tr C = 2.5 + 2.5 = 5 = 4.5 + 0.5 ✓. Variance of the scores z₁: (4 × 2.12²)/4 = 4.5 = μ₁ ✓. One number per sample keeps 90 % of the variation.

1
Mean (3, 3); subtract it → columns x̃₁, x̃₂.
Centre first, as derived.
2
Covariance: \(C_{11}=\tfrac{4+1+4+1}{4}=2.5,\ C_{12}=\tfrac{2+2+2+2}{4}=2\) \[ C=\begin{bmatrix}2.5&2\\2&2.5\end{bmatrix} \]
3
Eigenvalues: \((2.5-\mu)^2 - 4 = 0 \Rightarrow \mu = 2.5 \pm 2\), so μ₁ = 4.5, μ₂ = 0.5.
det(C − μI) = 0 for a 2×2 matrix is a quadratic.
4
Eigenvectors: \(\mathbf u_1 = \tfrac{1}{\sqrt2}(1,1),\ \mathbf u_2 = \tfrac{1}{\sqrt2}(1,-1)\).
Unit length, orthogonal.
5
Explained variance \(4.5/5 = 90\,\%\). Scores \(z_1 = (\tilde x_1+\tilde x_2)/\sqrt2 = \pm 2.12\).
PC 1 is "both features together".
A second view · reconstruction

Maximum variance = minimum reconstruction error

feature x₁ feature x₂
1
Reconstruct from PC 1 only: \(\hat{\mathbf x}_i = \bar{\mathbf x} + z_i\,\mathbf u_1\).
Keep one number per sample, then go back to the original space.
2
Pythagoras (the residual is ⟂ to u, \(\lVert\mathbf u\rVert = 1\)):\[ \lVert\tilde{\mathbf x}_i\rVert^2 = z_i^2 + \lVert\tilde{\mathbf x}_i - z_i\mathbf u\rVert^2 \]
Length² = part along u + part across u.
3
Average over samples:\[ \text{mean error} = \operatorname{tr}C - \mathbf u^{\mathsf T}C\mathbf u = \mu_2 \]
tr C is fixed, so minimizing the error = maximizing the variance.

By hand and in practice

Sample 1: (5, 4) → (4.5, 4.5); error 0.5² + 0.5² = 0.5 = μ₂ ✓. For the XRD library below, 4 of 501 numbers keep 91 % of the variance.

Materials example 1 · the periodic table from property vectors

Standardize first, or PCA just finds the biggest numbers

Data: 31 elements, Li to Sr (noble gases, C and As left out: no Pauling value, or they sublime). Four real properties: Pauling electronegativity χ, first ionization energy IE₁, covalent radius rcov, melting point Tm.

featurespread sjraw PC 1std. PC 1std. PC 2
χ (Pauling)0.780.000+0.57+0.10
IE₁ (eV)3.02−0.002+0.57+0.04
rcov (pm)37.4+0.008−0.52−0.34
Tm (K)727+1.000−0.27+0.93
explained99.7 %72.0 %22.2 %
\[ x_{ij}\;\to\;\frac{x_{ij}-\bar x_j}{s_j}\qquad\text{(every feature: mean 0, variance 1)} \]
Mendeleev's first periodic table from Osnovy Khimii
Mendeleev's first periodic table, Osnovy khimii (1869–71). Public domain

Physical meaning

Raw PCA ranks features by their units: 727 K beats 0.78. After standardizing, all features count equally, and PCA finds what moves together.

Materials example 1 · result

PCA rediscovers metals, non-metals and the d block

PC 1 (72 %): metallic → non-metallic character PC 2 (22 %): mostly melting point
s blockd blockp block

PC 1 = +χ, +IE₁, −rcov

Electronegative, hard to ionize and small: the metal → non-metal axis. Alkali metals far left, F far right.

PC 2 ≈ +Tm

Strong cohesion: the middle of the 3d row, B and Si at the top; alkali metals and molecular solids at the bottom.

What the model learned

No labels were used, yet the blocks separate. But the axes reflect these 31 elements: add heavy or f-block elements and the axes change. PCA reports patterns, not laws.

Derivation · k-means clustering

k-means: alternate two easy minimizations

1
Objective (within-cluster sum of squares) for centres m₁…mk and assignments c(i):\[ J = \sum_{i=1}^{n}\lVert\mathbf x_i - \mathbf m_{c(i)}\rVert^2 \]
Small J: every sample is close to its own centre.
2
Assignment step (centres fixed):\( c(i) = \arg\min_j \lVert\mathbf x_i - \mathbf m_j\rVert^2 \)
Each term of J depends on one sample only: send it to the nearest centre.
3
Update step (assignments fixed):\[ \frac{\partial}{\partial\mathbf m_j}\sum_{i\in j}\lVert\mathbf x_i-\mathbf m_j\rVert^2 = -2\sum_{i\in j}(\mathbf x_i-\mathbf m_j) = 0 \Rightarrow \mathbf m_j = \frac{1}{n_j}\sum_{i\in j}\mathbf x_i \]
The centre is the mean of its cluster: lecture 1's "best constant" again.
4
Repeat until nothing changes.
Neither step can raise J, and J ≥ 0, so it stops; but maybe in a local minimum.
Lloyd's algorithm
pick k → initial centres → assign ⇄ update → stop

What the model learned

  • Centres = prototypes: the average pattern of each group.
  • Assumes round, similar-sized clusters (plain distance), so standardize first.
  • Always returns k groups, even from structureless data.
  • Different starts → different answers: run many starts (k-means++), keep the lowest J.
Worked problem 2 · by hand

One iteration of k-means, k = 2, with a poor start

point(x₁, x₂)d² to m₁ = (1, 1)d² to m₂ = (2, 1)cluster
P1(1, 1)011
P2(2, 1)102
P3(1, 2)121
P4(4, 4)18132
P5(5, 4)25182
P6(4, 6)34292
1
Assign: J = 0 + 0 + 1 + 13 + 18 + 29 = 61.
Each point goes to the nearer centre (smaller d²).
2
Update: m₁ = mean(P1, P3) = (1, 1.5); m₂ = mean(P2, P4, P5, P6) = (3.75, 3.75); J = 18.
3
Iteration 2: P2 is now nearer m₁ (1.25 vs 10.6) and switches. New centres (1.33, 1.33), (4.33, 4.67); J = 4.67. Iteration 3 changes nothing: converged.

Check

J fell 61 → 18 → 8.63 → 4.67 and never rose, as derived. The final groups are the two visible clumps.

Materials example 2 · phase mapping of a combinatorial library (simulated)

231 XRD patterns across a ternary A–B–C wafer

αβγδ (ternary compound)two-phase band
diffraction angle 2θ (degrees)

Simulated, labelled: 4 phases with their own peaks; peaks shift with composition (Vegard-like); counting noise. The true phases are used only to grade the result, never by the algorithm.

Choosing k · elbow and silhouette

PCA to 4 scores, then k-means for k = 2 … 8

number of clusters k J (within-cluster) mean silhouette
\[ s_i = \frac{b_i - a_i}{\max(a_i,\,b_i)} \]
ai: mean distance to its own cluster; bi: to the nearest other cluster. s near 1: well placed; near 0: on a border.

Try it (outside the video)

k 4
J — · silhouette —
Materials example 2 · result and baseline

Clusters recover the phase map; composition alone does not

method (no phase labels used)samples in the right phase
baseline: phase = dominant element58 %
PCA (4 scores) + k-means, k = 4100 %

Why the silhouette preferred k = 5

At k = 5 the δ field splits in two. Both halves have the same peaks, only shifted (the Vegard-like shift). Physics says: one phase. Always inspect the cluster mean patterns.

What the model learned

Each centre is an average pattern, a "prototype" to index by hand. k-means groups by similarity, not by phase: a shifted phase can split, and a two-phase point is forced into one group. Methods that model patterns as mixtures (e.g. non-negative matrix factorization) go further.

Materials example 3 · clustering spectra (simulated)

Raman spectra of carbons: the whole curve beats one hand-made ratio

Raman shift (cm⁻¹)
method (60 spectra, 3 kinds)correct
baseline: ID/IG ratio, best two cut-offs83 %
PCA (3 scores) + k-means, k = 3100 %
PC 1 score (89 %) PC 2 score (9 %)

What the model learned

The ratio sees only two heights. PCA also sees the band widths, so defective and amorphous carbon, with overlapping ratios (0.81–1.60 and 0.69–1.25), separate cleanly.

Maps for the eye · t-SNE and UMAP

A map keeps neighbours, not distances

gap between phase centres (share of all six gaps)α–βα–δ
PCA scores (faithful distances)0.160.17
t-SNE, perplexity 10, seed 10.120.23
t-SNE, perplexity 10, seed 20.230.16
1

High-D: turn distances into neighbour probabilities; "perplexity" ≈ how many neighbours count.

2

2-D: place points so that their neighbour probabilities match (heavy-tailed kernel).

3

UMAP: same spirit, a nearest-neighbour graph laid out in 2-D; faster.

How to read a map

Trust: who is next to whom. Do not trust: gaps between clusters, cluster sizes, shapes. Change perplexity and seed; measure in the original or PCA space.

Lab 7 · this week in Colab

PCA, k-means and t-SNE on an XRD library

import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.manifold import TSNE
X = np.load("xrd_library.npy")   # 231 x 501
pca = PCA(n_components=4).fit(X)
Z = pca.transform(X)
print(pca.explained_variance_ratio_.cumsum())
for k in range(2, 9):
    km = KMeans(k, n_init=30, random_state=0).fit(Z)
    print(k, km.inertia_, silhouette_score(Z, km.labels_))
km = KMeans(4, n_init=30, random_state=0).fit(Z)
mean_patterns = pca.inverse_transform(km.cluster_centers_)
Y = TSNE(perplexity=30, random_state=0).fit_transform(Z)

Exercises

  • Redo worked problem 1 with np.linalg.eigh; check μ = 4.5, 0.5.
  • PCA of the 31 elements with and without StandardScaler; plot PC 1 vs PC 2 with symbols.
  • Phase map: choose k by elbow and silhouette, plot each cluster's mean pattern, merge clusters that are one phase.
  • t-SNE with perplexity 5, 30, 50 and two seeds: what changes, what stays?

Runs in Google Colab; no GPU needed. The simulated library and the element table are posted with this lecture.

Answers to the why questions

The four puzzles, solved

1 · A phase map without labels

PCA compresses each pattern to 4 scores (91 % of the variance); k-means groups similar patterns. On the simulated library every film lands with its main phase, versus 58 % for the composition rule. A human then indexes each cluster's mean pattern.

2 · "Melting point is PC 1"

No discovery: Tm just has the biggest numbers (spread 727 K vs 0.78 for χ). PCA maximizes variance, which depends on units. Standardized, PC 1 (72 %) is the metal → non-metal axis.

3 · Far apart on a t-SNE map?

Not necessarily. t-SNE keeps neighbours, not distances. All four phases are about equally far apart in PCA space, but the t-SNE α–β gap doubles just by changing the random seed.

4 · Choosing k

J always falls with k. Use the elbow and the silhouette as hints (0.81 at k = 5, 0.80 at k = 4), then check with physics: the two δ clusters had the same peaks, shifted, so k = 4.

Check your understanding · click a card to reveal

Concept check

Q1. Features: band gap in eV (spread 2) and lattice parameter in pm (spread 30). Without standardizing, what is PC 1?
Almost pure lattice parameter: its variance is 30²/2² = 225 times larger. Standardize first.
Q2. Covariance eigenvalues are 6, 3 and 1. What share do two components keep, and what is the mean reconstruction error?
(6 + 3)/10 = 90 %. The error is the dropped eigenvalue: 1.
Q3. 1-D points 0, 1, 5, 6; k = 2; start m₁ = 0, m₂ = 1. Where do the centres end?
Iteration 1: m₁ = 0, m₂ = 4 (J 41 → 14). Iteration 2: point 1 switches; m₁ = 0.5, m₂ = 5.5 (J 6 → 1).
Q4. On a t-SNE map, cluster A is twice as big as cluster B and far from C. What can you conclude?
Only that points inside each cluster are neighbours. Sizes and gaps are not meaningful; measure them in the original or PCA space.
Wrap-up

Summary and next lecture

1
PCA: the direction of maximum variance solves \(C\mathbf u = \mu\mathbf u\); μj/Σμ is its share; equivalently, minimum reconstruction error.
2
Standardize features in different units, or PCA just ranks units.
3
k-means: assign to the nearest centre, move each centre to its mean; J never rises; local minima → many starts.
4
Choose k with elbow + silhouette, then physics: inspect cluster mean patterns.
5
t-SNE and UMAP maps keep neighbours, not distances, sizes or gaps.

This week

Lab 7: PCA, k-means and t-SNE on the XRD library and the element table. Problem set 2 is due this week.

Week 8 · Midterm

Lectures 1–7: learning and baselines, linear models and regularization, descriptors, uncertainty and GPs, classification and trees, honest validation, unsupervised learning.

Week 9 · Neural networks

From the perceptron to multilayer networks: why nonlinearity is needed, and backpropagation derived from the chain rule, one step by hand.

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. 12 "Unsupervised Learning".
  • K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): chapters on dimensionality reduction and clustering.
  • C. M. Bishop, H. Bishop, Deep Learning: Foundations and Concepts, Springer (2024): chapters on discrete and continuous latent variables (k-means, PCA).
  • A. Géron, Hands-On Machine Learning, 3rd ed., O'Reilly (2022): dimensionality reduction; unsupervised learning techniques.
  • S. Sandfeld, Materials Data Science, Springer (2024): unsupervised learning for materials data.
  • L. van der Maaten, G. Hinton, "Visualizing data using t-SNE," J. Mach. Learn. Res. 9, 2579 (2008). L. McInnes, J. Healy, J. Melville, "UMAP," arXiv:1802.03426 (2018).
  • S. P. Lloyd, "Least squares quantization in PCM," IEEE Trans. Inf. Theory 28, 129 (1982). P. J. Rousseeuw, "Silhouettes," J. Comput. Appl. Math. 20, 53 (1987).
  • B. Cordero et al., "Covalent radii revisited," Dalton Trans. 2832 (2008) (radii used for the element PCA).

Image credits (Wikimedia Commons)

  • X-ray diffractometer: Sufangxi, CC BY-SA 4.0 — File page
  • Raman microscope (RamanScope III): Ijon, CC BY-SA 4.0 — File page
  • Mendeleev's first periodic table, Osnovy khimii (1869–1871): D. I. Mendeleev, public domain — File page

All schematics and plots were drawn for this course. The XRD library and the Raman spectra are simulated (see data/lecture07_*.js); the element properties are standard values (Pauling electronegativity, first ionization energy, covalent radius, melting point), rounded.