Machine LearningLinear Algebra & Dimensionality Reduction
What is Singular Value Decomposition (SVD), and where is it used in machine learning?
Question 278 of 303 · Updated
On this page
- 1. The core idea
- 2. A beginner-friendly numerical example
- 3. What do U, Sigma, and V mean intuitively?
- 4. Truncated SVD and low-rank approximation
- 5. SVD and PCA: how are they related?
- 6. Important machine-learning applications
- A. Dimensionality reduction
- B. Text mining and Latent Semantic Analysis (LSA)
- C. Recommender systems
- D. Image compression and denoising
- E. Least-squares problems and pseudoinverses
- F. Rank deficiency and collinearity diagnostics
- 7. Full, compact, and truncated SVD
- 8. How do you choose the number of components?
- 9. SVD versus eigendecomposition
- 10. Practical Python example
- 11. Assumptions, limitations, and trade-offs
- 12. Leakage-safe use in production ML
- 13. Common interview questions
- Key takeaway
Singular Value Decomposition (SVD) is a general-purpose matrix factorization technique. It expresses a matrix as the product of three structured matrices, exposing the strongest directions or patterns in the data. SVD is widely used for dimensionality reduction, low-rank approximation, text mining, recommendation systems, image compression, denoising, and least-squares problems.
1. The core idea#
For any real matrix with rows and columns, SVD gives
where:
- U contains the left singular vectors. Its columns are orthonormal directions in the output/row space.
- Σ (Sigma) is a diagonal or rectangular-diagonal matrix containing non-negative singular values, ordered from largest to smallest.
- V contains the right singular vectors. Its columns are orthonormal directions in the input/feature space.
- is the transpose of V. For complex matrices, use the conjugate transpose.
SVD works for rectangular, square, tall, wide, singular, and rank-deficient matrices. The matrix does not need to be invertible.
A compact form keeps only the non-zero singular triplets:
where . Each triplet consists of a left vector , singular value , and right vector .
2. A beginner-friendly numerical example#
Consider
The first column is , while the second is zero. There is only one independent direction, so the matrix has rank one.
One valid decomposition is
Multiplying them gives
The singular values are 5 and 0. The value 5 describes the strength of the only non-zero direction. The zero singular value tells us that there is no second independent direction in this matrix.
Remember: singular values are always non-negative. In exact arithmetic, the number of non-zero singular values equals the matrix rank.
3. What do U, Sigma, and V mean intuitively?#
Think of SVD as three operations:
- rotates or changes coordinates into orthogonal directions in the feature space.
- stretches or shrinks each direction according to its singular value.
- maps the result into the output space.
SVD can also be written as a sum of rank-one matrices:
Each term is one pattern contributing to the original matrix. The largest singular value corresponds to the strongest pattern. Smaller singular values represent progressively weaker directions.
For example, if the singular values are 12, 5, and 1, the first direction is much stronger than the third. However, a small singular value is not automatically noise; its importance depends on the application and validation results.
4. Truncated SVD and low-rank approximation#
A common goal is to keep only the largest singular values and their corresponding vectors:
This is called truncated SVD. The result has rank at most and approximates the original matrix with fewer dimensions.
The Eckart–Young theorem establishes that this is a best rank- approximation under both the Frobenius norm and spectral norm.
A small numerical example: suppose a matrix has singular values
The total squared Frobenius energy is
Keeping the first two directions retains
of the squared matrix energy. The discarded squared energy is 1, about 0.85%.
This is useful for compression and reconstruction. It does not mean 99.15% of predictive information is retained. A low-variance direction may still be important for predicting a target or identifying a rare event.
The reconstruction error is
This makes the cost of discarding singular directions measurable.
5. SVD and PCA: how are they related?#
SVD and Principal Component Analysis (PCA) are closely connected, but they are not identical concepts.
Let be a data matrix with observations in rows and numerical features in columns. First subtract each feature's training-set mean to obtain the centered matrix . Its SVD is
The columns of are the principal-component directions, and the component scores are
The sample covariance matrix is
Its eigenvectors are the right singular vectors in , and its eigenvalues are
So singular values of the centered data matrix determine the variance explained by PCA components.
Many PCA implementations use SVD directly rather than explicitly constructing and decomposing the covariance matrix. This is often numerically preferable, particularly for highly correlated or ill-conditioned features.
Key distinction:
- PCA normally centers data.
- Whether features should also be standardized depends on their units and the meaning of their variances.
- Truncated SVD commonly operates without centering, which is useful for sparse matrices.
6. Important machine-learning applications#
A. Dimensionality reduction#
A dataset with hundreds or thousands of correlated features can often be represented with fewer latent dimensions. For example, 500 numerical features might be projected onto 40 dominant singular directions.
This can reduce memory use and downstream computation. Always validate whether the reduced representation preserves what the task needs.
B. Text mining and Latent Semantic Analysis (LSA)#
A document-term matrix contains word counts or weights for documents. It is typically high-dimensional and sparse.
Truncated SVD can compress it into a lower-dimensional latent representation. Words that occur in similar document contexts can contribute to related latent directions, helping represent semantic structure beyond exact word matching.
In scikit-learn, TruncatedSVD is commonly used for LSA. Unlike ordinary centered PCA, it can work with sparse matrices without centering them first.
C. Recommender systems#
Imagine a user-item matrix in which rows are users, columns are products or movies, and entries represent ratings or interactions.
A low-rank factorization approximates it as
The latent factors can capture patterns in user preferences and item characteristics. A recommendation system can use these factors to estimate likely user-item preferences.
Missing-value warning: an unobserved rating is not automatically a zero rating. Classical SVD expects a complete matrix of values. A real recommender must use an appropriate missing-data strategy or a factorization method that optimizes only observed interactions. Blindly filling every missing rating with zero can create bias.
D. Image compression and denoising#
A grayscale image is a matrix of pixel intensities. Truncated SVD approximates it using fewer rank-one patterns.
A 1000 × 1000 image contains 1,000,000 matrix values. A rank-50 representation stores approximately
values, ignoring file-format overhead. That is roughly one tenth as many values.
The compressed image may look similar, but fine details can disappear. Denoising may occur if small singular directions mostly represent noise, but this is not guaranteed.
E. Least-squares problems and pseudoinverses#
SVD is useful when solving
A rectangular or rank-deficient matrix may not have an ordinary inverse. SVD can construct the Moore–Penrose pseudoinverse:
where non-zero singular values are inverted. Zero or very small values are treated using a numerical tolerance.
A least-squares solution can then be expressed as
Inverting very small singular values can amplify noise, so numerical implementations use tolerances or regularization.
F. Rank deficiency and collinearity diagnostics#
Very small singular values can indicate redundant columns, near-linear dependence, or an ill-conditioned matrix. This helps diagnose unstable least-squares systems and feature redundancy.
7. Full, compact, and truncated SVD#
- Full SVD: returns complete orthogonal factors, including extra directions needed to form full-sized orthogonal matrices.
- Compact/economy SVD: removes unnecessary extra rows or columns while retaining the singular triplets needed to represent the matrix.
- Truncated/partial SVD: computes only a selected subset, often the largest singular values and vectors.
For large sparse matrices where only a few dominant directions are needed, truncated or randomized algorithms can be much more practical than computing a full decomposition.
8. How do you choose the number of components?#
There is no universal best value of . Consider:
- Cumulative squared singular-value energy: calculate . This is useful for compression and reconstruction.
- Singular-value plot: look for a sharp drop or elbow. It is a diagnostic, not a definitive rule.
- Reconstruction error: measure how much matrix information is lost.
- Downstream validation: for classification, regression, retrieval, or recommendation, tune against the task-specific metric.
- Operational constraints: consider memory, latency, retraining frequency, and computational cost.
A threshold such as 90% or 95% of matrix energy is only a starting point. It does not guarantee the same percentage of target-relevant information or predictive performance.
9. SVD versus eigendecomposition#
Both are matrix factorization techniques, but they have different domains:
- Eigendecomposition applies to square matrices when the required eigenbasis exists.
- SVD applies to every real or complex rectangular matrix.
- Singular values are always non-negative.
- For a symmetric positive-semidefinite matrix such as a covariance matrix, eigenvalues are non-negative and relate to squared singular values.
- SVD is especially useful for rectangular, rank-deficient, and least-squares problems.
The right singular vectors of are eigenvectors of , and the left singular vectors are eigenvectors of . The squared singular values are the corresponding non-zero eigenvalues.
10. Practical Python example#
For a small dense matrix, NumPy provides an economy SVD:
PYTHONimport numpy as np A = np.array([ [3.0, 0.0], [4.0, 0.0], [0.0, 2.0] ]) U, s, VT = np.linalg.svd(A, full_matrices=False) # Reconstruct the original matrix A_reconstructed = U @ np.diag(s) @ VT print("Singular values:", s) print("Reconstruction:", A_reconstructed) # Retain only the largest singular direction k = 1 A_rank_1 = U[:, :k] @ np.diag(s[:k]) @ VT[:k, :] relative_error = ( np.linalg.norm(A - A_rank_1, ord="fro") / np.linalg.norm(A, ord="fro") ) print("Rank-1 approximation:", A_rank_1) print("Relative reconstruction error:", relative_error)
For large sparse matrices, use sparse or partial decomposition algorithms rather than converting the matrix to dense form unnecessarily.
11. Assumptions, limitations, and trade-offs#
SVD is an algebraic factorization. It does not require normally distributed data or a probabilistic generative model. Its usefulness still depends on the representation and objective.
- Feature scaling: features with very different numerical scales can dominate the decomposition. Scale when comparable feature contributions are intended; do not standardize blindly.
- Centering: centered SVD underlies standard PCA. Uncentered truncated SVD can be more suitable for sparse count or TF-IDF matrices.
- Outliers: large entries can dominate singular directions. Inspect extremes and consider robust alternatives when needed.
- Sparsity: centering a sparse matrix usually makes it dense. Sparse truncated-SVD methods avoid this operation but are not identical to centered PCA.
- Interpretability: latent directions combine original features and may not have simple business meanings.
- Information loss: truncation discards directions. Low reconstruction error does not guarantee better prediction.
- Computational cost: full SVD can be expensive at scale. Randomized, iterative, or sparse partial algorithms reduce cost with accuracy and convergence trade-offs.
- Numerical stability: very small singular values can make inversion unstable. Use tolerances or regularization.
- Sign ambiguity: a singular vector can be multiplied by -1 without changing the decomposition. A sign flip across runs does not necessarily indicate a meaningful change.
12. Leakage-safe use in production ML#
SVD learns directions from the matrix it is fitted on. When used in a predictive pipeline:
- Split training, validation, and test data before fitting learned preprocessing.
- Fit imputation, scaling (if appropriate), and SVD on training data only.
- Choose inside the training/validation process or cross-validation folds.
- Apply the same fitted transformation to validation, test, and production records.
- Persist component matrices, feature order, preprocessing parameters, and algorithm settings with the model.
- Compare against a baseline without dimensionality reduction.
- Monitor input drift, reconstruction behaviour, and downstream quality.
- Recompute factors only through a controlled retraining process.
For text retrieval, persist the vocabulary and TF-IDF weighting configuration too. New documents must be mapped into the same feature space before applying the learned projection.
13. Common interview questions#
Can SVD be applied to a rectangular matrix? Yes. SVD exists for every real or complex matrix, whether square, tall, or wide.
Can singular values be negative? No. They are non-negative and conventionally sorted in descending order.
What does a zero singular value mean? It indicates a redundant direction and contributes to the matrix having rank smaller than its maximum possible rank.
Is SVD the same as PCA? No. PCA is a dimensionality-reduction procedure; SVD is a general matrix factorization. Applying SVD to centered data gives the principal directions used by PCA.
Why is truncated SVD useful for text data? Text-term matrices are high-dimensional and sparse. Truncated SVD creates a compact latent representation without explicitly centering the sparse matrix.
Does keeping 95% of singular-value energy guarantee 95% prediction accuracy? No. It measures matrix reconstruction energy, not predictive accuracy. Validate using the metric relevant to the task.
Why use SVD for least squares? It handles rectangular and rank-deficient matrices and reveals small singular values that can make a solution unstable.
Key takeaway#
SVD factorizes a matrix into . Singular vectors describe orthogonal directions, while singular values measure the strength of each direction. Keeping only the largest singular values creates a principled low-rank approximation used in dimensionality reduction, text mining, recommendation, image compression, denoising, and least-squares computation. The right truncation level depends on reconstruction needs and downstream validation—not a universal threshold.
References
- 1.SLEPc — Singular Value Decompositionslepc.upv.es
- 2.scikit-learn — Decomposing signals in componentsscikit-learn.org
- 3.scikit-learn — TruncatedSVD APIscikit-learn.org
- 4.TensorFlow — Matrix approximation with Core APIstensorflow.org
- 5.Mathematics for Machine Learningmml-book.github.io
- 6.
- 7.Penn State — Principal Component Analysisonline.stat.psu.edu
Related questions
Explore other topics:Deep LearningMLOps