bundles / numpy 2.4.3 / numpy / linalg / lstsq
_ArrayFunctionDispatcher
numpy.linalg:lstsq
source: /numpy/linalg/_linalg.py :2417
Signature
def lstsq ( a , b , rcond = None ) Summary
Return the least-squares solution to a linear matrix equation.
Extended Summary
Computes the vector x that approximately solves the equation a @ x = b. The equation may be under-, well-, or over-determined (i.e., the number of linearly independent rows of a can be less than, equal to, or greater than its number of linearly independent columns). If a is square and of full rank, then x (but for round-off error) is the "exact" solution of the equation. Else, x minimizes the Euclidean 2-norm . If there are multiple minimizing solutions, the one with the smallest 2-norm is returned.
Parameters
a: (M, N) array_like"Coefficient" matrix.
b: {(M,), (M, K)} array_likeOrdinate or "dependent variable" values. If
bis two-dimensional, the least-squares solution is calculated for each of theKcolumns ofb.rcond: float, optionalCut-off ratio for small singular values of
a. For the purposes of rank determination, singular values are treated as zero if they are smaller thanrcondtimes the largest singular value ofa. The default uses the machine precision timesmax(M, N). Passing-1will use machine precision.
Returns
x: {(N,), (N, K)} ndarrayLeast-squares solution. If
bis two-dimensional, the solutions are in theKcolumns of x.residuals: {(1,), (K,), (0,)} ndarraySums of squared residuals: Squared Euclidean 2-norm for each column in
b - a @ x. If the rank ofais < N or M <= N, this is an empty array. Ifbis 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,).rank: intRank of matrix
a.s: (min(M, N),) ndarraySingular values of
a.
Raises
: LinAlgErrorIf computation does not converge.
Notes
If b is a matrix, then all array results are returned as matrices.
Examples
Fit a line, ``y = mx + c``, through some noisy data-points:import numpy as np x = np.array([0, 1, 2, 3]) y = np.array([-1, 0.2, 0.9, 2.1])✓
A = np.vstack([x, np.ones(len(x))]).T
✓A
✗m, c = np.linalg.lstsq(A, y)[0]
✓m, c
✗import matplotlib.pyplot as plt _ = plt.plot(x, y, 'o', label='Original data', markersize=10) _ = plt.plot(x, m*x + c, 'r', label='Fitted line') _ = plt.legend() plt.show()✓

See also
- scipy.linalg.lstsq
Similar function in SciPy.
Aliases
-
numpy.linalg.lstsq