FAU Erlangen-Nürnberg
Institute of Micro- and Nanostructure Research
notebooks/week03_pca_eels.ipynb — build a synthetic EELS stack, compute PCA, denoise, choose k from the scree plot.


import numpy as np
# Simulate loading an EELS spectrum image
# Shape: (ny, nx, energy_channels) = (64, 64, 1024)
eels_map = np.random.rand(64, 64, 1024).astype(np.float32)
ny, nx, ne = eels_map.shape
print("Original shape:", eels_map.shape) # (64, 64, 1024)
# Reshape: stack all pixels into rows → data matrix
X = eels_map.reshape(ny * nx, ne)
print("Data matrix shape:", X.shape) # (4096, 1024) — N=4096 spectra, D=1024 channels
# After PCA: reshape score maps back to spatial image
# (assume K=3 components)
K = 3
# scores.shape = (4096, 3) → reshape to (64, 64, 3)
# score_maps = scores.reshape(ny, nx, K)
print(f"Score maps after reshape: ({ny}, {nx}, {K}) = {ny*nx*K} values total")X.shape before any analysis — a transposed matrix gives meaningless PCA.
U, s, Vt = np.linalg.svd(X, full_matrices=False) — then zero out s[k:].U, s, Vt = np.linalg.svd(X_centered, full_matrices=False).C = X_centered @ Vt[:k].T — shape \((N, k)\).X_hat = mean + C @ Vt[:k] — shape \((N, D)\).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)




np.linalg.cond(X) — if \(> 10^6\), you have a serious problem.notebooks/week03_pca_eels.ipynb — “PCA denoising of a synthetic EELS stack.”
_shared/exam_mustknow.md — Week 3 statements are now filled.
©Philipp Pelz - FAU Erlangen-Nürnberg - Data Science for Electron Microscopy