Data Science for Electron Microscopy
Week 3: Linear algebra, PCA & spectral unmixing

Prof. Dr. Philipp Pelz

FAU Erlangen-Nürnberg

Institute of Micro- and Nanostructure Research

FAU Logo IMN Logo CENEM Logo ERC Logo Eclipse Logo

Recap: where we left off

  • Week 2: EM data formation. Specimen → interaction → detector → digitisation → metadata. Every stage leaves a fingerprint on the numbers.
  • Noise model → likelihood → loss: Gaussian noise gives MSE, Poisson counts give the Poisson NLL, mixed noise calls for a variance-stabilising transform (Anscombe).
  • Every EM pixel is a count, so the variance depends on the signal. Low-dose data are noisy no matter what you do afterwards.
  • Gap: a spectrum image holds 10⁴–10⁵ spectra with hundreds of channels each. We need a compact representation that is also physically interpretable.
  • Today: the linear algebra behind that representation. First PCA, which finds the subspace. Then NMF / MCR, which turn the subspace into phases.

Today’s question

  • Why does PCA denoise an EELS spectrum image? Because the signal lives in a low-dimensional subspace, while the noise spreads across all directions.
  • Why are PCA components not phases, and what gives us phases? Non-negativity and mixing constraints: NMF, MCR-ALS, endmember unmixing.
  • Road map: geometry & projection · SVD & PCA · scree & denoising · EELS preprocessing & Poisson weighting · linear mixing, NMF & MCR-ALS · unmixing pitfalls · ill-conditioning & limits.
  • Self-study: notebooks/week03_pca_nmf_eels.ipynb. Build a 3-phase spectrum image, then compare PCA and NMF against the ground truth.

Learning outcomes

By the end of this week you can:

  1. Reshape a spectrum image into a data matrix \(\mathbf{X}\in\mathbb{R}^{N\times D}\) (rows = pixels) and back.
  2. Explain SVD geometrically and connect singular values to the variance per principal component.
  3. Choose the number of components \(K\) from a scree plot, and name the ways that choice can go wrong.
  4. Describe the EELS preprocessing chain: energy alignment → power-law background → normalisation → Poisson weighting.
  5. Formulate NMF and MCR-ALS as constrained factorisations, and explain multiplicative updates and alternating least squares.
  6. Diagnose rotational ambiguity, PCA truncation bias and rare-phase loss, using residual maps and restarts.

Vectors, dot products and projection

Projection of \(\mathbf{b}\) onto the direction of \(\mathbf{a}\); the residual (orange dashed) is orthogonal.
  • One EELS spectrum with \(D\) channels is a vector \(\mathbf{x}\in\mathbb{R}^D\), a point in \(D\)-dimensional space.
  • Dot product \(\mathbf{a}^T\mathbf{b}=\|\mathbf{a}\|\|\mathbf{b}\|\cos\theta\) measures alignment; \(=0\) ⟹ orthogonal.
  • Projection onto a unit vector \(\hat{\mathbf{a}}\): \(c=\hat{\mathbf{a}}^T\mathbf{b}\), \(\ \text{proj}_{\mathbf{a}}\mathbf{b}=c\,\hat{\mathbf{a}}\).
  • The residual \(\mathbf{b}-c\,\hat{\mathbf{a}}\) is ⊥ \(\mathbf{a}\). “How much lies along \(\mathbf{a}\)?” is what PCA asks in every direction.

The data matrix: EM spectra as points in high-D space

Data cloud with principal directions (arrows): PC1 = direction of maximum spread, PC2 = orthogonal residual.
  • Data matrix \(\mathbf{X}\in\mathbb{R}^{N\times D}\): one row per pixel spectrum, one column per energy channel (this week’s convention).
  • Each spectrum is a point in \(\mathbb{R}^{1024}\); the cloud occupies only a tiny corner of that space.
  • \(K\) distinct phases ⟹ the spectra lie (approximately) on a \(K\)-dimensional subspace. Two phases → a 2-D plane in \(\mathbb{R}^{1024}\).
  • PCA finds and extracts that subspace.

Reshaping EM data into a matrix: the practical step

ny, nx, ne = eels_map.shape              # (64, 64, 1024) spectrum image
X = eels_map.reshape(ny * nx, ne)        # (4096, 1024): rows = pixels, cols = channels
# ... PCA / NMF on X gives per-pixel scores of shape (4096, K) ...
score_maps = scores.reshape(ny, nx, K)   # back to K images
  • Data layout rule: observations (pixels, spectra) in rows; features (channels) in columns.
  • Always check X.shape before any analysis — a transposed matrix gives meaningless PCA.

Projection onto a subspace

  • Approximate a spectrum \(\mathbf{x}\) with \(K\) orthonormal basis vectors (\(\mathbf{v}_i^T\mathbf{v}_j=\delta_{ij}\)). The best approximation is the orthogonal projection: \[\hat{\mathbf{x}} = \sum_{k=1}^{K} (\mathbf{v}_k^T \mathbf{x})\, \mathbf{v}_k = \mathbf{V}_K \mathbf{V}_K^T \mathbf{x}.\]
  • Scores \(c_k = \mathbf{v}_k^T \mathbf{x}\): one dot product each, no matrix inversion (orthonormality makes it trivial).
  • Residual \(\mathbf{x} - \hat{\mathbf{x}}\) is ⊥ every \(\mathbf{v}_k\). If the basis captures the signal, the residual is noise.
  • PCA’s eigenspectra form such a basis, so the scores of different PCs are uncorrelated.

Least squares = projection (no calculus required)

  • Problem: find weights \(\mathbf{w}\) such that \(\mathbf{Xw} \approx \mathbf{y}\) (predict target \(\mathbf{y}\) from features \(\mathbf{X}\)).
  • Geometric view: \(\mathbf{Xw}\) can only reach the column space of \(\mathbf{X}\).
  • The best approximation is the orthogonal projection of \(\mathbf{y}\) onto that column space.
  • Orthogonality condition: the residual \(\mathbf{r} = \mathbf{y} - \mathbf{Xw}\) must be perpendicular to every column of \(\mathbf{X}\), i.e. \(\mathbf{X}^T \mathbf{r} = \mathbf{0}\).
  • Substituting: \(\mathbf{X}^T(\mathbf{y} - \mathbf{Xw}) = \mathbf{0}\) → Normal equations: \(\mathbf{X}^T\mathbf{X}\,\hat{\mathbf{w}} = \mathbf{X}^T \mathbf{y}\) Bishop, Christopher M., (2006).

SVD: the rotate–stretch–rotate decomposition

SVD applied to a unit circle: (1) rotate by \(\mathbf{V}^T\), (2) stretch by \(\mathbf{\Sigma}\), (3) rotate by \(\mathbf{U}\) — the result is an ellipse.
  • Any matrix: \(\mathbf{X} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^T\) = rotate, stretch, rotate.
  • \(\mathbf{V}\) (\(D\times D\)): columns are eigenspectra, directions in channel space.
  • \(\boldsymbol{\Sigma}\): singular values \(\sigma_1\ge\sigma_2\ge\ldots\ge0\), the importance of each direction.
  • \(\mathbf{U}\) (\(N\times N\)): how strongly each direction is expressed per pixel → score maps.
  • \(\mathbf{X} = \sum_k \sigma_k \, \mathbf{u}_k \mathbf{v}_k^T\): a sum of rank-1 “spectral images”.

SVD and low-rank approximation (Eckart–Young)

  • Truncated SVD: keep only the top \(k\) singular values; set the rest to zero.
  • Result: \(\hat{\mathbf{X}}_k = \mathbf{U}_k \boldsymbol{\Sigma}_k \mathbf{V}_k^T\), where subscript \(k\) means “first \(k\) columns.”
  • Optimality (Eckart–Young theorem): \(\hat{\mathbf{X}}_k\) is the best rank-\(k\) approximation of \(\mathbf{X}\) in the sense of minimising the Frobenius norm of the reconstruction error: \[\| \mathbf{X} - \hat{\mathbf{X}}_k \|_F = \sqrt{\sigma_{k+1}^2 + \sigma_{k+2}^2 + \cdots}.\]
  • Denoising: if signal lives in rank-\(k\) and noise spreads over all ranks, truncation removes noise.
  • In Python: U, s, Vt = np.linalg.svd(X, full_matrices=False) — then zero out s[k:].

PCA: directions of maximum variance

  • PCA finds orthonormal directions that maximise the variance of the projected data: PC1 maximises \(\text{Var}(\tilde{\mathbf{X}}\mathbf{v})\) s.t. \(\|\mathbf{v}\|=1\); PC2 ⊥ PC1, and so on.
  • PCA = SVD of the centered data: \(\tilde{\mathbf{X}} = \mathbf{X}-\bar{\mathbf{x}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T\).
  • Loadings (eigenspectra): rows of \(\mathbf{V}^T\). Scores: \(\mathbf{U}\boldsymbol{\Sigma} = \tilde{\mathbf{X}}\mathbf{V}\) → reshape to score maps.
  • Equivalently: the eigenvectors of the covariance \(\mathbf{S}=\tilde{\mathbf{X}}^T\tilde{\mathbf{X}}/(N-1)\), i.e. the axes of the data ellipsoid. Variance along PC \(k\): \(\lambda_k = \sigma_k^2/(N-1)\).

PCA in five lines of NumPy

import numpy as np

# ✅ CORRECT full pipeline — copy this version
mean_spectrum = X.mean(axis=0)                                 # (D,) mean of original data
X_centered    = X - mean_spectrum                              # center before SVD
U, s, Vt      = np.linalg.svd(X_centered, full_matrices=False) # core computation
K = 3                                                          # chosen from scree plot

# Scores (chemical maps): how strongly each PC is expressed per pixel
scores       = X_centered @ Vt[:K].T        # shape (N, K)

# Eigenspectra (spectral shapes): rows of Vt[:K], shape (K, D)
eigenspectra = Vt[:K]                       # already unit-norm and orthogonal

# Reconstruct (denoise): restore mean to get back to original scale
X_denoised   = scores @ eigenspectra + mean_spectrum  # shape (N, D)

The scree plot: how many components to keep?

Scree plot (left) and cumulative variance plot (right) for the synthetic EELS stack. The elbow at \(k=2\) separates signal components (large bars) from noise components (flat floor).
  • Plot the variance explained \(\lambda_k / \sum_k \lambda_k\) (or \(\sigma_k^2\)) for each component.
  • Signal components: steeply decreasing — each one captures a large portion of variance.
  • Noise components: flat floor — all roughly equal variance (noise is isotropic).

Choosing K: elbow, 95 % rule and parallel analysis

  • Elbow: keep the components before the curve reaches the flat noise floor.
  • 95 % cumulative variance: the smallest \(K\) with \(\sum_{k\le K}\lambda_k/\sum_k\lambda_k\ge0.95\), a reasonable start for denoising.
  • Parallel analysis (Horn): keep \(\lambda_k\) larger than those of random data of the same shape.
  • Always inspect the eigenspectrum and score map of the last kept and the first discarded PC: structure = signal, random wiggles = noise.
  • No universal \(K\): it depends on the question (compression, denoising, rare-phase discovery).

PCA denoising of EELS: reconstruction with k components

PCA reconstruction of EELS stack with k = 1, 2, 5, 10 components. Top: reconstructed spectral images; bottom: reconstructed spectra at position 24 vs noisy (blue) and clean (green dashed).
  • Setup: synthetic 64-pixel × 300-channel EELS line scan, Fe-L and Cr-L components, Poisson noise → true rank 2.
  • k = 1: Cr component missing → systematic error (bias).
  • k = 2: recovers both components, tracks the ground truth.
  • k = 5, 10: noise components added back.
  • Error vs \(k\) is U-shaped; its minimum sits at the scree elbow.

Why PCA denoising works: the subspace argument

  • Signal is low-rank: if the spectrum image has \(K\) true chemical components, the clean data lies on a \(K\)-dimensional subspace of \(\mathbb{R}^D\).
  • Noise is full-rank: Poisson noise adds variance in every direction equally — it spreads across all \(D\) dimensions.
  • After SVD: the top \(K\) singular vectors capture the signal subspace; the remaining \(D - K\) directions are dominated by noise.
  • Truncation: project onto the signal subspace (keep top \(K\)), discard the orthogonal complement (noise).
  • Caveat: this assumes isotropic (equal-variance) noise. Poisson noise is signal-dependent, so the floor is not flat — hence Poisson weighting (coming up).

Eigen-spectra and score maps

First three eigenspectra extracted from the synthetic EELS stack. PC1 captures the dominant Fe-L variation; PC2 captures the Cr-L contrast; PC3 looks like noise.
  • PC1: Fe-L variation. PC2: Cr-L vs Fe-L contrast (signed). PC3+: no structure, noise.
  • Scores \(c_{ik}=\mathbf{v}_k^T(\mathbf{x}_i-\bar{\mathbf{x}})\) reshaped to \((n_y,n_x)\) → score maps (eigen-micrographs).
  • Eigenspectra and score maps can be negative: basis vectors, not physical spectra or concentrations.
  • Reconstruction: \(\hat{\mathbf{x}}_i = \bar{\mathbf{x}} + c_{i1}\mathbf{v}_1 + c_{i2}\mathbf{v}_2\).

Before any decomposition: the EELS preprocessing chain

  1. Energy alignment: register every spectrum to the zero-loss peak (or a known edge onset). Drift of a fraction of an eV is enough to create fake components.
  2. Spike / X-ray removal: cosmic-ray and hot-pixel spikes are rank-one outliers, and PCA will happily fit them.
  3. Background subtraction: a power law \(A E^{-r}\) fitted in a pre-edge window, then extrapolated under the edge Egerton, R. F., (2011).
  4. Normalisation: divide by the zero-loss or total intensity (thickness / beam-current changes). Note that this changes the noise model.
  5. Poisson weighting: scale the counts so that every entry has roughly unit noise variance.
  6. Only now: PCA (denoise, choose \(K\)) → NMF / MCR (interpret).

Power-law background and energy alignment

Synthetic Ti-L\(_{2,3}\) + O-K core-loss spectrum. (1) Power law fitted in a pre-edge window (log-log linear regression). (2) After subtraction the edges emerge. (3) A stack whose energy axis drifts by ±0.8 eV: its first principal component is simply the derivative \(dI/dE\) of the edge (img/make_figures.py).

  • Background: \(\log I = \log A - r \log E\) is a linear least-squares fit (projection again!). Typically \(r\approx 2\)–\(6\). The fit window must be edge-free and close to the onset.
  • Alignment: a rigid shift \(\delta\) adds \(\delta\cdot dI/dE\) to the spectrum (Taylor expansion). A derivative-shaped loading is therefore the fingerprint of misalignment, not of chemistry.

Poisson weighting before PCA

Thickness-varying background plus a weak Fe-L edge under Poisson noise. Left: unweighted PCA, where PC2 barely rises above a sloped noise floor. Right: after weighting, the noise floor is flat and the weak edge component stands out clearly (img/make_figures.py).
  • Poisson counts: \(\operatorname{Var}[x_{ij}] = \mathbb{E}[x_{ij}]\). Bright channels and thick pixels dominate the variance.
  • PCA = least squares, so it implicitly assumes equal-variance Gaussian noise (Week 2!).
  • Weighting Keenan, Michael R. et al., (2004), doi:10.1002/sia.1657: \(\tilde{\mathbf{X}} = \mathbf{G}^{-1/2}\,\mathbf{X}\,\mathbf{H}^{-1/2}\), with \(\mathbf{G}\) = diagonal of pixel totals and \(\mathbf{H}\) = diagonal of the mean spectrum.
  • After weighting, the noise is ≈ isotropic, the noise floor is flat, and the scree elbow becomes readable.
  • Un-weight the reconstruction afterwards: \(\hat{\mathbf{X}} = \mathbf{G}^{1/2}\hat{\tilde{\mathbf{X}}}\mathbf{H}^{1/2}\).

The linear mixing model

Unmixing factorises the unfolded datacube into non-negative abundances and non-negative endmember spectra (figure from ML-PC Unit 5).
  • Each pixel is a mixture of pure phases (endmembers): \[\mathbf{x}_i = \sum_{k=1}^{K} a_{ik}\,\mathbf{m}_k + \boldsymbol{\varepsilon}_i,\quad a_{ik}\ge 0,\ \textstyle\sum_k a_{ik}=1\]
  • Matrix form: \(\mathbf{X} \approx \mathbf{A}\mathbf{M}\) with \(\mathbf{A}\in\mathbb{R}_{\ge0}^{N\times K}\) (abundance maps) and \(\mathbf{M}\in\mathbb{R}_{\ge0}^{K\times D}\) (endmember spectra).
  • Same shape as PCA (\(\mathbf{X}\approx\mathbf{T}\mathbf{V}^T\)), but with different constraints: non-negativity (+ sum-to-one) instead of orthogonality.
  • Physically justified when the signal is additive: thin specimens, no strong multiple scattering or absorption.

Known endmembers: constrained least squares & the simplex

Linear mixing places every pixel inside a simplex whose vertices are the pure endmember spectra. Unmixing means finding the vertices plus each pixel’s barycentric coordinates. From Dobigeon, Nicolas et al. (2012), doi:10.1016/j.ultramic.2012.05.006.
  • Known \(\mathbf{M}\) (reference spectra): solve per pixel \(\min_{\mathbf{a}_i}\|\mathbf{x}_i-\mathbf{M}^T\mathbf{a}_i\|^2\). This is projection onto the span of the references (slide “Least squares = projection”).
  • Plain least squares can give negative fractions. Hence NNLS (\(\mathbf{a}\ge0\)) and FCLS (fully constrained: \(\ge0\), sum to one).
  • Geometry: with sum-to-one, the pixels lie in a \((K-1)\)-dimensional simplex. The vertices are the pure phases, and mixed pixels sit inside.
  • Unknown \(\mathbf{M}\), but pure pixels exist: VCA / N-FINDR search for the vertices directly.
  • Unknown \(\mathbf{M}\), no pure pixels: we need a factorisation → NMF / MCR-ALS.

Non-negative matrix factorisation (NMF)

  • Problem: given \(\mathbf{X}\ge0\), find \(\mathbf{W}\in\mathbb{R}_{\ge0}^{N\times K}\) and \(\mathbf{H}\in\mathbb{R}_{\ge0}^{K\times D}\) with \[\min_{\mathbf{W}\ge0,\,\mathbf{H}\ge0}\ \|\mathbf{X}-\mathbf{W}\mathbf{H}\|_F^2 \qquad\text{or}\qquad \min\ D_\text{KL}(\mathbf{X}\,\|\,\mathbf{W}\mathbf{H})\]
  • No subtraction allowed → components can only add up. The result is a parts-based representation: peaks, edges, phases Lee, Daniel D. et al., (1999), doi:10.1038/44565.
  • Frobenius loss = Gaussian likelihood; KL divergence = Poisson likelihood (up to constants). For counts, the KL loss is the principled choice (Week 2 again).
  • Non-convex in \((\mathbf{W},\mathbf{H})\) jointly, but convex in each factor separately → alternating optimisation. The result depends on initialisation.
  • No orthogonality and no variance ordering: components are not nested (NMF with \(K=3\) ≠ NMF with \(K=2\) plus one component).

NMF by multiplicative updates

  • Lee–Seung updates (Frobenius loss) Lee, Daniel D. et al., (2001), element-wise: \[\mathbf{H} \leftarrow \mathbf{H}\odot\frac{\mathbf{W}^T\mathbf{X}}{\mathbf{W}^T\mathbf{W}\mathbf{H}},\qquad \mathbf{W} \leftarrow \mathbf{W}\odot\frac{\mathbf{X}\mathbf{H}^T}{\mathbf{W}\mathbf{H}\mathbf{H}^T}\]
  • Gradient descent with a per-element step size: all factors ≥ 0, so non-negativity is preserved automatically.
  • The loss never increases, but convergence is slow and ends in a local minimum.
  • KL version = Poisson-ML update. In practice: sklearn.decomposition.NMF(beta_loss="kullback-leibler", solver="mu"); you write the updates yourself in notebook Part D.

PCA vs NMF on a synthetic 3-phase spectrum image

Top: ground-truth endmembers (TiO\(_2\)-like, FeO-like, Ni) and abundance maps. Middle: PCA with \(K=3\). The components are signed difference spectra, the maps have positive and negative lobes, and PC3 is pure noise (sum-to-one removes one dimension after centering). Bottom: NMF with \(K=3\) recovers phase-like spectra and non-negative maps, with small artefacts at the edge onsets (img/make_figures.py, same data as the notebook).

MCR-ALS: multivariate curve resolution

  • Model: \(\mathbf{X} = \mathbf{C}\mathbf{S}^T + \mathbf{E}\), with \(\mathbf{C}\) = concentrations (maps) and \(\mathbf{S}\) = pure spectra Juan, Anna de et al., (2014).
  • Alternating least squares:
    1. Initialise \(\mathbf{S}\) (purest pixels, PCA + varimax, or reference spectra).
    2. \(\mathbf{C} \leftarrow \arg\min_{\mathbf{C}}\|\mathbf{X}-\mathbf{C}\mathbf{S}^T\|^2\) subject to the constraints.
    3. \(\mathbf{S} \leftarrow \arg\min_{\mathbf{S}}\|\mathbf{X}-\mathbf{C}\mathbf{S}^T\|^2\) subject to the constraints.
    4. Repeat until the relative change in the residual is < \(10^{-6}\).
  • Each half-step is an ordinary (constrained) least-squares problem, i.e. a projection.
  • NMF = MCR with non-negativity only. MCR adds closure, unimodality, known spectra, selectivity / local rank.

MCR of a STEM-EDS spectrum image of a microelectronics interface: pure-component spectra (O, Si, Ti, Pt/Ga, Al) and their abundance maps, extracted from the raw datacube. From Kotula, Paul G. et al. (2006), doi:10.1017/S1431927606060636.

Pitfall 1: rotational ambiguity of NMF / MCR

Pixels of the 3-phase SI projected onto PC1–PC2 fill a triangle (simplex). An enlarged triangle (dashed) with non-negative vertex spectra reproduces every pixel exactly, with different spectra and different abundances (img/make_figures.py).
  • For any invertible \(\mathbf{T}\): \(\mathbf{X} = \mathbf{C}\mathbf{S}^T = (\mathbf{C}\mathbf{T})(\mathbf{T}^{-1}\mathbf{S}^T)\), with identical fit.
  • Non-negativity only rules out some \(\mathbf{T}\). It leaves a feasible band of solutions.
  • Geometrically: any simplex that encloses the data and has non-negative vertices is a valid answer.
  • Symptoms: endmembers change between restarts, or converge consistently to spectra with dips / copies of other phases. Consistency ≠ correctness.
  • Remedies: closure, known spectra, pure pixels / selectivity, physics-guided endmembers. Always report your constraints.
  • PCA is unique (up to sign) only because it imposes orthogonality.

Pitfall 2: PCA truncation bias and the rare phase

A rare phase occupying 13 pixels (0.3 %) is invisible in the scree plot (elbow at \(k=2\)). The Poisson-normalised residual at \(K=2\) shows it as a spatially coherent hot spot, and only at \(K\approx8\) is it absorbed, together with six noise components (img/make_figures.py).

Choosing the decomposition: a decision table

Question Method Constraint Unique? Watch out for
How many things vary? Denoise PCA / SVD (weighted) orthogonal, variance-ordered yes (± sign) truncation bias, rare phases, needs weighting
Which phases, known references NNLS / FCLS \(\mathbf{a}\ge0\), \(\sum a=1\) yes missing endmember → biased fractions
Which phases, unknown spectra NMF (Frobenius / KL) \(\mathbf{W},\mathbf{H}\ge0\) no rotational ambiguity, init, choose \(K\) from PCA
+ physical prior knowledge MCR-ALS / physics-guided NMF + closure, unimodality, known spectra ≈ with enough constraints constraints must be true
Discrete phases, no mixing K-means / GMM (Week 9) hard / soft labels no (init) mixed pixels at boundaries
Curved manifolds, shifting peaks Autoencoders (Week 9) learned non-linear no interpretability, validation

Ill-conditioning: when correlated features cause trouble

Loss landscape: well-conditioned problem (circular contours, left) vs ill-conditioned problem (narrow valley, right). Small noise → large parameter swing in the ill-conditioned case.
  • Condition number \(\kappa = \sigma_\text{max}/\sigma_\text{min}\) — ratio of largest to smallest singular value.
  • Well-conditioned: \(\kappa \approx 1\) (circular contours). Ill-conditioned: \(\kappa \gg 1\) (narrow valley).
  • Cause: highly correlated features → data matrix nearly singular → small \(\sigma_\text{min}\) → large \(\kappa\).
  • Effect: a tiny change in the data produces huge, unstable swings in the estimated parameters Murphy, Kevin P., (2012).
  • Cures: standardise features, project onto the top PCs, or Ridge (Week 4).

Limits of linear methods

  • Linearity: PCA, NMF and MCR all assume \(\mathbf{X}\approx\) (maps) × (spectra). Peak shifts (strain, valence), peak-shape changes (ELNES), plural scattering and EDS absorption bend the data cloud off the flat subspace / simplex.
  • Noise, identifiability, rare features: weight or use KL; add constraints; inspect residual maps (see the pitfalls).
  • These limits motivate Week 9: autoencoders learn non-linear low-dimensional representations, and constrained autoencoders learn NMF-style unmixing.

Summary

  • Data matrix: spectrum image \((n_y,n_x,D)\) → \(\mathbf{X}\in\mathbb{R}^{N\times D}\), rows = pixels. Every method today factorises \(\mathbf{X}\approx\) maps × spectra.
  • SVD / PCA: rotate–stretch–rotate; singular values² ∝ variance; truncation = projection onto the signal subspace (Eckart–Young). Unique, but components are signed.
  • Scree plot & denoising: signal = steep head, noise = flat floor. Too few components → bias, too many → noise.
  • Preprocessing: align → remove spikes → power-law background → normalise → Poisson-weight → decompose.
  • NMF / MCR-ALS: non-negativity (+ closure, …) gives phase-like spectra and maps. Multiplicative updates / alternating LS. KL loss = Poisson likelihood.
  • Pitfalls: rotational ambiguity (report constraints, check restarts), truncation bias (inspect residual maps), ill-conditioning (κ = σ_max/σ_min).

Must-know takeaways

  1. PCA = SVD of the centered data matrix; \(\sigma_k^2/(N-1)\) is the variance along PC \(k\); truncating at \(K\) is the best rank-\(K\) approximation (Eckart–Young).
  2. PCA denoises because the signal is low-rank and the noise is full-rank; choose \(K\) where the scree plot meets the noise floor.
  3. PCA is least squares, i.e. it assumes equal-variance Gaussian noise. Poisson-weight counts before PCA.
  4. EELS preprocessing order: align → background (power law) → normalise → weight → decompose. A derivative-shaped loading signals misalignment.
  5. NMF: \(\mathbf{X}\approx\mathbf{WH}\), \(\mathbf{W},\mathbf{H}\ge0\) gives a parts-based, physically plausible basis; KL-NMF = Poisson maximum likelihood.
  6. NMF / MCR are not unique: \(\mathbf{CS}^T = (\mathbf{CT})(\mathbf{T}^{-1}\mathbf{S}^T)\). Constraints (closure, known spectra, selectivity) reduce the ambiguity.
  7. Truncation removes low-variance, not unimportant, signal. Always inspect residual maps.

Looking ahead: Week 4

  • Topic: “Regression, optimisation & honest validation”.
  • Linear regression as projection, building directly on today’s least-squares geometry.
  • Gradient descent, SGD and Adam: loss landscapes and why ill-conditioning (today’s \(\kappa\)) makes optimisation slow.
  • Ridge and Lasso: systematic cures for ill-conditioning, and their geometry.
  • Honest validation: train/val/test, k-fold, GroupKFold by specimen. Also why every preprocessing step (scaling, PCA, feature selection) must be fitted inside the training fold.

Self-study this week

  • Notebook: notebooks/week03_pca_nmf_eels.ipynb, “PCA vs NMF on a synthetic spectrum image”.
    • Part A: PCA denoising of an EELS line scan (SVD, scree plot, U-shaped error curve).
    • Part B: a 3-phase 2-D spectrum image with Poisson noise and a known ground truth.
    • Part C: PCA vs NMF: match components to the ground truth, quantify spectral correlation and abundance error.
    • Part D: write multiplicative updates yourself; break NMF by removing pure pixels (rotational ambiguity); optional MCR-ALS with closure.
  • Goal: be able to explain why PCA components are not phases and when NMF can be trusted.

Open in Colab

CPU only, < 5 min end-to-end. Uses NumPy, SciPy, matplotlib and scikit-learn.

Continue

Backup slides

Material for questions and self-study; not part of the 90-minute lecture path.

Weighting and truncation in practice

STEM-XEDS element maps: raw → filtered → PCA unweighted → PCA weighted → PCA filtered & weighted. Weighting plus the right truncation separates a clean map from a destroyed one. From Potapov, Pavel et al. (2019), doi:10.1186/s40679-019-0066-0.
  • EDS counts are even sparser than EELS counts (often < 1 count per channel per pixel). Without weighting, PCA mainly models the bremsstrahlung.
  • Potapov & Lubk derive the optimal truncation rank from the noise statistics. It beats eyeballing the scree elbow Potapov, Pavel et al., (2019), doi:10.1186/s40679-019-0066-0.
  • Recipe: weight → PCA → choose \(K\) where the eigenvalues leave the noise floor (flat after weighting) → reconstruct → un-weight.
  • Record weighting, \(K\) and the software version. Otherwise the map is not reproducible (Week 2 FAIR).

Case study: NMF-aided phase unmixing of STEM-EDXS

  • Sample: lower-mantle assemblage from a diamond-anvil cell: bridgmanite, ferropericlase, Ca-perovskite, doped with trace Nd/Sm/U Chen, Hui et al., (2024), doi:10.1016/j.ultramic.2024.113981.
  • Problem: the phases share X-ray lines and intermix below the pixel scale. The per-pixel EDXS is far too noisy for trace elements.
  • Pipeline: NMF (3 components) → phase spectra + abundance maps → constrained least-squares refinement → quantification.
  • Result: trace Sm detected in ferropericlase down to tens of ppm.
  • Next step: physics-guided NMF, where endmembers are built from X-ray emission theory and fitted with a Poisson loss Teurtrie, Adrien et al., (2024).

Recovered phase spectra of bridgmanite, ferropericlase and Ca-perovskite after NMF-aided unmixing (a–c), and the corresponding abundance maps (d–f). From Chen, Hui et al. (2024), doi:10.1016/j.ultramic.2024.113981.

The covariance matrix: where geometry meets statistics

  • Covariance matrix of centered data: \(\mathbf{S} = \frac{1}{N-1}\tilde{\mathbf{X}}^T\tilde{\mathbf{X}} \in \mathbb{R}^{D \times D}\).
  • Entry \(S_{ij}\) = covariance between energy channels \(i\) and \(j\); \(S_{ii}\) = variance of channel \(i\).
  • Geometry: the level set \(\mathbf{x}^T\mathbf{S}^{-1}\mathbf{x} = 1\) is an ellipsoid whose axes are the eigenvectors of \(\mathbf{S}\) with lengths \(\propto \sqrt{\lambda_k}\) (eigenvalues).
  • PCA = align the coordinate axes with the ellipsoid axes: rotate to the eigenbasis of \(\mathbf{S}\), where features are uncorrelated.
  • In EM: off-diagonal entries of \(\mathbf{S}\) are large when two energy channels always increase or decrease together (e.g. Fe-L23 channels are correlated because they all belong to the same edge).

Matrices as geometric transformations

A \(2\times2\) matrix applied to the unit square: rotates, stretches, and shears — the unit square (blue) becomes a parallelogram (orange).
  • A matrix \(\mathbf{A}\) maps every vector \(\mathbf{x}\) to a new vector \(\mathbf{y} = \mathbf{Ax}\).
  • Geometrically: \(\mathbf{A}\) rotates, stretches, and (for non-symmetric \(\mathbf{A}\)) shears space.
  • The data matrix \(\mathbf{X} \in \mathbb{R}^{N \times D}\): \(N\) spectra (rows), each with \(D\) energy channels (columns).
  • One row = one spectrum = one point in \(\mathbb{R}^D\).
  • Convention for this week: observations in rows, features in columns.

Why correlated features cause ill-conditioning in EM

  • Scenario: two EDS channels (Fe-K\(\alpha\) at 6.4 keV and Ni-K\(\alpha\) at 7.5 keV) both increase with sample thickness in an FeNi alloy.
  • Forming a regression matrix from both channels → two nearly parallel column vectors → near-singular \(\mathbf{X}^T\mathbf{X}\) → high \(\kappa\).
  • PCA as a cure: PCA rotates to the principal directions. In the new basis, the directions are uncorrelated by construction (orthogonal). The PCA-transformed data matrix has no correlated columns.
  • Practical rule: if your condition number is \(> 10^3\) and you are fitting a linear model, standardise your features (subtract mean, divide by std) and consider PCA pre-processing or Ridge regularisation.
  • Fitting with highly correlated features gives wildly uncertain coefficients even when the prediction accuracy looks fine.

Ill-conditioning: a quick diagnostic

  • Check condition number: np.linalg.cond(X) — if \(> 10^6\), you have a serious problem.
  • Variance–inflation factor (VIF): for each feature, regress it on all others. High \(R^2\) → high VIF → high collinearity.
  • Standardise first: features on vastly different scales (counts vs kV vs nm) create artificial ill-conditioning. Always subtract the mean and divide by the standard deviation before linear modelling.
  • PCA as pre-processing: project features onto the first \(K\) principal components (choose \(K\) to drop near-zero singular values). The resulting \(K\) features are guaranteed to be uncorrelated.
  • Ridge regularisation (Week 4): adds \(\lambda\mathbf{I}\) to \(\mathbf{X}^T\mathbf{X}\), lifting all eigenvalues above \(\lambda\) — quick fix when you want to keep all features.

References

Pattern recognition and machine learning, Christopher M. Bishop.
EELS elemental mapping with unconventional methods i. Theoretical basis: Image analysis with multivariate statistics and entropy concepts, Ultramicroscopy, Patrick Trebbia & Nicolas Bonnet.
Mapping chemical and bonding information using multivariate analysis of electron energy-loss spectrum images, Ultramicroscopy, M. Bosman, M. Watanabe, D. T. L. Alexander, & V. J. Keast https://doi.org/10.1016/j.ultramic.2006.04.016.
Electron energy-loss spectroscopy in the electron microscope, R. F. Egerton.
Data processing for atomic resolution electron energy loss spectroscopy, Microscopy and Microanalysis, Paul Cueva, Robert Hovden, Julia A. Mundy, Huolin L. Xin, & David A. Muller https://doi.org/10.1017/S1431927612000244.
Accounting for Poisson noise in the multivariate analysis of ToF-SIMS spectrum images, Surface and Interface Analysis, Michael R. Keenan & Paul G. Kotula https://doi.org/10.1002/sia.1657.
Spectral mixture analysis of EELS spectrum-images, Ultramicroscopy, Nicolas Dobigeon & Nathalie Brun https://doi.org/10.1016/j.ultramic.2012.05.006.
Learning the parts of objects by non-negative matrix factorization, Nature, Daniel D. Lee & H. Sebastian Seung https://doi.org/10.1038/44565.
Algorithms for non-negative matrix factorization, Advances in Neural Information Processing Systems, Daniel D. Lee & H. Sebastian Seung.
Multivariate curve resolution (MCR). Solving the mixture analysis problem, Analytical Methods, Anna de Juan, Joaquim Jaumot, & Romà Tauler.
Application of multivariate statistical analysis to STEM x-ray spectral images: Interfacial analysis in microelectronics, Microscopy and Microanalysis, Paul G. Kotula & Michael R. Keenan https://doi.org/10.1017/S1431927606060636.
Statistical consequences of applying a PCA noise filter on EELS spectrum images, Ultramicroscopy, Stijn Lichtert & Jo Verbeeck https://doi.org/10.1016/j.ultramic.2012.10.001.
Machine learning: A probabilistic perspective, Kevin P. Murphy.
Optimal principal component analysis of STEM XEDS spectrum images, Advanced Structural and Chemical Imaging, Pavel Potapov & Axel Lubk https://doi.org/10.1186/s40679-019-0066-0.
Non-negative matrix factorization-aided phase unmixing and trace element quantification of STEM-EDXS data, Ultramicroscopy, Hui Chen, Farhang Nabiei, James Badro, Duncan T. L. Alexander, & Cécile Hébert https://doi.org/10.1016/j.ultramic.2024.113981.
From STEM-EDXS data to phase separation and quantification using physics-guided NMF, arXiv preprint arXiv:2404.17496, Adrien Teurtrie, Nathanaël Perraudin, Thomas Holvoet, Hui Chen, Duncan T. L. Alexander, Guillaume Obozinski, & Cécile Hébert.