PCA by Power Iteration
Centre a two-dimensional cloud, build its covariance matrix and repeatedly multiply a direction. The final unit vector points along the greatest variance; choose a consistent sign.
import math
vector = [2, 2]
norm = math.hypot(*vector)
print([x/norm for x in vector])From arithmetic to an experiment
Centre a two-dimensional cloud, build its covariance matrix and repeatedly multiply a direction. The final unit vector points along the greatest variance; choose a consistent sign. The trace reads the local variables of your function as it executes. Change one input or parameter, predict the result, then run the checks again. A small deterministic example makes arithmetic mistakes easier to locate than a long training run. State the shape and meaning of the returned value before coding. Keep preprocessing, evaluation and model updates in their proper order, and examine the boundary case in each check. The companion lab lets you replay intermediate values while the same algorithm runs.
Your task
principal_axis(points, steps) returns the first principal unit direction for 2D points using power iteration starting at (1,1)/sqrt(2). Centre points, use population covariance, take steps iterations; fall back to the covariance column with the greatest norm if the starting direction is orthogonal; return (0,0) for zero variance and orient x >= 0. Inputs are nonempty.
The explanation opens here once every check passes.