Paul's Python CoursePPC

Principal component analysis

Not met yet

PCA finds the directions a set of readings spreads along, biggest first, so many readings can be squashed into a few numbers. Centre each column, work out the covariance matrix, and find its eigenvectors: those are the principal components, new directions that mix the original readings. Each eigenvalue's share of the total says how much of the spread its component explains. Squash with (X - means) @ components[:, :k]; rebuild with Z @ components[:, :k].T + means, which loses only what the other components held. Like k-means, it learns from the readings alone, with no answers.

Try it

main.py
import numpy as np

X = np.array([[2.0, 4.1], [3.0, 5.9], [4.0, 8.2], [5.0, 9.8]])
means = X.mean(axis=0)
centred = X - means
values, vectors = np.linalg.eigh(centred.T @ centred / (len(X) - 1))
order = np.argsort(values)[::-1]
values, vectors = values[order], vectors[:, order]
print(np.round(values / values.sum(), 3))
print(np.round(centred @ vectors[:, :1], 2).ravel())

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks PCA can work on the readings as they are, without taking off each column's mean first.
  • Thinks PCA chooses the most important of the original readings, rather than new directions that mix them.
  • Thinks readings rebuilt from fewer components than columns come back exactly.
  • Thinks PCA needs answers or labels to find its directions.

Where it comes up