Solving Linear Systems
Np.linalg.solve.
Two apples and three bananas cost eight dollars. One apple and one banana cost three dollars. What does each fruit cost? That's a system of linear equations, and matrices solve it in one line.

- 2 apples + 3 bananas = 8
- 1 apple + 1 banana = 3
- Find each price
A x equals b
We write the counts as a matrix A, and the totals as a vector B. We want the prices X, so that A times X equals B. Lin alg dot solve finds it. Run it. Apples cost one dollar, and bananas cost two. And A times X gives back the totals.
import numpy as np
A = np.array([[2, 3],
[1, 1]])
b = np.array([8, 3])
x = np.linalg.solve(A, b)
print("apple, banana:", x)
print("check:", A @ x)apple, banana: [1. 2.] check: [8. 3.]
Solve, not invert
You could compute the inverse of A, and multiply it by B. But solve is faster and more accurate, so always prefer it. With more equations than unknowns, there's usually no exact answer. Then we look for the closest answer, with least squares. That's exactly what linear regression does.
| key | value |
|---|---|
| Ax = b | the system |
| np.linalg.solve | exact answer |
| More equations | no exact answer |
| Least squares | the closest answer |
Summary
A system of linear equations is AX equals B, and lin alg dot solve finds X. Next, regression, written with matrices.
Key takeaways- Ax = b
- np.linalg.solve(A, b)
- Prefer solve to inv