Compute the best rank-k approximation of a matrix with a truncated SVD
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `low_rank(A, k)` returning the best rank-`k` approximation of the 2-D matrix `A` by truncating its SVD to the top `k` singular values.
Requirements:
- Compute `U, s, Vt = np.linalg.svd(A, full_matrices=False)`.
- Reconstruct as `(U[:, :k] * s[:k]) @ Vt[:k]`.
- Return a matrix of the same shape as `A`.
For example:
```python
A = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
low_rank(A, 1) # rank-1 approximation, shape (3, 3)
low_rank(A, 2) # A has rank 2 (row 3 = 2 * row 2 - row 1), so this recovers A up to rounding
low_rank(A, 3) # any k >= min(A.shape) also recovers A
```
```hint Why truncation is optimal
Think about which norms the truncated SVD is the best approximation in, and which theorem says so.
```
```hint Avoid a diagonal matrix
Look at how a 1-D array of length `k` broadcasts against an `m x k` array.
```
### What a Strong Answer Covers
- Why keeping the top `k` singular values and vectors gives the best rank-`k` approximation, and in which norms.
- How the economy SVD shapes line up and how broadcasting scales the columns of `U`.
- What happens for `k = 0`, for `k >= min(A.shape)` and for an invalid `k`.
- Time and space complexity, and what to use when `A` is large and `k` is small.
### Follow-up Questions
- What is the approximation error in the Frobenius and spectral norms, expressed through the singular values?
- How would you choose `k` for a given matrix, for example to keep 90% of the energy?
- How would you compute a rank-20 approximation of a 100,000 x 10,000 matrix?
- How does this computation relate to PCA?
Overview: Implement a NumPy function that returns the best rank-k approximation of a matrix by truncating its singular value decomposition. It tests understanding of the SVD and its optimality, broadcasting with the economy factors, edge cases for k, and the cost of the computation on large matrices.