Sub topic 3
PCA: the linear baseline
This chapter assumes you know basic Python and NumPy, the scikit-learn fit/transform interface, Euclidean distance, and the idea of a feature vector. Principal component analysis (PCA) is the first method to try before t-SNE or UMAP. It gives you a reference plot, and it shows what a nonlinear method adds.
What PCA does
PCA finds new axes, called principal components, that are straight lines through the data. The first component points in the direction of greatest variance. The second is perpendicular to the first and captures the most variance that remains. Projecting each point onto the first two components gives a 2-D picture.
Internally, PCA centres the data and then finds the eigenvectors of the covariance matrix. Scikit-learn does this with a singular value decomposition (SVD). Each component has an explained variance, which tells you how much of the total spread it captures.
Running PCA on the digits data
The digits dataset has 1,797 images, each 8x8 pixels, so each point has 64 features.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
pca = PCA(n_components=2, random_state=0)
Z = pca.fit_transform(X)
print(pca.explained_variance_ratio_)
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()The printed explained_variance_ratio_ shows the share of total variance each component keeps. For digits, two components keep only about 29% in total. The other 71% of the variance is thrown away, so the plot is a heavily compressed view.
In the plot, some digits form loose groups, but many classes overlap in the middle. That overlap is the main reason to try a nonlinear method.
What PCA is good for
- Speed and determinism. It is fast and gives the same answer every run, apart from the sign of a component.
- Global structure. Large distances in the plot reflect large distances in the data, so the layout is meaningful at a coarse scale.
- Reuse.
transformworks on new points, and the components can be inspected. - Preprocessing. Reducing to 30 to 50 components before t-SNE or UMAP removes noise and saves time.
Common errors
- Forgetting to scale. PCA follows variance, so a feature measured in large units dominates. When features have different units, standardise them first with
StandardScaler. The digits pixels share one scale, so it is not needed here. - Reading components as clusters. A component is a direction, not a group. Points that overlap in 2-D may be far apart in other dimensions.
- Expecting curved structure. PCA can only rotate and project. If the data lies on a curved sheet, such as a spiral, a straight projection flattens it and mixes up distant parts.
Exercise
PCA on a dataset with two features, height in metres (values near 1.7) and income in dollars (values near 50,000), gives a first component that points almost entirely along income. Why, and what is the fix?
Show answer
PCA maximises variance, and income has a far larger numeric spread than height, so it dominates the first component. Standardise both features with StandardScaler (zero mean, unit variance) before fitting PCA.