Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

102. Low rank matrix approximation

easy
GeneralGeneral
senior

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-kk approximation in the Frobenius norm is given by the truncated SVD:

Ak=∑i=1kσiuiviT=UkΣkVkTA_k = \sum_{i=1}^k \sigma_i u_i v_i^T = U_k \Sigma_k V_k^T

where UkU_k and VkV_k contain the first kk columns of UU and rows of VTV^T (columns of VV), and Σk\Sigma_k contains the top kk singular values.

Requirements

Implement the function

python

Rules:

  • Use SVD to approximate (A) as (A \approx U \Sigma V^\top), then keep only the top (k) singular values/vectors.
  • Return (A_k) as a NumPy array.
  • Do not use any helper libraries beyond NumPy and Python built-ins.

Example

python

Output:

python
Input Signature
ArgumentType
Anp.ndarray
kint
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Use NumPy only; no other libraries.

  • Return ndarray.

  • Use SVD with top-k components only.

Hint 1

Use np.linalg.svd(A, full_matrices=False) to get U, s, Vt where s is a 1D array of singular values.

Hint 2

Form the rank-k reconstruction via slicing: U[:, :k] @ np.diag(s[:k]) @ Vt[:k, :].

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
svd
low-rank-approximation
numpy-linear-algebra
matrix-reconstruction
35 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit