Linear Algebra
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against NumPy 2.5 (2.5.4 is the current patch release). Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run on NumPy 2.5.4. Linear algebra in NumPy is the numpy.linalg module plus a few top-level functions (matmul, dot, einsum, tensordot, kron). Under the hood they call BLAS and LAPACK libraries bundled with the wheels, so speed and, to a small degree, the last digits of the results depend on the installed library (see Threads, Free-Threading & Performance).
Arrays, not matrices
Use two-dimensional ndarrays and the @ operator. numpy.matrix is documented as no longer recommended, even for linear algebra: it is always 2-D, overloads * as matrix multiplication, and behaves inconsistently with ordinary arrays. Use np.array (and np.asarray) and write A @ B for a matrix product and A * B for the element-wise product. The old alias np.mat was removed in NumPy 2.0.
Source: numpy.matrix and NumPy 2.0 migration guide
Products
A @ B is numpy.matmul(A, B). For 1-D operands it is the inner product, for 2-D operands the matrix product, and for higher dimensions it treats the last two axes as matrices and broadcasts the leading ones. A scalar operand is an error: use * for scaling.
import numpy as np
from numpy import linalg as la
A = np.array([[3., 1.], [1., 2.]])
b = np.array([9., 8.])
print(A @ b, np.matmul(A, b), np.dot(A, b))
print(np.vecdot(b, b), np.inner(b, b))
print(np.outer(b[:1], b))
print((np.ones(3) @ np.ones(3)), (np.ones((2, 3)) @ np.ones(3)).shape)
try:
np.ones((2, 3)) @ 2
except ValueError as e:
print(e)
[35. 25.] [35. 25.] [35. 25.] 145.0 145.0 [[81. 72.]] 3.0 (2,) matmul: Input operand 1 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)
The product functions are:
| Function | Meaning |
|---|---|
|
Matrix product with broadcasting over leading axes; the preferred spelling. |
|
Same as |
|
Dot product along the last axis (conjugating the first argument for complex numbers), broadcasting over the rest. |
|
Batched matrix-vector and vector-matrix products. |
|
Inner and outer product, Kronecker product, general contraction over chosen axes, Einstein summation, and optimised order for a chain of matrix products. |
|
Array API standard names for operations that also exist at the top level. |
.mT and numpy.linalg.matrix_transpose transpose only the last two axes, which is what you want for a batch of matrices; .T reverses all axes. Both return views. np.cross requires three-dimensional vectors: two-dimensional vectors were deprecated in NumPy 2.0 and raise a ValueError in 2.5.4, so write the z-component explicitly.
Source: NumPy reference: Linear algebra and numpy.matmul
Solving linear systems
numpy.linalg.solve(A, b) solves A x = b for a square, full-rank A. It is faster and numerically more accurate than computing inv(A) @ b, so prefer it unless you really need the inverse matrix.
x = la.solve(A, b)
print(x, np.allclose(A @ x, b))
print(la.inv(A), la.det(A), la.matrix_rank(A), la.cond(A), np.trace(A))
print(la.solve(A, np.array([[9., 1], [8, 2]]))) # several right-hand sides, one per column
[2. 3.] True [[ 0.4 -0.2] [-0.2 0.6]] 5.000000000000001 2 2.6180339887498953 5.0 [[2. 0.] [3. 1.]]
Source: numpy.linalg.solve, numpy.linalg.inv and numpy.linalg.matrix_rank
Since NumPy 2.0, b is treated as a single vector only when it is one-dimensional; any other shape is a stack of matrices of right-hand sides. For a batch of systems with one vector each, add a trailing axis (b[..., None]) and remove it afterwards:
M = np.random.default_rng(0).normal(size=(4, 3, 3))
bb = np.ones((4, 3))
print(la.solve(M, bb[..., None]).shape) # (4, 3, 1): one column per system
try:
la.solve(M, bb)
except ValueError as e:
print(e)
(4, 3, 1) solve: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (m,m),(m,n)->(m,n) (size 4 is different from 3)
Source: numpy.linalg.solve
A singular matrix raises numpy.linalg.LinAlgError:
try:
la.inv(np.array([[1., 2.], [2., 4.]]))
except la.LinAlgError as e:
print("LinAlgError", e)
LinAlgError Singular matrix
Source: numpy.linalg.inv and numpy.linalg.LinAlgError
A nearly singular matrix does not raise: the result is just inaccurate. Check the condition number la.cond(A) (the ratio of the largest to the smallest singular value). The Hilbert matrix is the classic example:
n = 10
H = 1 / (np.arange(1, n + 1)[:, None] + np.arange(n))
xtrue = np.ones(n)
b = H @ xtrue
print(f"{la.cond(H):.2e}")
print(f"{np.abs(la.solve(H, b) - xtrue).max():.1e}")
print(f"{np.abs(la.inv(H) @ b - xtrue).max():.1e}")
1.60e+13 6.3e-04 7.3e-03
A condition number near 1e16 means no digits of a double-precision result can be trusted; one of 1e13 loses about 13 of the 16 digits, and inv(H) @ b loses more than solve. matrix_rank uses a tolerance on the singular values, so a rank is relative to the floating-point precision, not exact.
Source: numpy.linalg.solve and numpy.linalg.cond
Least squares and the pseudo-inverse
numpy.linalg.lstsq(X, y, rcond=None) returns the solution minimising the 2-norm of the residual X @ c - y, the residual sums of squares, the rank, and the singular values. For a rank-deficient system it returns the minimum-norm solution. Since NumPy 2.0 the default rcond=None uses machine precision times the larger matrix dimension (the old default -1 was machine precision); pass rcond=None explicitly to select the modern behaviour in code that must also run on 1.x.
X = np.c_[np.ones(5), np.arange(5.)]
y = np.array([1.1, 2.9, 5.2, 7.1, 8.8])
coef, res, rank, sv = la.lstsq(X, y, rcond=None)
print(coef, res, rank, sv)
Xd = np.array([[1., 1, 2], [1, 2, 3], [1, 3, 4]]) # third column = first + second
yd = np.array([1., 2, 3])
c, res, rk, sv = la.lstsq(Xd, yd, rcond=None)
print(rk, c, np.allclose(la.pinv(Xd) @ yd, c))
[1.1 1.96] [0.092] 2 [5.78859314 1.22155205] 2 [-0.33333333 0.66666667 0.33333333] True
numpy.linalg.pinv computes the Moore-Penrose pseudo-inverse through the SVD. Both lstsq and pinv are the stable way to fit linear models; never form the normal equations X.T @ X explicitly, because that squares the condition number. Regression with inference, diagnostics and regularisation belongs in statsmodels or scikit-learn (see scikit-learn); NumPy’s lstsq is the building block.
Source: numpy.linalg.lstsq
Eigenvalues and eigenvectors
Use eigh (or eigvalsh) for symmetric or Hermitian matrices: it is faster, returns real eigenvalues in ascending order, and eigenvectors that are orthonormal. Use eig (or eigvals) for general square matrices. In NumPy 2.5, eig and eigvals always return complex arrays, even when every eigenvalue is real; older NumPy returned a real array in that case. Code that compared dtype or relied on real results must call .real after checking that the imaginary part is zero, or switch to eigh when the matrix is symmetric.
w, V = la.eigh(A)
print(w)
print(V)
w2, V2 = la.eig(A)
print(w2, V2.dtype)
print(la.eigvals(np.array([[0., 1.], [-1., 0.]])))
[1.38196601 3.61803399] [[ 0.52573111 -0.85065081] [-0.85065081 -0.52573111]] [3.61803399+0.j 1.38196601+0.j] complex128 [0.+1.j 0.-1.j]
Eigenvectors are returned as the columns of V and are determined only up to sign (and complex phase), so do not compare them across platforms or library versions. eigh reads only one triangle of the matrix (UPLO="L" by default, or "U") and does not check symmetry, so passing a non-symmetric matrix gives a silently wrong answer.
Source: numpy.linalg.eig and numpy.linalg.eigh
Singular value decomposition
numpy.linalg.svd(B) factors B = U @ diag(s) @ Vh. By default full_matrices=True returns square U and Vh; pass full_matrices=False for the economy form, which is what you want almost always. svdvals (2.0) returns just the singular values. Truncating to the largest k values gives the best rank-k approximation in the 2-norm and the Frobenius norm (Eckart-Young), the basis of PCA and latent semantic analysis:
B = np.arange(6.).reshape(3, 2)
U, s, Vh = la.svd(B)
print(U.shape, s, Vh.shape)
print(la.svd(B, full_matrices=False)[0].shape)
print(la.svdvals(B))
rng = np.random.default_rng(0)
B = rng.normal(size=(6, 4)) @ rng.normal(size=(4, 5)) # rank 4
U, s, Vh = la.svd(B, full_matrices=False)
print(s.round(3))
k = 2
Bk = (U[:, :k] * s[:k]) @ Vh[:k]
print(f"{la.norm(B - Bk, 2):.4f} {s[k]:.4f}") # error equals the next singular value
(3, 3) [7.38648213 0.66323581] (2, 2) (3, 2) [7.38648213 0.66323581] [5.038 4.442 1.712 1.218 0. ] 1.7119 1.7119
Source: numpy.linalg.svd
Norms, determinants and factorisations
numpy.linalg.norm(x, ord=None, axis=None) is the general function: with ord=None it gives the 2-norm of a vector or the Frobenius norm of a matrix. The newer vector_norm and matrix_norm (2.0) are explicit about which one you mean and take axis/keepdims; for matrix_norm, ord is keyword-only.
v = np.array([3., -4.])
print([float(la.vector_norm(v, ord=o)) for o in (1, 2, np.inf, 0)])
M2 = np.array([[1., 2.], [3., 4.]])
print([float(la.matrix_norm(M2, ord=o)) for o in ("fro", 1, np.inf, 2, "nuc")])
[7.0, 5.0, 4.0, 2.0] [5.477225575051661, 6.0, 7.0, 5.464985704219043, 5.8309518948453]
Source: numpy.linalg.vector_norm and numpy.linalg.matrix_norm
For a vector, ord=1 is the sum of absolute values, 2 the Euclidean length, np.inf the largest absolute value and 0 the count of non-zero entries. For a matrix, 1 and np.inf are the largest absolute column and row sums, 2 is the largest singular value, "fro" is the Frobenius norm and "nuc" the sum of singular values.
det overflows or underflows for large matrices; slogdet returns the sign and the logarithm of the absolute value instead:
D = np.eye(300) * 0.1
print(la.det(D))
print(la.slogdet(D))
1.0000000000021837e-300 SlogdetResult(sign=np.float64(1.0), logabsdet=np.float64(-690.7755278982115))
Source: numpy.linalg.det and numpy.linalg.slogdet
Further factorisations: cholesky (lower triangular L with A = L @ L.T for a symmetric positive-definite matrix, upper=True since 2.0 returns the upper factor, and a non-positive-definite matrix raises LinAlgError), qr (orthonormal Q and upper-triangular R), matrix_power, multi_dot, matrix_rank, tensorsolve and tensorinv. LU, Schur, the matrix exponential and triangular solvers live in SciPy.
L = la.cholesky(A)
print(L, np.allclose(L @ L.T, A))
Q, R = la.qr(A)
print(np.allclose(Q @ R, A))
try:
la.cholesky(np.array([[1., 2.], [2., 1.]]))
except la.LinAlgError as e:
print("LinAlgError", e)
print(la.cholesky(np.array([[4., 2.], [2., 3.]]), upper=True))
[[1.73205081 0. ] [0.57735027 1.29099445]] True True LinAlgError Matrix is not positive definite [[2. 1. ] [0. 1.41421356]]
Source: numpy.linalg.norm and numpy.linalg.slogdet
Stacked (batched) operations
Almost every numpy.linalg function accepts arrays with more than two dimensions and applies the operation to the last two axes, broadcasting over the leading ones. A stack of 4 matrices of shape 3x3 has shape (4, 3, 3):
M = np.random.default_rng(0).normal(size=(4, 3, 3))
print(la.det(M).shape, la.inv(M).shape, (M @ M).shape)
print(np.matvec(M, np.ones((4, 3))).shape, np.vecmat(np.ones((4, 3)), M).shape)
print(M.mT.shape, la.matrix_transpose(M).shape)
print(la.norm(M, axis=(1, 2)).shape, la.vector_norm(M, axis=-1).shape)
(4,) (4, 3, 3) (4, 3, 3) (4, 3) (4, 3) (4, 3, 3) (4, 3, 3) (4,) (4, 3)
This replaces Python loops over many small matrices and is the idiom for batches of rotation matrices, covariance matrices or images. Mind the axis placement: functions that reduce a matrix to a scalar (det, matrix_rank, cond, norm with axis=(1, 2)) drop the last two axes. See Broadcasting for the rules that decide how the leading axes align.
Choosing a function
NumPy and SciPy
scipy.linalg is a superset of numpy.linalg: it is always compiled with BLAS and LAPACK, adds LU (lu, lu_factor/lu_solve), Schur, QZ, expm/logm/sqrtm, triangular and banded solvers, generalised eigenvalue problems (eigh(a, b)), and sparse routines in scipy.sparse.linalg. Use NumPy for the common cases on dense arrays and SciPy as soon as you need one of these or finer control (such as assume_a= in scipy.linalg.solve to select a symmetric or positive-definite solver). Dense NumPy and SciPy routines work on arrays that fit in memory; for huge or sparse problems use scipy.sparse. Embeddings and similarity search over vectors use these same products and norms: see Embeddings. The R equivalents of these functions are described on Matrices and Arrays in the R section.
Source: SciPy reference: scipy.linalg
NumPy 2 changes at a glance
| Change | Detail |
|---|---|
|
Use arrays and |
|
|
|
|
New functions |
|
|
Always return complex arrays (2.5); use |
|
Requires 3-D vectors in 2.5.4 (2-D vectors deprecated in 2.0). |
Pitfalls
-
A * Bis element-wise; matrix products use@. -
inv(A) @ bis slower and less accurate thansolve(A, b). -
solve(M, b)with a 2-Dband a batch of matrices treatsbas a matrix, not as a batch of vectors. -
Eigenvector columns and singular vectors have arbitrary signs; compare reconstructions (
A @ V - V * w) instead. -
eighdoes not check that the matrix is symmetric. -
detof a large matrix overflows or underflows; useslogdet. -
Integer arrays are converted to
float64bylinalgfunctions; a matrix product ofint8arrays can overflow silently, because array overflow does not warn (see Type Promotion (NEP 50)). -
Results may differ in the last digits across BLAS implementations and thread counts; test with
np.allclose, not==.