Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs
Low-rank matrix approximation is a simple way to compress a matrix while keeping most of its information, often done using Singular Value Decomposition (SVD). Your task is to compute a rank-(k) approximation (A_k) of a given matrix (A) that minimizes reconstruction error. The Eckart-Young-Mirsky theorem states that the optimal rank- approximation in the Frobenius norm is given by the truncated SVD:
where and contain the first columns of and rows of (columns of ), and contains the top singular values.
Implement the function
Rules:
Output:
| Argument | Type |
|---|---|
| A | np.ndarray |
| k | int |
| Return Name | Type |
|---|---|
| value | np.ndarray |
Use NumPy only; no other libraries.
Return ndarray.
Use SVD with top-k components only.
Use np.linalg.svd(A, full_matrices=False) to get U, s, Vt where s is a 1D array of singular values.
Form the rank-k reconstruction via slicing: U[:, :k] @ np.diag(s[:k]) @ Vt[:k, :].