Finding structure in materials data without labels: principal components, clusters and maps.
Undergraduate course · 16 weeks
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)
data
X and y
X only
goal
predict y
compress, group, visualize
check
test error
no 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.
X-ray diffractometer. Sufangxi, CC BY-SA 4.0Benchtop 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.
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.
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.
feature
spread sj
raw PC 1
std. PC 1
std. PC 2
χ (Pauling)
0.78
0.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
explained
99.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, 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
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 \]
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
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
\[ 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 element
58 %
PCA (4 scores) + k-means, k = 4
100 %
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
method (60 spectra, 3 kinds)
correct
baseline: ID/IG ratio, best two cut-offs
83 %
PCA (3 scores) + k-means, k = 3
100 %
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.16
0.17
t-SNE, perplexity 10, seed 1
0.12
0.23
t-SNE, perplexity 10, seed 2
0.23
0.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 TSNEX = 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?
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).
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
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.