Sparse LSA via Truncated SVD

Quick Overview

Implement latent semantic analysis on a sparse document-term matrix by computing a truncated SVD without densifying it. Tests implicit linear operators, deterministic sign conventions, explained variance computed from sparse data, and the cost and accuracy of sparse eigen solvers.

Sparse LSA via Truncated SVD

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement an `LSA` class with `fit`, `transform`, `fit_transform` and `top_terms`. `fit(X)` computes the top `n_components` right singular vectors of an uncentered sparse document-term matrix without densifying it (no `toarray` or `todense`) and returns `self`. `transform(X)` returns the ndarray `X @ components_.T` for sparse or dense input. The class must meet these requirements: - Set `components_` (shape `(k, n_terms)`) and `singular_values_` (descending). - Sign convention: the largest-magnitude entry of each component is positive. - `explained_variance_` is the per-column variance of `transform(X)`. `explained_variance_ratio_` divides it by the summed column variances of `X`, matching scikit-learn's `TruncatedSVD`. - `top_terms(vocabulary, n_top)` returns, for each component, the `n_top` terms in descending order of signed loading, with stable ties. - A non-sparse `X` in `fit` raises `TypeError`. An `n_components` outside `[1, min(X.shape) - 1]` raises `ValueError`. For example: ```python import numpy as np import scipy.sparse as sp D = np.zeros((5, 6)) D[:3, :3] = np.outer([0.2, 0.1, 0.3], [3, 2, 1]) # fruit topic D[3:, 3:] = np.outer([0.1, 0.05], [1, 2, 4]) # car topic vocab = ["apple", "banana", "fruit", "car", "engine", "wheel"] lsa = LSA(2).fit(sp.csr_matrix(D)) lsa.singular_values_ # [1.4, sqrt(0.2625)] ≈ [1.4, 0.5123] lsa.top_terms(vocab, 2) # [["apple", "banana"], ["wheel", "engine"]] ``` ```hint Work through products only Find an eigenproblem whose eigenvectors are the right singular vectors of `X`, then apply its matrix to a vector using only sparse matrix-vector products. ``` ```hint Determinism Check the order in which a sparse eigen solver returns its eigenpairs, and remember that it starts from a random vector unless you pass one. ``` ### Constraints & Assumptions - `X` is a `scipy.sparse` matrix of non-negative floats. - Results must match a dense SVD to `rtol=1e-6`: the singular values directly, and the components after the same sign convention is applied to the dense result. - `len(vocabulary) == n_terms`. ### What a Strong Answer Covers - How the singular vectors and singular values come out of sparse products alone, and why that is equivalent to an SVD of `X`. - Deterministic output: eigenpair ordering, a fixed starting vector and the sign convention. - Explained variance and its ratio computed without densifying, using the same definitions as `TruncatedSVD`. - Input validation and the stable tie rule in `top_terms`. - The cost in terms of `nnz`, `k` and the number of iterations, and the accuracy cost of working with `X^T X`. ### Follow-up Questions - How would you scale this to millions of documents? - Why not mean-center the TF-IDF matrix as PCA would? - How would you rank documents against a query in the latent space?

Overview: Implement latent semantic analysis on a sparse document-term matrix by computing a truncated SVD without densifying it. Tests implicit linear operators, deterministic sign conventions, explained variance computed from sparse data, and the cost and accuracy of sparse eigen solvers.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement an LSA class with fit, transform, fit_transform and top_terms. fit(X) computes the top n_components right singular vectors of an uncentered sparse document-term matrix without densifying it (no toarray or todense) and returns self. transform(X) returns the ndarray X @ components_.T for sparse or dense input.

The class must meet these requirements:

  • Set components_ (shape (k, n_terms) ) and singular_values_ (descending).
  • Sign convention: the largest-magnitude entry of each component is positive.
  • explained_variance_ is the per-column variance of transform(X) . explained_variance_ratio_ divides it by the summed column variances of X , matching scikit-learn's TruncatedSVD .
  • top_terms(vocabulary, n_top) returns, for each component, the n_top terms in descending order of signed loading, with stable ties.
  • A non-sparse X in fit raises TypeError . An n_components outside [1, min(X.shape) - 1] raises ValueError .

For example:

import numpy as np
import scipy.sparse as sp

D = np.zeros((5, 6))
D[:3, :3] = np.outer([0.2, 0.1, 0.3], [3, 2, 1])   # fruit topic
D[3:, 3:] = np.outer([0.1, 0.05], [1, 2, 4])       # car topic
vocab = ["apple", "banana", "fruit", "car", "engine", "wheel"]
lsa = LSA(2).fit(sp.csr_matrix(D))
lsa.singular_values_      # [1.4, sqrt(0.2625)] ≈ [1.4, 0.5123]
lsa.top_terms(vocab, 2)   # [["apple", "banana"], ["wheel", "engine"]]

Constraints & Assumptions

  • X is a scipy.sparse matrix of non-negative floats.
  • Results must match a dense SVD to rtol=1e-6 : the singular values directly, and the components after the same sign convention is applied to the dense result.
  • len(vocabulary) == n_terms .

What a Strong Answer Covers Guidance

  • How the singular vectors and singular values come out of sparse products alone, and why that is equivalent to an SVD of X .
  • Deterministic output: eigenpair ordering, a fixed starting vector and the sign convention.
  • Explained variance and its ratio computed without densifying, using the same definitions as TruncatedSVD .
  • Input validation and the stable tie rule in top_terms .
  • The cost in terms of nnz , k and the number of iterations, and the accuracy cost of working with X^T X .

Follow-up Questions Guidance

  • How would you scale this to millions of documents?
  • Why not mean-center the TF-IDF matrix as PCA would?
  • How would you rank documents against a query in the latent space?