PCA
📐 What is PCA? Principal component analysis finds the directions along which a dataset varies most. The first component is the unit vector that, when you project the centered data onto it, gives the largest variance; each next one does the same while staying orthogonal to the ones before. Keeping the top
kdirections compresses the data with the least squared reconstruction error anyk-dimensional linear projection can achieve.
It comes up in from-scratch classic-ML rounds as a linear algebra check: the interviewer wants to see that you center, pick the right decomposition and can say what the eigenvalues mean.
The Prompt
PCA is three lines with a library call, so the interviewer listens for the details: centering, which decomposition, sorting, signs, and what "explained variance" is.
"Implement PCA. Given an
(n, d)data matrix andk, return the topkcomponents, how much variance each explains, and a function that projects new data."
Clarifying Questions
You: May I use np.linalg? And should the components come out as rows or columns?
Interviewer: Yes to np.linalg. Rows: a (k, d) array.
You: Do I standardize the features, or only center them?
Interviewer: Only center. Tell me when you'd standardize.
You: Variance with n - 1 or n in the denominator?
Interviewer: n - 1.
You: Components are only defined up to sign. Is any sign fine, or should I make them deterministic?
Interviewer: Make them deterministic so the tests are stable.
What You'll Build
pca_eig(X, k) -> (components, explained_variance): via the covariance matrix;(k, d)and(k,).pca_svd(X, k) -> (components, explained_variance): via the SVD of the centered data.transform(X, mean, components) -> (m, k)andinverse_transform(Z, mean, components) -> (m, d).explained_variance_ratio(X, explained_variance) -> (k,): each component's share of the total variance.