LDA and Random Projection
PCA keeps the directions of largest variance and never looks at the label. Two other linear reductions make different trade-offs. Linear Discriminant Analysis (LDA) uses the label and keeps the directions that best separate the classes. Random projection uses nothing at all, not even the data's variance: it multiplies by a random matrix, and a theorem guarantees that distances survive. One is the most informed reduction, the other the cheapest.
When the label hides in a low-variance direction
Imagine two classes stretched along a long axis but separated along a short one. PCA keeps the long axis, because that is where the variance is, and throws the separation away. LDA keeps the short one.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
rng = np.random.default_rng(0)
n = 200
long_axis = rng.normal(0, 5, 2 * n) # big spread, no class information
y = np.repeat([0, 1], n)
short_axis = rng.normal(0, 0.5, 2 * n) + np.where(y == 1, 1.5, -1.5)
X = np.column_stack([long_axis, short_axis])
def separation(z, y):
"""Distance between class means in units of the pooled standard deviation."""
a, b = z[y == 0], z[y == 1]
return abs(a.mean() - b.mean()) / np.sqrt((a.var() + b.var()) / 2)
z_pca = PCA(n_components=1).fit_transform(X).ravel()
z_lda = LinearDiscriminantAnalysis(n_components=1).fit_transform(X, y).ravel()
print(f"PCA 1-D: class separation {separation(z_pca, y):.2f}")
print(f"LDA 1-D: class separation {separation(z_lda, y):.2f}")PCA 1-D: class separation 0.11
LDA 1-D: class separation 5.96
On the 1-D PCA axis the class means are only 0.11 pooled standard deviations apart: the classes overlap completely. On the 1-D LDA axis they are 5.96 apart, almost perfectly separated. Same data, same number of dimensions kept; the difference is whether the method looked at the label.
LDA: the definitions
For classes with means , rows each and overall mean , define the within-class scatter (how spread each class is) and the between-class scatter (how far apart the class means are):
LDA looks for directions that maximise the ratio
The solutions are the leading eigenvectors of . Because is built from class means, its rank is at most , so LDA gives at most components: one for a binary problem, two for the three wine cultivars. Here is the computation by hand, compared with scikit-learn:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
X, y = load_wine(return_X_y=True)
X = (X - X.mean(0)) / X.std(0)
mu = X.mean(0)
Sw = np.zeros((13, 13)); Sb = np.zeros((13, 13))
for c in np.unique(y):
Xc = X[y == c]
d = Xc - Xc.mean(0)
Sw += d.T @ d
m = (Xc.mean(0) - mu)[:, None]
Sb += len(Xc) * (m @ m.T)
vals, vecs = np.linalg.eig(np.linalg.solve(Sw, Sb))
order = np.argsort(vals.real)[::-1]
vals = vals.real[order]
print("eigenvalues of Sw^-1 Sb:", np.round(vals[:2], 3).tolist(), "the rest ~0:", bool(np.abs(vals[2:]).max() < 1e-8))
print("share of discriminative power:", np.round(vals[:2] / vals[:2].sum(), 3).tolist())
lda = LinearDiscriminantAnalysis(n_components=2).fit(X, y)
print("sklearn explained_variance_ratio_:", np.round(lda.explained_variance_ratio_, 3).tolist())eigenvalues of Sw^-1 Sb: [9.082, 4.128] the rest ~0: True
share of discriminative power: [0.687, 0.313]
sklearn explained_variance_ratio_: [0.687, 0.313]
The 13 standardised wine features reduce to two discriminant directions with eigenvalues 9.082 and 4.128; all the others are zero, as the rank argument predicts. The first direction carries 68.7% of the separating power, the same ratio scikit-learn reports as explained_variance_ratio_ (for LDA it means a share of the between-class separation, not of the total variance).
Note: LDA is fitted with the labels, so it is a supervised step and must be fitted on training data only, inside the pipeline. Fitted on all data, it finds directions that separate the test rows too, and cross-validation becomes optimistic, especially with many features and few rows.
Random projection
Sometimes the data is so wide (a million hashed text features, a long sensor vector) that even computing PCA is too expensive. Random projection multiplies by a random matrix : . The Johnson–Lindenstrauss lemma says that for any points and any , a random projection to
dimensions keeps every pairwise distance within a factor with high probability. The bound depends on the number of points , not on the original dimension . scikit-learn's johnson_lindenstrauss_min_dim computes it; GaussianRandomProjection draws from , and SparseRandomProjection uses mostly zeros, which is faster.
import numpy as np
from sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection
from sklearn.metrics import pairwise_distances
for eps in [0.5, 0.3, 0.1]:
print(f"n=300, eps={eps}: k >= {int(johnson_lindenstrauss_min_dim(300, eps=eps))}")
rng = np.random.default_rng(0)
X = rng.normal(size=(300, 3000)) # 300 points in 3,000 dimensions
D = pairwise_distances(X)
iu = np.triu_indices(300, 1)
# From scratch: a Gaussian matrix scaled by 1/sqrt(k)
for k in [50, 300, 1000]:
R = rng.normal(0, 1 / np.sqrt(k), size=(3000, k))
ratio = pairwise_distances(X @ R)[iu] / D[iu]
print(f"k={k:>4}: distance ratio min {ratio.min():.3f}, max {ratio.max():.3f}")
Z = SparseRandomProjection(n_components=300, random_state=0).fit_transform(X)
ratio = pairwise_distances(Z)[iu] / D[iu]
print(f"sklearn sparse, k=300: min {ratio.min():.3f}, max {ratio.max():.3f}")n=300, eps=0.5: k >= 273
n=300, eps=0.3: k >= 633
n=300, eps=0.1: k >= 4888
k= 50: distance ratio min 0.629, max 1.380
k= 300: distance ratio min 0.809, max 1.158
k=1000: distance ratio min 0.909, max 1.098
sklearn sparse, k=300: min 0.850, max 1.170
The bound is demanding: for 300 points it asks for 273 dimensions at , 633 at 0.3 and 4,888 at 0.1. It is also a worst-case guarantee, and in practice the distortion is smaller. With 300 points in 3,000 dimensions, 50 random dimensions already keep every one of the 44,850 pairwise distances between 0.63 and 1.38 times its true value, 300 dimensions between 0.81 and 1.16, and 1,000 between 0.91 and 1.10. The sparse version does as well as the Gaussian one at (0.85 to 1.17) and is much cheaper to apply. Distance-based models (kNN, clustering, SVM with an RBF kernel) work on the projected data almost as on the original.
Which linear reduction?
| Method | Uses the label | Number of components | Best for |
|---|---|---|---|
| PCA | no | up to | compression, denoising, correlated dense features |
| Truncated SVD | no | chosen | sparse matrices (text) |
| LDA | yes | at most | classification with few classes, a supervised 2-D view |
| Random projection | no | from the JL bound | very wide data, speed, privacy-preserving sketches |
Pitfalls
- LDA fitted on all rows: it saw the test labels. Put it in a pipeline.
- Too many features for LDA: with more features than rows, is singular. Use
solver="eigen", shrinkage="auto"or reduce with PCA first. - LDA's assumptions: it is optimal for Gaussian classes with a shared covariance. Curved or multi-modal classes need non-linear methods.
- Random projection on small : the JL bound is often larger than the original dimension (it is for points at : 4,888); then there is nothing to gain.
Practice
- A problem has 4 classes and 50 features. How many LDA components can you get?
Answer
At most , because the between-class scatter matrix is built from 4 class means and has rank at most 3.
- You need distances among 10,000 documents preserved within 20%. How does the needed change if the vocabulary grows from 50,000 to 5,000,000 words?
Answer
It does not change. The JL bound depends on the number of points and on , not on the original dimension .
Test yourself
What does LDA maximise?
- The total variance
- The ratio of between-class scatter to within-class scatter
- The number of components
- The reconstruction error
Why can PCA throw away the direction that separates the classes?
- PCA uses the label in the wrong way
- PCA keeps high-variance directions, and the separating direction may have low variance
- PCA only works on two classes
- PCA always keeps all directions
The Johnson-Lindenstrauss bound on depends on …
- the original dimension only
- the number of points and the tolerance
- the class labels
- the eigenvalues of the data
Why must LDA be fitted inside the cross-validation pipeline?
- It is slow
- It uses the labels, so fitting it on all rows leaks test labels into the features
- It needs scaled data
- It cannot transform test data