MLCrack

    ML MATH & LINEAR ALGEBRA ยท INTERVIEW QUESTION

    Explain the role of SVD in PCA. How does truncated SVD relate to dimensionality reduction?

    ๐ŸŸก intermediate ยท Linear Algebra

    Hint: Consider the relationship between the covariance matrix eigenvectors and the right singular vectors.

    Answer

    PCA finds principal components by computing eigenvectors of the sample covariance matrix XโŠคX/(nโˆ’1)X^\top X/(n-1) (for mean-centered data). For mean-centered data, SVD decomposes X=UฮฃVโŠคX = U\Sigma V^\top directly.

    For mean-centered data, truncated SVD recovers the same principal subspace as PCA. The practical difference is centering: scikit-learn's PCA centers the data, while TruncatedSVD does not. That makes TruncatedSVD suitable for sparse matrices, but it is not identical to PCA unless you center the input first.

    • Columns of VV are the principal components
    • ฮฃ2/(nโˆ’1)\Sigma^2 / (n-1) gives eigenvalues of the covariance matrix
    • UฮฃU\Sigma gives the projected data

    Truncated SVD keeps only the top-kk singular values/vectors, giving the best rank-k approximation (Eckart-Young theorem):

    Xk=UkฮฃkVkโŠคX_k = U_k \Sigma_k V_k^\top

    Worked example

    Take the centered matrix

    X=[โˆ’100010].X = \begin{bmatrix} -1 & 0 \\ 0 & 0 \\ 1 & 0 \end{bmatrix}.

    Its singular values are ฯƒ1=2\sigma_1 = \sqrt{2} and ฯƒ2=0\sigma_2 = 0. The first right singular vector is the xx-axis, so keeping k=1k=1 projects every row onto that axis. The rank-1 reconstruction is

    X1=U1ฯƒ1V1โŠค=[โˆ’101][10]=[โˆ’100010],X_1 = U_1 \sigma_1 V_1^\top = \begin{bmatrix} -1 \\ 0 \\ 1 \end{bmatrix} \begin{bmatrix} 1 & 0 \end{bmatrix} = \begin{bmatrix} -1 & 0 \\ 0 & 0 \\ 1 & 0 \end{bmatrix},

    which keeps the dominant horizontal variation and discards no information because this centered example already has rank one.

    python
    import numpy as np from sklearn.decomposition import TruncatedSVD X = np.array([[-1., 0.], [0., 0.], [1., 0.]]) # TruncatedSVD does not center; center first for PCA equivalence. X_centered = X - X.mean(axis=0) svd = TruncatedSVD(n_components=1) X_reduced = svd.fit_transform(X_centered) print(f'Explained variance: {svd.explained_variance_ratio_.sum():.2%}')