SciPy linear solvers
Quick answer
SciPy linear algebra routines solve equations and fit approximate solutions using numerical algorithms. For a square nonsingular matrix A, solve finds x such that A @ x = b. When there are more observations than unknowns, least squares instead minimizes the sum of squared residuals. This is a foundation of linear regression, not yet a complete predictive modeling workflow. Examples use local Python 3.13.5, SciPy 1.17.0, NumPy 2.3.5 and Matplotlib 3.10.8 as applicable. All fixtures are synthetic; ByteMind library execution is unverified.
Recover two calibration constants
Two equations represent synthetic calibration readings: 2a+b=7 and a+3b=11. Use solve rather than calculating an inverse.
import numpy as npfrom scipy.linalg import solveA = np.array([[2., 1.], [1., 3.]])b = np.array([7., 11.])x = solve(A, b)print(np.round(x, 6).tolist())print(bool(np.allclose(A @ x, b)))Expected output:
[2.0, 3.0]TrueThe solution satisfies both equations. allclose checks approximate equality; floating-point solutions are not symbolic proofs.
Fit a constant to noisy measurements
A column of ones means every predicted reading equals the same unknown constant. Three readings overdetermine the single parameter.
import numpy as npfrom scipy.linalg import lstsqA = np.ones((3, 1))b = np.array([2., 4., 6.])x, _, rank, _ = lstsq(A, b)r = b - A @ xprint(round(float(x[0]), 6), rank)print(round(float(r @ r), 6))Expected output:
4.0 18.0The mean minimizes squared error for a constant predictor. Residuals are observed minus predicted. The rank reports the number of independent columns here; computing residuals directly avoids depending on the shape of lstsq’s residual return value.
Common mistakes
Do not solve a rectangular system with solve or form inv(A) @ b as the default. Singular or ill-conditioned inputs can fail or give unreliable coefficients. A small residual does not establish small parameter error when the problem is ill-conditioned. Inspect rank, conditioning and the scale of residuals. Never fit on held-out targets.
Practice and next steps
Compute the residual of [2, 3] under the first system by hand. Change one reading in the constant fit and predict the new mean. Try the residual calculation challenge. The separate pure-Python exercise assesses the underlying calculation, not library execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
SciPy linear solvers — knowledge check
Apply scientific computing and visualization reasoning to synthetic examples.
Which routine fits an overdetermined linear system by minimizing squared residuals?
A @ x = [3, 5] and b = [4, 2]. What is b - A @ x?
What is the rank of a nonempty column of ones?
Why avoid explicit inversion for solving Ax=b?
A small residual for an ill-conditioned system establishes what?