Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2.12 Dimensionality reduction

🖥️ Lecture slides: Session 13 (Wed Oct 28), first half

1. Learning outcomes

By the end of this notebook you can:

  1. state the dimension DD of one sample and the size of a dataset (number of samples NN, volume in bytes) for a table, a set of waveforms and a gridded field, and say why N/DN/D and the intrinsic dimension matter for learning;

  2. 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);

  3. 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);

  4. 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;

  5. 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

2. Data dimension and data size

The dimension of one sample, DD, 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 DD-dimensional space.

The size of a dataset is the number of samples NN and its volume in bytes (for a dense array, N×D×N \times D \times bytes per value).

What matters for learning is how NN compares with DD. 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 DD: 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.

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 NN, DD, N/DN/D 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.

[D] not answered yet
[sizes] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
                      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 N<DN < D: 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 DD 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.

[[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 N−1N-1; that is the form we use for the climate field in section 5.

variance along each axis: [4.051 0.251]   axes (rows):
 [[-0.503 -0.864]
 [-0.864  0.503]]

The variances are close to 22=42^2 = 4 and 0.52=0.250.5^2 = 0.25, the values used to build the cloud, and the first axis points at about 60° from the x1x_1 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.

[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
fraction of variance per axis: [0.942 0.058]
<Figure size 1000x450 with 2 Axes>

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.

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.

[P2] not answered yet
[cum_var, n90] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
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.   ])
<Figure size 1500x400 with 3 Axes>

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 N=5000N = 5000 and D=9D = 9, and the intrinsic dimension is about three, not nine. A B6 entry that scores 2 reports both numbers (NN, DD) 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 cos⁡(latitude)\sqrt{\cos(\text{latitude})}, 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).

[E1] not answered yet
[anom, anom_w] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
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 kk is proportional to Sk2S_k^2.

[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
variance fraction, EOF1 to EOF5: [0.525 0.17  0.084 0.034 0.027] (sum 0.840)
<Figure size 1400x650 with 6 Axes>

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 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).

[E3] not answered yet
[r_nino] using the reference result so the next cells run.

Worked solution below (click ⋯ to open).

Notebook Cell
correlation of PC1 with the comparison index over 912 months: r = 0.929
<Figure size 1200x320 with 1 Axes>

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.

<Figure size 1000x430 with 2 Axes>

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”.

<Figure size 1000x700 with 4 Axes>

ICA recovers the sine, square and sawtooth waves (in any order, sign and scale); the PCA components remain mixtures.

8. Summary

MethodWhat it preservesUse it to
PCA / EOFdirections of largest variance; linear, invertiblecompress correlated features, estimate the intrinsic dimension (B6), find the dominant modes of a field
t-SNElocal neighborhoods only; not distances, not densitylook at a high-dimensional dataset in 2D before clustering
ICAstatistically independent, non-Gaussian sourcesseparate signals recorded as linear mixtures
References
  1. 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