🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeSVD NumPy: Decompose a Matrix

To decompose a matrix in NumPy, use SVD. SVD expresses the matrix as a product of factors.
I’ll explain the shapes of those factors and show how to reconstruct the matrix or make a lower-rank approximation.
TL;DR: NumPy SVD returns U, s, and Vh
Call np.linalg.svd(A, full_matrices=False) for a compact decomposition, then reconstruct a 2D matrix with (U * s) @ Vh.
- U contains left singular vectors, s contains descending singular values, and Vh contains right singular vectors as rows.
- For an M by N input, reduced output shapes are (M, K), (K,), and (K, N), where K is the smaller dimension.
- Use np.linalg.svdvals(A) when singular values are all you need.
What does NumPy SVD return?
An SVD expresses A as UΣVh, with U columns holding left singular vectors and Vh rows holding right singular vectors. NumPy returns the diagonal of Σ as one-dimensional s, not as a matrix. For complex arrays, H indicates conjugate transpose.
For an M by N matrix, K = min(M, N), and s has K values. The table shows how the full and reduced settings affect U and Vh.
| Setting | U shape | s shape | Vh shape |
|---|---|---|---|
| full_matrices=True | (M, M) | (K,) | (N, N) |
| full_matrices=False | (M, K) | (K,) | (K, N) |
I choose the reduced setting for reconstruction because its factors pair directly with s.
How to compute and reconstruct an SVD step by step
A fixed rectangular matrix shows component shapes and makes the output repeatable.
Step 1: Define the matrix and compute its decomposition
Pass a 2-by-3 array to np.linalg.svd() and request reduced matrices. The returned order is U, s, then Vh.
import numpy as np
A = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
U, s, Vh = np.linalg.svd(A, full_matrices=False)
reconstructed = (U * s) @ Vh
rank_one = s[0] * np.outer(U[:, 0], Vh[0, :])
print("Shapes:", U.shape, s.shape, Vh.shape)
print("Singular values:", np.round(s, 3))
print("Reconstruction matches:", np.allclose(A, reconstructed))
print("Rank-1 approximation:\n", np.round(rank_one, 2))
Save this as svd_demo.py and run python3 svd_demo.py. I ran that command with NumPy 2.4.3. Here are its shapes and values:
Shapes: (2, 2) (2,) (2, 3)
Singular values: [9.508 0.773]
Reconstruction matches: True
Rank-1 approximation:
[[1.57 2.08 2.59]
[3.76 4.97 6.17]]

The reconstruction check is True. The rank-one matrix keeps the first singular value and its paired vectors.
Syntax of np.linalg.svd()
The function accepts an array and keyword options that control the returned factors. Its current signature is np.linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=False). The defaults request full-sized factors, return vectors, and make no symmetry assumption.
| Argument | Purpose | Practical choice |
|---|---|---|
| a | Input array with at least two dimensions | Check the final two dimensions are the matrix you intend to decompose |
| full_matrices | Controls whether U and Vh include the full square bases | Use False when compact factors are enough |
| compute_uv | Controls whether singular vectors are returned | Use False if you need values only |
| hermitian | States that the input is Hermitian or symmetric | Leave False unless that property is known |
With compute_uv=True, the result is a tuple containing U, s, and Vh. With compute_uv=False, the result is the singular-value array rather than that tuple. The dedicated np.linalg.svdvals(a) call expresses the values-only task directly.
For an M by N input, let K=min(M,N). Reduced output has U shape (M,K), s shape (K,), and Vh shape (K,N). The full mode instead returns square U and Vh matrices with shapes (M,M) and (N,N), while s keeps K entries.
Prerequisites for setup
Run the example with Python and NumPy available in the same environment. It uses arrays and matrix multiplication, with no external data or service.
Check the interpreter and import before running the decomposition. A failed import points to the active Python environment, not to an SVD shape issue.
import numpy as np
print(np.__version__)
Install NumPy in that environment through its normal package manager if the import fails. Do not assume an installation in a different interpreter is available to the command you use to run the script.
Hands-on example: performing SVD with NumPy
The executed 2-by-3 example makes the return order visible without hiding the shape issue. A rectangular matrix has two singular values because K is the smaller input dimension. Each value scales a matching pair of vectors in the factorization.
For a full reconstruction, retain every value and its paired vectors. The multiplication (U * s) scales columns of U by broadcasting the one-dimensional s array, then @ multiplies the result by Vh. Creating np.diag(s) is another valid way to express the middle factor, but it allocates a separate diagonal matrix.
The rank-one expression in the script keeps only the leading singular triplet. It forms an outer product from the first column of U and first row of Vh, then scales that matrix by s[0]. The result approximates the input rather than reproducing every entry exactly.
To inspect the approximation error, subtract the reconstruction from A and measure a norm. The Frobenius norm treats the residual as one vector of entries. A relative error divides by the input norm, which makes comparisons across differently scaled matrices meaningful, provided the input norm is nonzero.
residual = A - rank_one
print("Frobenius error:", np.linalg.norm(residual))
print("Relative error:", np.linalg.norm(residual) / np.linalg.norm(A))
This code adds a check, not a second decomposition. The chosen norm answers how far the approximation is from the supplied matrix under that measure.
For k=1, use U[:, :1], s[:1], and Vh[:1, :]. Increase the same slice boundary in each factor to retain more components. A mismatch means the factors no longer describe the same singular directions.
Choose k by testing the resulting matrix in its intended use, rather than treating a fixed percentage of retained values as a universal rule. A compact approximation can reduce storage, while its usefulness depends on the information the task needs to preserve.
The singular values provide one inspection aid: a sharp drop can indicate that later components contribute less to the represented matrix. It does not by itself establish that those components are irrelevant to a prediction, image, or downstream calculation.
The singular values arrive in descending order, so keeping the first k retains the largest components first. A rank-k approximation is useful when a lower-rank representation suits the task, but choosing k is a modeling decision: inspect the singular values and validate the approximation against the downstream need.
For larger arrays, avoid assuming that a small rank slice makes the computation itself truncated. np.linalg.svd computes the decomposition and the later slices select components from its outputs. When the input is sparse or too large for that workflow, a sparse solver such as SciPy’s svds has different output and convergence considerations, so check its API before substituting it.
NumPy also accepts stacked matrices. If A has shape (B,M,N), it decomposes each final-two-axis matrix and returns leading batch dimensions along with each factor. In that case, the one-dimensional broadcast used for a single 2D matrix must be adapted: insert an axis into s so it scales the column dimension for every batch.
U, s, Vh = np.linalg.svd(batch, full_matrices=False)
reconstructed_batch = (U * s[..., None, :]) @ Vh
The ellipsis preserves any batch dimensions, and the inserted axis aligns each singular value with its corresponding U column. Verify the resulting shapes against the input before applying this form to arrays with additional batch axes.
Step 2: Rebuild the matrix from U, s, and Vh
For a reduced 2D SVD, multiplying each U column by its matching singular value gives a direct reconstruction: (U * s) @ Vh. NumPy broadcasts s across U’s columns, so there is no need to create a diagonal matrix.
Use np.allclose() to allow for floating-point rounding when checking the reconstruction.
Step 3: Keep only the first k singular values
Choose a smaller rank by retaining matching columns of U, entries of s, and rows of Vh.
Use (U[:, :k] * s[:k]) @ Vh[:k, :] for a rank-k approximation. NumPy computes the full SVD before these slices are applied.
For related matrix operations, see AskPython’s guides to NumPy matrix rank and NumPy pseudoinverse.
SVD shapes, truncation, and common errors
Check the returned shapes before multiplying components, then choose an API that matches whether you need vectors or values alone. These checks resolve common reconstruction and output misunderstandings.
| Need or symptom | Choice or check |
|---|---|
| Only singular values | np.linalg.svd(A, compute_uv=False) or np.linalg.svdvals(A) |
| Compact factors | Set full_matrices=False |
| Negative entries in singular vectors | Singular values in s are nonnegative |
| Unexpected complex reconstruction | Use Vh directly and do not transpose it again |
| LinAlgError | NumPy reports that SVD did not converge. Inspect non-finite inputs and retry with cleaned data or a suitable solver |
Singular vectors can change by paired sign flips, or by phases in complex arrays, without changing the product. Compare reconstructed matrices rather than individual vectors.
When A has more than two dimensions, NumPy applies SVD to each matrix in the final two axes. The leading dimensions are batch dimensions, and each batch member gets its own U, s, and Vh. The 2D reconstruction expression should then add broadcast axes to s as shown in the official NumPy SVD documentation.
For an arbitrary input, keep hermitian at its default because symmetry has not been established. Set hermitian=True only for Hermitian or symmetric input.
This flag tells NumPy to use that property during computation. If only singular values are needed, the svdvals documentation describes the focused alternative.
For symmetric matrices and eigenvalue-focused work, compare this decomposition with AskPython’s eigvalsh guide. SVD accepts rectangular arrays, while eigvalsh handles Hermitian or symmetric square arrays.
A two-dimensional input keeps the algebra visible, but the returned factors are still arrays with shapes that govern valid multiplication. Check the shapes in a debugger or print them before combining factors when adapting the example to your own input.
The singular values measure the strength of each component in the decomposition. A value near zero contributes little to reconstructing the input, although whether it can be discarded depends on the precision your application needs.
When the input is rank deficient, some singular values are zero or close to zero within floating-point precision. This affects rank estimates, so a computed rank usually needs a tolerance rather than a direct test for exact equality with zero.
A singular vector’s sign is not a stable identifier for a component. If a later run flips matching signs in U and Vh, their product still represents the same matrix. Tests should compare the reconstruction or subspace, not demand identical vector entries.
For complex arrays, conjugation matters. NumPy’s Vh already contains the conjugate-transposed right singular vectors, so use it in the reconstruction as returned. Taking another transpose or conjugate without a reason changes the multiplication.
The hermitian option is a promise about the input structure, not a request to make an arbitrary matrix symmetric. Keep its default for general matrices. For a known symmetric or Hermitian matrix, the option lets the routine use the documented structure.
Non-convergence raises numpy.linalg.LinAlgError. Inspect the input for NaN or infinite values first, since these prevent a meaningful factorization. If the values are finite and the routine still fails, preserve the input and error details while testing a solver suited to the matrix’s size and structure.
Memory use also depends on the requested output. Full matrices can contain many entries that are not needed for reconstruction of a rectangular input. The reduced form keeps the factors sized to K and is a practical default when the full orthogonal bases are not part of the task.
CodeSignal’s lesson on SVD with NumPy presents the decomposition as a worked learning exercise. Its learner invitation is separate from the API task here, so use the lesson if you want guided practice and use the NumPy reference for exact argument and shape behavior.
Conclusion: choose the SVD output you need
Use reduced np.linalg.svd() when you need factors for reconstruction or approximation, and choose svdvals() when singular values alone answer the question.
For exact parameter shapes and batched reconstruction, refer to the NumPy linalg.svd reference. For a neighboring decomposition task, see eigenvalue decomposition in Python.
FAQ
These answers cover common follow-up questions about NumPy SVD output and reconstruction.
How do you reconstruct a matrix from NumPy SVD?
For a reduced 2D decomposition, calculate (U * s) @ Vh. Use np.allclose(A, reconstructed) to check the result within floating-point tolerance.
How do you get a truncated SVD in NumPy?
Compute a reduced SVD, then retain the first k columns of U, first k singular values, and first k rows of Vh. This gives a rank-k approximation, but NumPy computes the full decomposition first.
Why are some SVD components negative?
Entries in U or Vh can be negative, but singular values in s are nonnegative. Paired sign changes in singular vectors leave the decomposition unchanged.


