Dimensionality reduction
About this lesson
Every feature in a data set is a dimension, and many features say almost the same thing. Dimensionality reduction keeps most of the information with fewer numbers. Watch principal component analysis (PCA) work on six students' maths and physics scores: centre the data, turn a line until the points are most spread out along it, and replace two numbers per student with one, keeping 95% of the variance.
Features are dimensions
Each student is a row of data with two features: a maths score and a physics score, out of 10. Two features means two dimensions, so each student is a point on a flat chart. Real data often has hundreds.
student maths physics A 3 4 B 5 4 C 6 5 D 6 7 E 7 7 F 9 9 features = columns; 2 features = 2 dimensions
Read the lesson step by step
Features are dimensions
Each student is a row of data with two features: a maths score and a physics score, out of 10. Two features means two dimensions, so each student is a point on a flat chart. Real data often has hundreds.
student maths physics A 3 4 B 5 4 C 6 5 D 6 7 E 7 7 F 9 9 features = columns; 2 features = 2 dimensionsTwo numbers, one story
The scores rise together: good at maths usually means good at physics. The points hug a slanted line. Dimensionality reduction keeps most of the information with fewer features: here, one number per student instead of two.
maths up -> physics up (mostly) the points lie close to one slanted line goal: describe each student with 1 number, not 2, and lose as little as possibleCentre the data
Principal component analysis (PCA) is the classic method. Step one: subtract the mean. The average student scored 6 and 6, so student A's (3, 4) becomes (−3, −2). Now every point is measured from the centre, the cross.
Xc = X - X.mean(axis=0) mean = (6, 6) A (3, 4) - (6, 6) = (−3, −2) B (5, 4) - (6, 6) = (−1, −2) C (6, 5) - (6, 6) = (0, −1) D (6, 7) - (6, 6) = (0, 1) E (7, 7) - (6, 6) = (1, 1) F (9, 9) - (6, 6) = (3, 3)Try every direction
Draw a line through the centre and drop each point onto it at a right angle. The variance (spread) of the landing spots depends on the angle: along the maths axis it is 4.0. Turning the line changes it.
variance = how spread out the landing spots are (mean squared distance from the centre; np.cov divides by n - 1) 0° variance 4.0 15° variance 5.8 30° variance 7.1 45° variance 7.6 60° variance 7.1 75° variance 5.8 90° variance 4.0The best line: PC1
At 45° the spread peaks at 7.6. The direction of greatest variance is the first principal component, PC1. It points along (0.71, 0.71): both scores up together, a kind of overall score.
C = np.cov(Xc.T) = [[4.0, 3.6], [3.6, 4.0]] eigenvalues 0.4, 7.6 (eigh: smallest first) PC1 = eigenvector of 7.6 = (0.71, 0.71) an eigenvector of C keeps its direction when multiplied by C; the largest one is PC1Project: one number each
Each student's new feature is where they land on PC1: z = 0.71 × maths + 0.71 × physics, both centred. Student A lands at −3.54. Two numbers became one.
z = Xc @ w A 0.71×−3 + 0.71×−2 = −3.54 B 0.71×−1 + 0.71×−2 = −2.12 C 0.71× 0 + 0.71×−1 = −0.71 D 0.71× 0 + 0.71× 1 = 0.71 E 0.71× 1 + 0.71× 1 = 1.41 F 0.71× 3 + 0.71× 3 = 4.24What we keep, what we lose
The leftover direction, at right angles, is PC2. Its variance is only 0.4: the short drop lines are all we throw away. PC1 keeps 7.6 of the total 8.0, that is 95% of the variance, with half the numbers.
total variance 4.0 + 4.0 = 8.0 PC1 7.6 (95%) PC2 0.4 (5%, dropped) kept = vals[-1] / vals.sum() = 7.6 / 8.0 = 0.95PCA in NumPy
The whole method is six lines: centre, build the covariance matrix, take its eigenvectors, keep the one with the largest eigenvalue, project. With hundreds of features you keep the top k eigenvectors instead of one.
Xc = X - X.mean(axis=0) C = np.cov(Xc.T) vals, vecs = np.linalg.eigh(C) w = vecs[:, -1] # PC1 z = Xc @ w kept = vals[-1] / vals.sum() prints w = [0.71 0.71] z = [-3.54 -2.12 -0.71 0.71 1.41 4.24] kept = 0.95 scikit-learn: PCA(n_components=1).fit_transform(X) gives the same z, up to its signWhy reduce, and the catch
Fewer features train faster, filter out noise and can be plotted: 64-pixel images of digits become dots on a 2D chart. The catch: scale features first when their units differ, and PCA only finds straight-line directions.
uses faster training, less noise, plots of high-dimensional data (8×8 digits: 64 -> 2) scale standardise each feature first if units differ (cm vs kg), or the big one wins limit PCA finds straight (linear) directions; curved structure needs other methods
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What is the first principal component (PC1) of a data set?
PCA turns a line through the mean and keeps the angle where the projected points have the largest variance. The direction with the least spread is the last component, the first one dropped.
02Why does PCA subtract the mean from every feature first?
The principal directions are lines through the mean. Centring moves the centre of the cloud to (0, 0), so the covariance matrix and the projections are measured from there.
03The covariance matrix has eigenvalues 7.6 and 0.4. What share of the variance does keeping only PC1 keep?
Each eigenvalue is the variance along its component. 7.6 / (7.6 + 0.4) = 7.6 / 8.0 = 0.95, so 95% is kept and the 5% along PC2 is dropped.
04A student's centred scores are (−1, −2) and PC1 is (0.71, 0.71). What is their PC1 score z?
z is the dot product with PC1: 0.71 × (−1) + 0.71 × (−2) = −2.12 (exactly −3 / √2). Two numbers have become one.
05One feature is a height in centimetres, another a weight in tonnes. What should you do before PCA?
PCA chases variance, so a feature measured in large numbers dominates just because of its units. Scaling first puts the features on an equal footing.
Glossary
- Dimension
- One feature of the data. A row with two numbers is a point in 2D; a row with 64 numbers is a point in 64 dimensions.
- Dimensionality reduction
- Describing each example with fewer features while keeping as much of the information as possible.
- Principal component analysis (PCA)
- A method that finds new directions (principal components) ordered by how much of the data's variance lies along each, then keeps the first few.
- Variance
- How spread out values are: the sum of squared distances from the mean divided by n − 1 (the sample variance, as numpy.cov computes it).
- Centring
- Subtracting each feature's mean, so the centre of the data sits at zero.
- Covariance matrix
- A table of how each pair of features varies together; its diagonal holds each feature's variance.
- Eigenvector, eigenvalue
- A direction that a matrix only stretches, and by how much. For a covariance matrix the eigenvectors are the principal components and the eigenvalues their variances.
- Projection
- Dropping a point onto a line at a right angle; its position along the line is its new single number.
Notes and sources
- The six students are invented for the lesson. Both scores have the same variance, so PC1 lies at exactly 45° and keeps exactly 95% of the variance; real data is rarely this tidy.
- Variance here is the sample variance, as numpy.cov computes it: the sum of squared distances from the mean divided by n − 1 (5 for six students).
- The line of greatest variance is also the line closest to the points: it makes the squared drop lines as short as possible, which is how Pearson first described it in 1901.
- An eigenvector can point either way; the program flips w so it points up and to the right, which flips the sign of every z.
- The NumPy program in the lesson is real: run it and it prints [0.71 0.71], the six PC1 scores and 0.95.
- K. Pearson, On lines and planes of closest fit to systems of points in space, Philosophical Magazine 2 (1901)
- H. Hotelling, Analysis of a complex of statistical variables into principal components, J. Educational Psychology 24 (1933)
- Stanford CS229 Machine Learning, lecture notes (A. Ng, T. Ma): principal components analysis
- Goodfellow, Bengio & Courville, Deep Learning (2016), section 2.12: Example: Principal Components Analysis
- I. T. Jolliffe & J. Cadima, Principal component analysis: a review and recent developments, Phil. Trans. R. Soc. A 374 (2016)
- NumPy reference: numpy.cov
- NumPy reference: numpy.linalg.eigh
- scikit-learn user guide: Principal component analysis (PCA)
- scikit-learn: Importance of feature scaling (PCA on unscaled and scaled data)
- scikit-learn: load_digits (1797 images, 8 × 8 = 64 features)
Quiz Unlocks after the last step.