Least-squares workflows
Solve or analyze least-squares systems using an orthonormal-triangular decomposition.
NumPy · Function
Computes the QR factorization of an array, expressing it as an orthonormal factor Q and an upper-triangular factor R. The mode selects reduced, complete, R-only, or raw Householder output.
The function factors an array into an orthonormal component Q and an upper-triangular component R. The mode controls whether it returns reduced or complete factors, only R, or the raw Householder representation; arrays with leading dimensions are treated as stacks of matrices.
numpy.linalg.qr(a, mode='reduced')| Name | Type | Description |
|---|---|---|
a | array_like | An array-like object with at least two dimensions and shape (..., M, N). |
mode | {'reduced', 'complete', 'r', 'raw'}, optional | One of 'reduced', 'complete', 'r', or 'raw'; defaults to 'reduced'. |
For reduced or complete modes, returns Q and R. For r mode, returns R only. For raw mode, returns (h, tau), where h contains Householder reflectors and tau contains their scaling factors.
import numpy as np
A = np.array([[1., 2.], [3., 4.], [5., 6.]])
Q, R = np.linalg.qr(A)
assert np.allclose(A, Q @ R)
assert np.allclose(Q.T @ Q, np.eye(2))
print(Q.shape, R.shape)Computes a reduced QR factorization and verifies reconstruction and orthonormal columns.
Solve or analyze least-squares systems using an orthonormal-triangular decomposition.
Extract an orthonormal basis from the columns of a matrix.
Process multiple matrices stored in an array with leading batch dimensions.
It decomposes a matrix into Q and R, where Q has orthonormal columns and R is upper triangular. The default reduced mode uses K = min(M, N), producing Q with shape (..., M, K) and R with shape (..., K, N).
Follow-up: How would you obtain only the triangular factor? Use mode='r', which returns R with shape (..., K, N), avoiding construction of Q.
The complete mode returns Q with shape (..., M, M) and R with shape (..., M, N). For a real input Q is orthogonal; for a complex input it is unitary.
Follow-up: What does complete mode imply for a square real matrix? Q is a square orthogonal matrix, so its columns and rows are orthonormal.
The raw mode returns h and tau instead of Q and R. h stores Householder reflectors and tau stores their scaling factors; their dtypes are np.double or np.cdouble.
Follow-up: Why might raw mode be useful? It exposes the factorization's reflector representation when downstream code needs the underlying Householder data rather than explicit Q.
numpy.linalg.lstsqnumpy.linalg.svdnumpy.linalg.choleskynumpy.linalg.solve