🖥️ Lecture slides: Session 13 (Wed Oct 28), first half
1. Learning outcomes¶
By the end of this notebook you can:
state the dimension of one sample and the size of a dataset (number of samples , volume in bytes) for a table, a set of waveforms and a gridded field, and say why and the intrinsic dimension matter for learning;
explain what a principal component (an empirical orthogonal function, EOF, in climate science) is: an orthogonal direction of maximum variance, computed from the covariance of mean-removed data with a singular value decomposition (SVD);
read a variance-explained curve and state how many components a dataset needs (its intrinsic dimension, criterion B6 of the AI-ready rubric in 2.13);
interpret the first modes of a real geophysical field physically (spatial pattern and time series), knowing that modes are statistical and not guaranteed to be physical;
use a nonlinear embedding (t-SNE) for visualization only, knowing that it preserves neither distances nor density.
To run it. From the repository root, pixi run jupyter lab. Run the setup cell below once. Section 5 reads 76 years of sea surface temperature from NOAA through OPeNDAP (about 6 MB, a few seconds); without network the notebook says so and uses a synthetic field instead. Each Your turn cell is followed by a check that prints correct, a hint, or not answered yet. If your answer is not correct yet, the check puts the reference result in place so that the rest of the notebook runs; your own result is kept with the suffix _yours. Sections 1 to 6 fit in 25 minutes; section 7 is optional.
Source
# Setup: imports, data access, plotting helpers and the checks for the Your-turn cells. You do not need to read this cell.
import urllib.request
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from scipy import signal
from sklearn.decomposition import PCA, FastICA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
import mlgeo_synth
plt.rcParams.update({"figure.dpi": 100, "axes.grid": True, "grid.alpha": 0.3, "axes.spines.top": False,
"axes.spines.right": False, "font.size": 10})
LITH_COLORS = {"basalt": "C3", "andesite": "C2", "granite": "C0"}
ERSST_URL = "https://psl.noaa.gov/thredds/dodsC/Datasets/noaa.ersst.v5/sst.mnmean.nc"
NINO_URL = "https://psl.noaa.gov/data/correlation/nina34.anom.data"
SYNTH = {} # filled only if the synthetic fallback is used
def toy_cloud(n=10000, seed=42):
"""2D Gaussian cloud: center (2, 1), standard deviations 2 and 0.5 along its axes, rotated by 60 degrees."""
rng = np.random.default_rng(seed)
theta = np.pi / 3
R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
return R @ np.diag([2.0, 0.5]) @ rng.standard_normal((2, n)) + np.array([[2.0], [1.0]])
def load_ersst():
"""ERSST v5 monthly SST, tropical Pacific 20S-20N, 120E-280E, 1950-2025; synthetic field if NOAA is unreachable."""
try:
with xr.open_dataset(ERSST_URL) as ds:
sst = ds["sst"].sel(lat=slice(20, -20), lon=slice(120, 280), time=slice("1950-01", "2025-12")).load()
print("ERSST v5 (Huang et al., 2017) read through OPeNDAP from NOAA PSL:", dict(sst.sizes))
return sst, "ERSST v5"
except Exception as err:
print(f"FALLBACK: NOAA PSL could not be reached ({type(err).__name__}: {str(err)[:80]}).\n"
"Using the synthetic global temperature field of mlgeo_synth.climate_field (360 months, 1991-2020).\n"
"The maps and numbers below are NOT the tropical Pacific; the text describes the real data.")
field, truth = mlgeo_synth.climate_field(n_lat=40, n_lon=80, n_months=360, seed=42)
SYNTH.update(truth)
time = pd.date_range("1991-01-01", periods=360, freq="MS")
sst = xr.DataArray(field.astype("float32"), dims=("time", "lat", "lon"), name="sst",
coords={"time": time, "lat": truth["lat"], "lon": truth["lon"]})
return sst, "synthetic"
def load_nino34(anom):
"""Nino 3.4 index from NOAA PSL as a monthly Series; prints the basis stated in the file."""
if SYNTH:
print("FALLBACK: synthetic field, so the comparison series is the amplitude of the planted zonal mode.")
return (anom * SYNTH["zonal_pattern"]).mean(("lat", "lon")).to_series()
try:
text = urllib.request.urlopen(NINO_URL, timeout=30).read().decode()
except Exception as err:
print(f"Nino 3.4 file not reachable ({type(err).__name__}); using the 5S-5N, 170W-120W average of the "
"ERSST anomalies instead (same data, so not an independent check).")
box = anom.sel(lat=slice(5, -5), lon=slice(190, 240))
return box.weighted(np.cos(np.deg2rad(box.lat))).mean(("lat", "lon")).to_series()
values, notes = {}, []
for line in text.splitlines()[1:]:
parts = line.split()
if len(parts) == 13 and parts[0].isdigit():
for m, v in enumerate(parts[1:], start=1):
values[pd.Timestamp(int(parts[0]), m, 1)] = float(v)
elif line.strip() and line.strip() not in notes and not line.strip().startswith("-99"):
notes.append(line.strip())
print("Nino 3.4 file, as stated in its last lines:", " | ".join(notes))
return pd.Series(values).replace(-99.99, np.nan)
def orient(pcs, VT, X):
"""Fix the arbitrary signs: EOF1 positive in the Nino 3.4 box, the other PCs increasing with time."""
box = ((abs(X["lat"]) <= 5) & (X["lon"] >= 190) & (X["lon"] <= 240)).values
t = np.arange(len(pcs))
for k in range(pcs.shape[1]):
s = np.sign(VT[0, box].mean()) if k == 0 and box.any() else np.sign(np.polyfit(t, pcs.iloc[:, k], 1)[0])
pcs.iloc[:, k] *= s
return pcs
def regress_map(anom, pc):
"""Anomaly map regressed on a PC scaled to unit variance: degrees C per standard deviation of the PC."""
pc_da = xr.DataArray(((pc - pc.mean()) / pc.std()).to_numpy(), dims="time", coords={"time": anom["time"]})
return xr.cov(anom, pc_da, dim="time")
def plot_toy(X, evals, evecs, scores):
fig, ax = plt.subplots(1, 2, figsize=(10, 4.5))
ax[0].plot(X[0], X[1], ".", color="k", alpha=0.1)
c = X.mean(axis=1)
for k, col in enumerate(["C0", "C1"]):
ax[0].plot([c[0], c[0] + 2 * np.sqrt(evals[k]) * evecs[k, 0]], [c[1], c[1] + 2 * np.sqrt(evals[k]) * evecs[k, 1]],
color=col, lw=3, label=f"PC{k + 1} (2 standard deviations)")
ax[0].set(xlim=(-6, 8), ylim=(-6, 8), aspect="equal", xlabel="$x_1$", ylabel="$x_2$", title="Data and principal axes")
ax[0].legend(fontsize=8)
ax[1].plot(scores[:, 0], scores[:, 1], ".", color="k", alpha=0.1)
ax[1].set(xlim=(-7, 7), ylim=(-7, 7), aspect="equal", xlabel="PC1 score", ylabel="PC2 score",
title="Same data in the principal-axis frame")
fig.tight_layout()
def plot_geochem(pca, scores, labels, names, cum_var, n90):
fig, ax = plt.subplots(1, 3, figsize=(15, 4), gridspec_kw={"width_ratios": [1, 1.1, 1]})
k = np.arange(1, len(cum_var) + 1)
ax[0].bar(k, pca.explained_variance_ratio_, color="0.6", label="per component")
ax[0].plot(k, cum_var, "o-", color="k", label="cumulative")
ax[0].axhline(0.9, color="C3", ls="--", lw=1, label="90%")
ax[0].axvline(n90, color="C3", ls=":", lw=1)
ax[0].set(xlabel="principal component", ylabel="fraction of variance", title="Variance explained")
ax[0].legend(fontsize=8)
load = pca.components_[0]
ax[1].bar(names, load, color=["C3" if v < 0 else "C0" for v in load])
ax[1].tick_params(axis="x", rotation=60)
ax[1].set(ylabel="loading", title=f"PC1 loadings ({100 * pca.explained_variance_ratio_[0]:.0f}% of variance)")
for lith, col in LITH_COLORS.items():
m = labels == lith
ax[2].scatter(scores[m, 0], scores[m, 1], s=5, alpha=0.4, color=col, label=lith)
ax[2].set(xlabel="PC1 score (differentiation index)", ylabel="PC2 score", title="Samples, colored by rock type")
ax[2].legend(fontsize=8, markerscale=3)
fig.tight_layout()
def plot_modes(maps, pcs, var_frac, source):
fig, ax = plt.subplots(2, 2, figsize=(14, 6.5), gridspec_kw={"width_ratios": [1.6, 1]})
for k, m in enumerate(maps):
lim = float(abs(m).max())
im = ax[k, 0].pcolormesh(m["lon"], m["lat"], m, cmap="RdBu_r", vmin=-lim, vmax=lim, shading="auto")
fig.colorbar(im, ax=ax[k, 0], label="°C per std of PC", fraction=0.03, pad=0.02)
ax[k, 0].set(title=f"EOF{k + 1}, {100 * var_frac[k]:.1f}% of variance ({source})", ylabel="latitude (°N)",
facecolor="0.85")
if source != "synthetic":
ax[k, 0].add_patch(plt.Rectangle((190, -5), 50, 10, fill=False, ls="--", lw=1))
ax[k, 0].set_aspect("equal")
pc = pcs.iloc[:, k] / pcs.iloc[:, k].std()
ax[k, 1].plot(pc.index, pc, lw=0.6, color="0.4")
ax[k, 1].plot(pc.index, pc.rolling(12, center=True).mean(), lw=1.5, color="C3" if k == 0 else "C0",
label="12-month running mean")
ax[k, 1].set(title=f"PC{k + 1} (standardized)", ylabel="std")
ax[k, 1].legend(fontsize=8, loc="upper left")
ax[1, 0].set_xlabel("longitude (°E)")
fig.tight_layout()
def plot_pc1_nino(pc1, nino_s, r, source):
fig, ax = plt.subplots(figsize=(12, 3.2))
ax.plot(pc1.index, (pc1 - pc1.mean()) / pc1.std(), lw=1, color="C3", label="PC1 (standardized)")
lab = "Nino 3.4 index (standardized)" if source != "synthetic" else "planted zonal mode amplitude (standardized)"
ax.plot(nino_s.index, (nino_s - nino_s.mean()) / nino_s.std(), lw=1, color="k", alpha=0.7, label=lab)
ax.set(ylabel="std", title=f"PC1 against an independent index, r = {r:.2f}")
ax.legend(fontsize=8, ncol=2, loc="upper left")
def plot_tsne(embeddings, labels):
fig, ax = plt.subplots(1, len(embeddings), figsize=(5 * len(embeddings), 4.3))
for a, (perp, emb) in zip(np.atleast_1d(ax), embeddings.items()):
for lith, col in LITH_COLORS.items():
m = labels == lith
a.scatter(emb[m, 0], emb[m, 1], s=5, alpha=0.5, color=col, label=lith)
a.set(title=f"t-SNE, perplexity {perp}", xticks=[], yticks=[])
np.atleast_1d(ax)[0].legend(fontsize=8, markerscale=3)
fig.tight_layout()
# ---- checks for the Your-turn cells ------------------------------------------------------------------------------
TURNS = {"D": ["sizes"], "P1": ["toy_var_frac", "scores"], "P2": ["cum_var", "n90"],
"E1": ["anom", "anom_w"], "E2": ["U", "S", "VT", "var_frac"], "E3": ["r_nino"]}
HINTS = {
"D": "for each array a in datasets: N = a.shape[0], D = int(np.prod(a.shape[1:])), MB = a.nbytes / 1e6; "
"collect one dict per dataset and build pd.DataFrame(rows).set_index('dataset') with columns N, D, N/D, MB.",
"P1": "toy_var_frac = evals / evals.sum(); scores = B.T @ evecs.T (each row of evecs is one principal axis).",
"P2": "cum_var = np.cumsum(pca.explained_variance_ratio_); n90 = the first k with cum_var >= 0.9, "
"for example int(np.argmax(cum_var >= 0.9)) + 1.",
"E1": "clim = sst.sel(time=slice('1991', '2020')).groupby('time.month').mean('time'); "
"anom = sst.groupby('time.month') - clim; anom_w = anom * np.sqrt(np.cos(np.deg2rad(anom.lat))).",
"E2": "U, S, VT = np.linalg.svd(X.values, full_matrices=False); var_frac = S**2 / np.sum(S**2).",
"E3": "pc1.corr(nino_s), or np.corrcoef on the two aligned arrays (pandas skips missing months for you).",
}
def _ref(key, ns):
r = {}
if key == "D":
rows = [{"dataset": n, "N": a.shape[0], "D": int(np.prod(a.shape[1:])), "N/D": a.shape[0] / np.prod(a.shape[1:]),
"MB": a.nbytes / 1e6} for n, a in ns["datasets"].items()]
r["sizes"] = pd.DataFrame(rows).set_index("dataset")
elif key == "P1":
r["toy_var_frac"] = ns["evals"] / ns["evals"].sum()
r["scores"] = ns["B"].T @ ns["evecs"].T
elif key == "P2":
r["cum_var"] = np.cumsum(ns["pca"].explained_variance_ratio_)
r["n90"] = int(np.argmax(r["cum_var"] >= 0.9)) + 1
elif key == "E1":
sst = ns["sst"]
clim = sst.sel(time=slice("1991", "2020")).groupby("time.month").mean("time")
r["anom"] = sst.groupby("time.month") - clim
r["anom_w"] = r["anom"] * np.sqrt(np.cos(np.deg2rad(r["anom"].lat)))
elif key == "E2":
r["U"], r["S"], r["VT"] = np.linalg.svd(ns["X"].values, full_matrices=False)
r["var_frac"] = r["S"] ** 2 / np.sum(r["S"] ** 2)
elif key == "E3":
r["r_nino"] = ns["pc1"].corr(ns["nino_s"])
return r
def _close(a, b, rtol=1e-3):
try:
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
except (TypeError, ValueError):
return False
if a.shape != b.shape or not np.array_equal(np.isnan(a), np.isnan(b)):
return False
m = ~np.isnan(b)
return bool(np.allclose(a[m], b[m], rtol=rtol, atol=1e-6 * (np.abs(b[m]).max() if m.any() else 1)))
def _verdict(key, v, r):
hint = "not yet. Hint: " + HINTS[key]
if key == "D":
s = v["sizes"]
if not isinstance(s, pd.DataFrame) or not set(["N", "D", "N/D", "MB"]) <= set(s.columns):
return "not yet: sizes should be a DataFrame with columns N, D, N/D and MB. Hint: " + HINTS[key]
s, ref = s.loc[r["sizes"].index] if set(r["sizes"].index) <= set(s.index) else s, r["sizes"]
if not _close(s[["N", "D", "N/D"]].to_numpy(), ref[["N", "D", "N/D"]].to_numpy()):
return hint
mb_ok = _close(s["MB"], ref["MB"], 0.01) or _close(s["MB"], ref["MB"] * 1e6 / 2**20, 0.01)
return "correct" if mb_ok else "not yet: MB should be a.nbytes / 1e6 (bytes to megabytes)."
if key == "E2":
ok = _close(v["S"], r["S"]) and _close(v["var_frac"], r["var_frac"]) and np.shape(v["VT"]) == np.shape(r["VT"])
return "correct" if ok else hint # U and VT are defined up to a sign per mode, so only S is compared
if key == "E1":
ok = all(_close(getattr(v[n], "values", v[n]), r[n].values) for n in TURNS[key])
return "correct" if ok else hint
ok = all(_close(v[n], r[n]) for n in TURNS[key])
return "correct" if ok else hint
def your_turn(key, ns):
r = _ref(key, ns)
v = {n: ns.get(n) for n in TURNS[key]}
verdict = "not answered yet" if all(x is None for x in v.values()) else _verdict(key, v, r)
print(f"[{key}] {verdict}")
if verdict == "correct":
return
kept = []
for n in TURNS[key]:
if ns.get(n) is not None:
ns[n + "_yours"] = ns[n]
kept.append(n + "_yours")
ns[n] = r[n]
note = f"; yours kept as {', '.join(kept)}" if kept else ""
print(f"[{', '.join(TURNS[key])}] using the reference result so the next cells run{note}.")2. Data dimension and data size¶
The dimension of one sample, , is the number of values that describe it once flattened: the features of a table row (nine for one rock analysis below), time samples times components for a waveform, pixels times bands for an image patch, grid points times levels times variables for a gridded atmospheric state. It is not the rank of the array that stores the sample. A seismogram is a 2D array (component, time), an image patch 3D, a climate state 4D; each is still a single point in a -dimensional space.
The size of a dataset is the number of samples and its volume in bytes (for a dense array, bytes per value).
What matters for learning is how compares with . With few samples in a high-dimensional space, most of the space is empty, the distances between any two samples become similar (so nearest neighbors and clusters lose contrast), and a model with many parameters fits the noise. Many geoscience datasets escape this because their intrinsic dimension, the number of directions that actually carry the variance, is much smaller than : neighboring time samples of a seismogram, or neighboring grid points of a temperature field, are strongly correlated. PCA estimates the intrinsic dimension. This is criterion B6 (Dimensionality) of the AI-ready rubric in 2.13.
We load three course datasets. For the sea surface temperature (section 5) one sample is one monthly map.
geochem = mlgeo_synth.geochem_table(n=5000, seed=42) # synthetic whole-rock analyses, one row per sample
waveforms = np.zeros((1000, 3, 6000), dtype=np.float32) # 1000 windows, 3 components, 60 s at 100 Hz (shape only)
sst, sst_source = load_ersst() # monthly SST maps, degrees C (time, lat, lon)
datasets = {"geochemical table": geochem.drop(columns="label").to_numpy(),
"waveform windows": waveforms, "SST monthly maps": sst.values}ERSST v5 (Huang et al., 2017) read through OPeNDAP from NOAA PSL: {'time': 912, 'lat': 21, 'lon': 81}
Your turn: dimension and size. For each array in datasets (first axis = samples), compute , , and the in-memory size in MB, and collect them in a DataFrame sizes indexed by dataset name, with columns N, D, N/D, MB.
Hint: int(np.prod(a.shape[1:])) and a.nbytes / 1e6.
# --- your code
sizes = None # DataFrame: index = dataset name, columns N, D, N/D, MB
# --- end
your_turn("D", globals())[D] not answered yet
[sizes] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
rows_sol = []
for name, a in datasets.items():
N, D = a.shape[0], int(np.prod(a.shape[1:]))
rows_sol.append({"dataset": name, "N": N, "D": D, "N/D": N / D, "MB": a.nbytes / 1e6})
sizes_sol = pd.DataFrame(rows_sol).set_index("dataset")print(sizes.round(3)) N D N/D MB
dataset
geochemical table 5000 9 555.556 0.360
waveform windows 1000 18000 0.056 72.000
SST monthly maps 912 1701 0.536 6.205
Only the rock table has many more samples than dimensions. The waveform windows and the monthly maps have : as raw vectors they are thin clouds in a very large space, and whether a model can learn from them depends on their intrinsic dimension, which sections 4 and 5 measure. Part of the SST is land (missing values), removed in section 5.
For scale (approximate, computed from shapes): a STEAD earthquake waveform is 3 × 6000 = 18,000 values; a Sentinel-2 patch of 120 × 120 pixels with 12 bands is 172,800 values; one ERA5 global state is 1440 × 721 grid points × 13 pressure levels ≈ 13.5 million values per variable, about 54 MB in float32.
3. PCA in three steps¶
PCA finds the orthogonal directions along which the data vary most. We build it by hand on a cloud of 10,000 points in two dimensions, drawn from a Gaussian with standard deviations 2 and 0.5 along its axes, rotated by 60°. PCA should recover that rotation.
Step 1: remove the mean. Each row of X is one variable, each column one sample.
X = toy_cloud() # shape (2 variables, 10000 samples)
B = X - X.mean(axis=1, keepdims=True) # mean-removed data
covB = B @ B.T / (B.shape[1] - 1) # 2 x 2 covariance matrix
print(covB.round(3))[[1.212 1.651]
[1.651 3.09 ]]
Step 2: SVD of the covariance matrix. The covariance matrix is symmetric, so its SVD returns its eigenvalues (the variance along each principal axis, largest first) and its eigenvectors (the axes). The same axes come out of the SVD of the data matrix B itself, with eigenvalues equal to the squared singular values divided by ; that is the form we use for the climate field in section 5.
_, evals, evecs = np.linalg.svd(covB) # rows of evecs are the principal axes
print("variance along each axis:", evals.round(3), " axes (rows):\n", evecs.round(3))variance along each axis: [4.051 0.251] axes (rows):
[[-0.503 -0.864]
[-0.864 0.503]]
The variances are close to and , the values used to build the cloud, and the first axis points at about 60° from the axis (the sign of an axis is arbitrary).
Step 3: variance explained and projection.
Your turn. Write toy_var_frac, the fraction of the total variance carried by each axis, and scores, the coordinates of every sample in the principal-axis frame (shape 10000 × 2).
Hint: divide evals by its sum; project with B.T @ evecs.T.
# --- your code
toy_var_frac = None # 2 values summing to 1
scores = None # array (10000, 2)
# --- end
your_turn("P1", globals())[P1] not answered yet
[toy_var_frac, scores] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
toy_var_frac_sol = evals / evals.sum()
scores_sol = B.T @ evecs.Tprint("fraction of variance per axis:", toy_var_frac.round(3))
plot_toy(X, evals, evecs, scores)fraction of variance per axis: [0.942 0.058]

PC1 carries about 94% of the variance. The projection rotates the cloud so that the direction of largest variance lies along the horizontal axis: one number per sample now describes most of what the two original numbers did.
4. PCA on a geochemical table¶
The synthetic table from mlgeo_synth holds 5000 whole-rock analyses: seven major-element oxides (wt%), density and magnetic susceptibility, plus a rock type (basalt, andesite, granite) that PCA does not see. The generator drives the oxides with a hidden differentiation index: as a melt evolves, SiO2, Na2O and K2O rise while MgO, FeO and CaO fall. Features are standardized first, because oxides span tens of wt% while magnetic susceptibility is of order 10-3 SI and would otherwise not count.
features = geochem.drop(columns="label")
Z = StandardScaler().fit_transform(features) # zero mean, unit variance per feature
pca = PCA().fit(Z)
geo_scores = pca.transform(Z)Your turn: the variance-explained curve. Write cum_var, the cumulative fraction of variance explained by the components, and n90, the number of components needed to reach 90% of the variance.
Hint: np.cumsum(pca.explained_variance_ratio_); then the first index where cum_var >= 0.9, plus one.
# --- your code
cum_var = None # 9 values increasing to 1
n90 = None # integer
# --- end
your_turn("P2", globals())[P2] not answered yet
[cum_var, n90] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
cum_var_sol = np.cumsum(pca.explained_variance_ratio_)
n90_sol = int(np.argmax(cum_var_sol >= 0.9)) + 1print(f"PC1 carries {100 * pca.explained_variance_ratio_[0]:.1f}% of the variance; {n90} components reach 90% "
f"(cumulative: {np.round(cum_var, 3)})")
plot_geochem(pca, geo_scores, geochem["label"].to_numpy(), features.columns, cum_var, n90)PC1 carries 78.2% of the variance; 3 components reach 90% (cumulative: [0.782 0.879 0.939 0.977 0.987 0.993 0.996 0.999 1. ])

PC1 carries about four fifths of the variance and three components pass 90% (two reach 88%). On PC1, SiO2, Na2O and K2O load with one sign and MgO, FeO, CaO, density and magnetic susceptibility with the other: PC1 is the differentiation index the generator planted, and a sample’s PC1 score places it on the basalt-to-granite range in one number. PCA never saw the rock types, yet they separate along PC1, because composition and rock type come from the same process; PC2 then sets the andesites apart from the two end members.
Link to rubric criterion B6. For this table and , and the intrinsic dimension is about three, not nine. A B6 entry that scores 2 reports both numbers (, ) and the variance-explained curve with the number of components for 90%, as you just did. Real oxide tables add closure (an analysis sums to about 100 wt%), which creates correlations of its own; this synthetic table is not closed (see 2.4).
5. EOFs of tropical Pacific sea surface temperature¶
Applied to a field that varies in space and time, PCA is called EOF analysis. Each sample is one monthly map; each principal axis is a map, the EOF; and the score of each month on it is a time series, the principal component (PC). Together they say which spatial pattern varies most and when.
Data. NOAA Extended Reconstructed Sea Surface Temperature version 5 (ERSST v5; Huang et al., 2017, J. Climate, Huang et al. (2017)): monthly SST on a 2° grid built from ship, buoy and Argo measurements. The setup cell read 20°S to 20°N, 120°E to 280°E (80°W), January 1950 to December 2025, through OPeNDAP, which transfers only that region. The tropical Pacific holds the largest mode of year-to-year climate variability, the El Niño Southern Oscillation (ENSO).
Recipe. (1) Remove the seasonal cycle: subtract the 1991 to 2020 mean of each calendar month at each grid point, and do not detrend. (2) Multiply by , so that the contribution of a grid cell to the variance, which is quadratic in the data, is proportional to its area. (3) Reshape to a (time × space) matrix, drop land points, and take its SVD.
Your turn: anomalies and weights. Write anom, the SST anomaly with respect to the 1991 to 2020 monthly climatology, and anom_w, the anomaly multiplied by the square root of the cosine of latitude.
Hint: sst.sel(time=slice("1991", "2020")).groupby("time.month").mean("time"), then sst.groupby("time.month") - clim; np.deg2rad(anom.lat).
# --- your code
anom = None # DataArray (time, lat, lon), degrees C
anom_w = None # same shape, weighted
# --- end
your_turn("E1", globals())[E1] not answered yet
[anom, anom_w] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
clim_sol = sst.sel(time=slice("1991", "2020")).groupby("time.month").mean("time")
anom_sol = sst.groupby("time.month") - clim_sol
anom_w_sol = anom_sol * np.sqrt(np.cos(np.deg2rad(anom_sol.lat)))X = anom_w.stack(space=("lat", "lon")).dropna("space", how="any") # (time, space), land points removed
print(f"{X.sizes['time']} months x {X.sizes['space']} ocean grid points "
f"({sst.sizes['lat'] * sst.sizes['lon'] - X.sizes['space']} land or missing points dropped)")912 months x 1626 ocean grid points (75 land or missing points dropped)
Your turn: the SVD. Take the SVD of the matrix X.values and write var_frac, the fraction of variance of each mode.
Hint: np.linalg.svd(..., full_matrices=False) returns U, S, VT; the variance of mode is proportional to .
# --- your code
U, S, VT = None, None, None # from np.linalg.svd
var_frac = None # one value per mode
# --- end
your_turn("E2", globals())[E2] not answered yet
[U, S, VT, var_frac] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
U_sol, S_sol, VT_sol = np.linalg.svd(X.values, full_matrices=False)
var_frac_sol = S_sol**2 / np.sum(S_sol**2)print("variance fraction, EOF1 to EOF5:", np.round(var_frac[:5], 3), f"(sum {var_frac[:5].sum():.3f})")
pcs = pd.DataFrame(U[:, :5] * S[:5], index=X["time"].to_index(), columns=[f"PC{k}" for k in range(1, 6)])
pcs = orient(pcs, VT, X) # signs: EOF1 warm in the Nino 3.4 box, PC2 rising
maps = [regress_map(anom, pcs[f"PC{k}"]) for k in (1, 2)] # EOF as degrees C per standard deviation of its PC
plot_modes(maps, pcs, var_frac, sst_source)variance fraction, EOF1 to EOF5: [0.525 0.17 0.084 0.034 0.027] (sum 0.840)

Reading the modes (ERSST v5; the dashed box is the Niño 3.4 region, 5°S to 5°N, 170°W to 120°W).
EOF1 is ENSO. Its map is a tongue of warm anomaly along the equator from the coast of Ecuador and Peru to the date line, about 1 °C per standard deviation of PC1, strongest near the coast. PC1 peaks in El Niño winters (1972-73, 1982-83, 1997-98, 2015-16, 2023-24) and is negative in La Niña years (1955-56, 1973-76, 1988-89, 1999-2000, 2010-11, 2020-22). It also drifts upward from the 1950s: a little of the warming trend leaks into the leading mode.
EOF2 is mostly the long-term trend. With the sign chosen so that PC2 rises, its map is warm over the western Pacific warm pool and the subtropics and cool along the equatorial cold tongue, a pattern in which the west has warmed more than the east; PC2 rises from the 1950s to the 2020s. PC2 also drops sharply in the strongest El Niño winters (1965-66, 1972-73, 1982-83, 1997-98, 2015-16). In those events, the warm anomaly reached farther east, to the South American coast, than EOF1 alone describes; EOF2 carries that part of ENSO diversity (eastern-Pacific versus central-Pacific events). We did not detrend, so the warming had to appear somewhere, and the SVD put most of it in a mode shared with ENSO asymmetry.
These modes are statistical: EOFs are orthogonal and PCs uncorrelated by construction, while physical processes are under no such constraint, so one EOF can mix processes (EOF2) and one process can spread over several EOFs. They also depend on the region, period and preprocessing. A mode is physical only once it is checked against an independent observation or a mechanism. We check EOF1 against the Niño 3.4 index published by NOAA PSL.
nino = load_nino34(anom)
pc1 = pcs["PC1"]
nino_s = nino.reindex(pc1.index) # same months as PC1Nino 3.4 file, as stated in its last lines: NINA34 | 5N-5S 170W-120W | ERSST V6 | Anomaly from 1981-2010 | https://psl.noaa.gov/data/timeseries/month/DS/NINO34/ | units=degC
Your turn: validate PC1. Write r_nino, the correlation between pc1 and nino_s.
Hint: pc1.corr(nino_s).
# --- your code
r_nino = None # a number between -1 and 1
# --- end
your_turn("E3", globals())[E3] not answered yet
[r_nino] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
r_nino_sol = pc1.corr(nino_s)print(f"correlation of PC1 with the comparison index over {nino_s.notna().sum()} months: r = {r_nino:.3f}")
plot_pc1_nino(pc1, nino_s, r_nino, sst_source)correlation of PC1 with the comparison index over 912 months: r = 0.929

The correlation, 0.94 with ERSST v5, means that EOF1 is the ENSO signal that the Niño 3.4 box average tracks. The check is independent in method (a box average against a basin-wide decomposition), not fully in data: as the file states, the PSL index is computed from ERSST (a later version), with anomalies from a 1981 to 2010 base. The PC also captures a small part of the trend that the fixed-box index does not.
6. t-SNE for visualization only¶
PCA is linear: it keeps the large-scale geometry and can be inverted. t-distributed Stochastic Neighbor Embedding (t-SNE) is nonlinear and built only to draw: it places the samples in a plane so that neighbors in the original space stay neighbors. We embed 1500 rocks from the standardized table (t-SNE is slow on large sets) at two values of perplexity, roughly the number of neighbors each sample considers.
idx = np.random.default_rng(42).choice(len(Z), size=1500, replace=False)
emb = {p: TSNE(n_components=2, perplexity=p, random_state=42).fit_transform(Z[idx]) for p in (5, 50)}
plot_tsne(emb, geochem["label"].to_numpy()[idx])
Both embeddings separate the rock types, but the shapes, the sizes of the groups and the gaps between them change with perplexity. Distances and cluster sizes in a t-SNE plot are not meaningful: use it to look, never to measure or to feed a model. Whether the groups you see are real is a clustering question, which is the second half of this session (3.3).
7. Optional: Independent Component Analysis¶
ICA helps when the measurements are linear mixtures of independent, non-Gaussian sources and you want the sources back (blind source separation), for example tectonic, hydrological and seasonal signals mixed in GNSS time series. PCA finds uncorrelated, orthogonal directions of maximum variance; ICA finds statistically independent directions, not necessarily orthogonal. Below, three known signals are mixed into three “receivers”.
t = np.linspace(0, 8, 2000)
sources = np.c_[np.sin(2 * t), np.sign(np.sin(3 * t)), signal.sawtooth(2 * np.pi * t)]
sources += 0.2 * np.random.default_rng(0).standard_normal(sources.shape)
mixed = sources @ np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]]).T # 3 receivers
unmixed = {"ICA": FastICA(n_components=3, random_state=0).fit_transform(mixed),
"PCA": PCA(n_components=3).fit_transform(mixed)}
fig, ax = plt.subplots(4, 1, figsize=(10, 7), sharex=True)
for a, (name, s) in zip(ax, {"mixed (receivers)": mixed, "true sources": sources, **unmixed}.items()):
a.plot(t, s / s.std(axis=0) + [0, 4, 8], lw=0.7)
a.set(title=name, yticks=[])
fig.tight_layout()
ICA recovers the sine, square and sawtooth waves (in any order, sign and scale); the PCA components remain mixtures.
8. Summary¶
| Method | What it preserves | Use it to |
|---|---|---|
| PCA / EOF | directions of largest variance; linear, invertible | compress correlated features, estimate the intrinsic dimension (B6), find the dominant modes of a field |
| t-SNE | local neighborhoods only; not distances, not density | look at a high-dimensional dataset in 2D before clustering |
| ICA | statistically independent, non-Gaussian sources | separate signals recorded as linear mixtures |
- Huang, B., Thorne, P. W., Banzon, V. F., Boyer, T., Chepurin, G., Lawrimore, J. H., Menne, M. J., Smith, T. M., Vose, R. S., & Zhang, H.-M. (2017). Extended Reconstructed Sea Surface Temperature, Version 5 (ERSSTv5): Upgrades, Validations, and Intercomparisons. Journal of Climate, 30(20), 8179–8205. 10.1175/jcli-d-16-0836.1