ENع
←Fewer dimensions
Lesson 11 · Classic machine learning

Dimensionality reduction

14 min9 steps5 questionsIntermediate
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 11 · Interactive
01 / 09

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. Two 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 possible
  3. Centre 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)
  4. 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.0
  5. The 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 PC1
  6. Project: 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.24
  7. What 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.95
  8. PCA 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 sign
  9. Why 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

Quiz Unlocks after the last step.