Implement PCA From Scratch in R Using SVD
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement principal component analysis in base R without `prcomp()`. Center and scale a numeric dataset, run `svd()`, and provide variance explained, projection of new rows, and reconstruction from the first `k` components. Define exactly the four functions below.
`pca_fit(X, center = TRUE, scale = TRUE)` accepts a numeric matrix or an all-numeric data.frame. Scaling uses the sample standard deviation (denominator `n - 1`) of the centered data. It returns a named list with:
- `sdev`: the singular values divided by `sqrt(n - 1)`.
- `rotation`: a `p x p` matrix with columns `PC1..PCp` and rows named after the columns of `X`. In each column the entry with the largest absolute value is positive (flip the column if needed).
- `center` and `scale`: the named numeric vectors that were used (zeros when `center = FALSE`, ones when `scale = FALSE`).
- `scores`: the `n x p` matrix of the centered and scaled `X %*% rotation`, with columns `PC1..PCp` and rows named after the rows of `X`.
`pca_variance_explained(fit)` returns a data.frame (`stringsAsFactors = FALSE`) with columns `PC`, `variance`, `prop_variance` and `cumulative`.
`pca_project(fit, newdata)` returns the scores of `newdata` using `fit$center`, `fit$scale` and `fit$rotation`.
`pca_reconstruct(fit, k)` returns an `n x p` matrix on the original scale built from the first `k` components, with the scaling and centering undone.
Row and column names must be preserved in `scores`, `rotation`, `center` and `scale`.
For example:
```r
fit <- pca_fit(mtcars) # center = scale = TRUE
fit$sdev # length p, decreasing
dim(fit$rotation) # p x p, columns PC1..PCp
pca_variance_explained(fit)
# PC variance prop_variance cumulative
# 1 PC1 6.608 0.601 0.601
# 2 PC2 2.650 0.241 0.842
# ...
pca_project(fit, mtcars[1:3, ]) # 3 x p scores
pca_reconstruct(fit, k = 2) # n x p, original scale
```
```hint Reading the SVD
Write the processed matrix as $U D V^T$ and decide which factor holds the loadings, which product gives the scores, and how $d$ relates to the variance along each direction.
```
```hint Signs and order
A sign flip has to reach every output that depends on that component. For reconstruction, undo the preprocessing steps in the reverse order you applied them.
```
### Constraints & Assumptions
- Base R only; `prcomp()` and `princomp()` are not allowed.
- `X` is a numeric matrix or an all-numeric data.frame with `n` rows and `p` columns.
- `newdata` has the same columns in the same order as the fitted `X`.
### What a Strong Answer Covers
- Preprocessing that matches the spec: column means, sample standard deviation with `n - 1` on the centered data, and the stored `center` and `scale` vectors when either step is switched off.
- The mapping from `svd()` output to `sdev`, `rotation` and `scores`, including the `sqrt(n - 1)` divisor.
- A deterministic sign rule applied consistently to loadings and scores.
- Projection and reconstruction that reuse the fitted parameters and undo them in the right order, with names preserved on every output.
- Behaviour on edge cases such as constant columns, `k = 1`, and data with more columns than rows.
### Follow-up Questions
- Why apply a deterministic sign convention to `rotation`?
- How would you handle a matrix with more columns than rows (`p > n`)?
- How would you test your implementation against `prcomp()`?
Overview: Implement principal component analysis in base R with svd() instead of prcomp(), covering centering, sample-sd scaling, variance explained, projection of new rows and reconstruction from the first k components. Tests the link between SVD and PCA, sign conventions, naming and numerical edge cases.