Key ideas
- Why reduce: fewer features to store and learn from, visualisation in 2-D/3-D, noise removal, and relief from the curse of dimensionality (in high dimensions the data are sparse)4. Example: the fraction of the cube inside the inscribed ball is for , for and for , and it keeps shrinking towards 0.
- Feature selection keeps a subset of the original columns (variance threshold, univariate tests, RFE). Feature extraction builds new features from all of them (PCA, NMF, autoencoders)4.
- PCA finds orthonormal directions (principal axes) in feature space. The first maximises the variance of the projected data; each next one maximises the remaining variance while staying orthogonal to the earlier ones3. They are the eigenvectors of the covariance matrix, and each eigenvalue is the variance along its axis3. The new coordinates (scores) are uncorrelated3.
- PCA must work on centred data; scikit-learn centres each feature but does not scale it2. With features in different units (dollars vs years), the high-variance one dominates PC1, so standardise first3.
- Equivalently, PCA keeps the -dimensional hyperplane through the mean that best reconstructs the data in squared error, which is the truncated SVD of the centred matrix (Eckart–Young)3. With the reconstruction is exact; the scores are still rotated coordinates, not the original .
- Choosing : keep the smallest whose cumulative explained-variance ratio reaches a target such as 90–95%, or look for the bend in a scree plot3. In scikit-learn,
PCA(n_components=0.95, svd_solver="full")does this for you2. - Loadings (the weights in each component) show which original features drive it: same signs mean the features rise together, opposite signs a contrast.
- PCA is unsupervised: it ignores labels and need not keep the directions that separate the classes3. Its components are nested: the first component is the same whether you keep 1 or 4.
whiten=Truerescales each score to unit variance, so after whitening all components have the same variance2.- Related linear methods1: Truncated SVD skips centring and works on sparse term–document matrices, which is latent semantic analysis (LSA). In , a row of gives a document's topic weights and a row of a topic's word weights. NMF factorises non-negative data into non-negative, additive parts; its components are fitted jointly, so unlike PCA's they can all change when you change how many you keep. Factor analysis allows a different noise variance per feature; ICA separates independent non-Gaussian sources after whitening.
- Non-linear methods: kernel PCA (PCA with the kernel trick), Isomap (geodesic distances on a neighbourhood graph), t-SNE and UMAP for visualisation1,4. A linear autoencoder with a -unit bottleneck trained on squared error spans the same subspace as the top principal components, but its weights need not be orthogonal6.
- t-SNE matches neighbour distributions. Its perplexity is roughly the number of close neighbours each point has (typical 5–50); low values emphasise local structure5. Run it until the layout is stable. Cluster sizes and gaps between clusters in the plot carry little meaning, and pure noise can look clustered at low perplexity5. Use it to look, not to cluster4.
Formulas
- Centred data (), covariance . Explained-variance ratio of component : 3.
- SVD : the columns of are the principal axes and , so variance ratios can be computed from squared singular values2,3.
- Scores with the matrix of axes (scikit-learn's
components_, shape(n_components, n_features)); reconstruction (plus the mean)2. - Best rank- approximation error: 3.
- A covariance matrix is symmetric positive semi-definite, so it always has real eigenvalues and an orthonormal eigenbasis. Perfectly collinear features give an eigenvalue of 0: one component carries no variance.
Worked example
Centred 2-D data with covariance .
- , so , ; PC1 explains of the variance.
- gives , and .
- Point : score ; rank-1 reconstruction ; squared error , the part along PC2.
In code
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(0)
X = rng.multivariate_normal([0, 0], [[5, 2], [2, 2]], size=500)
pca = PCA().fit(X)
print(pca.components_.round(2)) # [[ 0.9 0.44] [-0.44 0.9 ]] rows = axes
print(pca.explained_variance_.round(2)) # [5.83 0.94]
print(np.linalg.eigvalsh(np.cov(X.T))[::-1].round(2)) # [5.83 0.94] covariance eigenvalues
print((pca.singular_values_**2 / (len(X) - 1)).round(2)) # [5.83 0.94] sigma^2 / (n - 1)
print(pca.explained_variance_ratio_.round(3)) # [0.861 0.139]
The sample estimates are close to the exact values , 6 and 1.
Common pitfalls
- PCA without centring is not PCA; on raw features with different units, PC1 just follows the feature with the largest numbers.
- A principal component is a direction (a mix of all features), not the original feature with the largest variance.
- PCA does not assume uncorrelated inputs; it exploits correlation and outputs uncorrelated scores. Collinear features do not make it fail.
- Keeping as many components as possible defeats the purpose; pick from the explained-variance curve.
- PCA is not regression: it minimises perpendicular distances to a subspace and treats all features alike, with no target.
- In a t-SNE plot, do not read cluster sizes or distances between clusters as real quantities5.
References
- scikit-learn User Guide: Decomposing signals in components — Sec. 2.5.1 PCA; 2.5.2 Kernel PCA; 2.5.3 Truncated SVD and latent semantic analysis; 2.5.5 Factor Analysis; 2.5.6 ICA; 2.5.7 NMF
- scikit-learn API: sklearn.decomposition.PCA — Parameters n_components, whiten; attributes components_, explained_variance_, explained_variance_ratio_, singular_values_
- Wikipedia: Principal component analysis — Overview; Intuition (scree plot); Details (First component, Covariances, Dimensionality reduction, Singular value decomposition); Further considerations; Properties and limitations; Computation using the covariance method (cumulative energy)
- Wikipedia: Dimensionality reduction — Introduction; Feature selection; Feature projection (Kernel PCA, Graph-based kernel PCA, t-SNE, UMAP)
- Wattenberg, Viégas & Johnson, How to Use t-SNE Effectively (Distill, 2016) — Sections 1–4 (hyperparameters, cluster sizes, distances between clusters, random noise)
- Wikipedia: Autoencoder — Applications — Dimensionality reduction — Principal component analysis