Sub topic 3
PCA: the linear baseline
Principal component analysis (PCA) is the method you run before t-SNE or UMAP. It is fast, deterministic and easy to explain. It also shows how much structure a straight-line projection can capture. If PCA already separates your classes, you may not need anything fancier.
This chapter assumes you know basic Python and NumPy, the scikit-learn fit/transform interface, Euclidean distance, and the idea of a feature vector.
What PCA does
PCA finds a new set of perpendicular axes for your data. These axes are the principal components. The first axis points along the direction of greatest variance. The second axis has the greatest variance among directions perpendicular to the first, and so on. Keeping only the first two or three axes gives a low-dimensional view that preserves as much total variance as any linear projection of that size can.
PCA is linear. Each output coordinate is a weighted sum of the input features, so it can only rotate, project and flatten the data. It cannot unroll a curved surface.
How it works internally
Let Xc be the data with each column's mean subtracted. The singular value decomposition (SVD) factors it as Xc = U S Vt. The rows of Vt are the principal directions. The squared singular values give the variance along each direction: explained_variance = S**2 / (n - 1). The projection onto the first k components is Xc @ Vt[:k].T.
You can check this against scikit-learn:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
Z_svd = Xc @ Vt[:2].T
pca = PCA(n_components=2, svd_solver="full").fit(X)
Z_pca = pca.transform(X)
# Component signs are arbitrary, so compare absolute values.
print(np.allclose(np.abs(Z_svd), np.abs(Z_pca)))
print(np.allclose(S[:2] ** 2 / (len(X) - 1), pca.explained_variance_))Both lines print True. The sign comparison matters. An eigenvector and its negative describe the same axis, so two runs or two libraries can return mirrored plots. A flipped PCA plot is not a different result.
A 2-D baseline plot
This code projects the 64-pixel digit images onto the first two components:
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
Z = PCA(n_components=2, random_state=0).fit_transform(X)
plt.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=8)
plt.colorbar(label="digit")
plt.title("PCA of the 64-dimensional digits data")
plt.show()Some digits, such as 0 and 6, separate fairly well. Many others overlap heavily in the centre. That overlap is the baseline the nonlinear methods in later chapters try to beat.
What the projection costs
The cost is measured by the explained variance ratio. This is the share of total variance each component keeps:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
pca = PCA(random_state=0).fit(X)
cum = np.cumsum(pca.explained_variance_ratio_)
print(f"first 2 components keep {cum[1]:.1%} of the variance")
print("components needed for 90%:", int(np.searchsorted(cum, 0.90)) + 1)For the digits data, two components keep roughly 29% of the variance. About 21 components are needed to reach 90%. A 2-D plot therefore discards most of the information, and what you see is a thin slice of the data.
A plot of cumulative variance against component count is called a scree-style plot. It helps you choose how many components to keep when you use PCA as preprocessing instead of as a final picture.
Preprocessing decisions
PCA is sensitive to feature scale, because it maximises variance and a feature with large numeric values has large variance.
| Situation | What to do |
|---|---|
| Features share units and meaning, such as pixel intensities | Centre only. PCA does this for you. |
| Features have different units or ranges, such as age and income | Standardise each column first with `StandardScaler`. |
| A few features have extreme outliers | Consider a robust scaler or a transform such as log. Otherwise outliers can capture a whole component. |
| Count data with heavy skew | Transform first, for example `log1p`. |
Scaling changes the result. Standardising gives every feature equal weight, which can amplify noisy low-variance features. Pick the option that matches what you want "distance" to mean, and keep it identical when you later compare methods.
Common errors
- Reading axes as meaningful quantities. Component 1 is a mix of many features. Inspect
pca.components_to see the weights before you give an axis a name. - Comparing runs by sign. Mirrored plots are the same solution, as shown above.
- Forgetting that PCA preserves large distances, not small ones. PCA keeps far-apart points far apart. It does not protect small neighbourhoods, so nearby points can land on top of each other when they differ along a dropped direction.
- Expecting clusters to appear. If classes differ along curved or twisted structure, a linear projection can overlay them.
- Using too many components for visualisation. Plotting only components 1 and 2 hides structure in components 3 and above. Try pairs such as 1 and 3, or a 3-D view.
PCA as the first stage of a pipeline
PCA is also used for preprocessing. On data with hundreds or thousands of features, a common recipe is to reduce to about 30 to 50 components with PCA and then run t-SNE or UMAP on the result. This lowers memory use and run time. It can also remove some noise, because the discarded low-variance directions often contain mostly noise. Later chapters return to this in the workflow.
The same idea gives the PCA initialisation that t-SNE offers with init="pca". Starting from the first two components gives a layout whose global arrangement already reflects the data, which makes runs more stable.
Using PCA as a baseline
A baseline is only useful if you can compare against it with something other than your eyes. Keep these habits:
- Run PCA first and note the explained variance of the first two components.
- Colour the plot by any labels you have and see whether classes separate.
- Keep the same preprocessing for every method you compare.
- Later, score each embedding with a neighbourhood-preservation measure such as trustworthiness, covered in the quality metrics chapter.
If a nonlinear embedding shows structure that PCA does not, that is evidence of curved or local structure in the data. It is not proof that the structure is real, and the chapter on reading plots explains how to check.
Exercise
You run PCA on a table with columns for height in centimetres (values around 170) and annual income in dollars (values around 50,000), without scaling. The first component explains 99.9% of the variance. What most likely happened, and how do you fix it?
Show answer
Income has a far larger numeric range and variance than height, so the first component is almost entirely the income axis. The 99.9% figure reflects the units, not the true structure. Standardise both columns with StandardScaler (fitted on training data) before PCA, then check the explained variance again.
Exercise
Two colleagues run PCA on the same data. Their scatter plots look like mirror images of each other. Is one of them wrong?
Show answer
No. A principal direction and its negative describe the same axis, so the sign of each component is arbitrary. Both plots show the same solution, and comparing absolute values of the projections (as in the SVD check above) confirms it.