Lesson 22 solved two equations in two unknowns by eliminating one letter. Real problems have more: three unknowns, ten, a thousand. Elimination scales up by writing only the numbers, in a matrix, and following one method: clear the numbers below the diagonal, row by row, until the matrix is a staircase, then read the answer off from the bottom up. It's the method behind np.linalg.solve, it shows plainly when a system has no answer or endless ones, and it answers a question at the heart of ML: which weights make a model fit these examples exactly, and what to do when no weights can.
What you'll be able to do
Write a system of equations as an augmented matrix [A | b]
Use row moves to reach a staircase, then substitute back up to the answer
Tell the three outcomes apart: one solution, none, or infinitely many
Solve for a model's weights exactly, in NumPy and PyTorch, and see why more examples than weights needs a best fit instead
Quick check
Have a guess before you start. x + y = 5 and x − y = 1. What are x and y?
x = 4, y = 1
x = 3, y = 2
x = 2, y = 3
x = 5, y = 0
Show the answer
x = 3, y = 2
Adding the equations eliminates y: 2x = 6, so x = 3, and then y = 2.
The math: row moves down to a staircase
Purpose. Many equations, many unknowns, one method.
Write each equation as a row of its coefficients, with the right-hand side after a bar. The system
x + y + z = 6, 2x + 3y + z = 11, x + 3y + 4z = 19
becomes the augmented matrix:
12113311461119
In plain words: each row is one equation; each column before the bar is one unknown.
Three row moves keep the solution the same: swap two rows; multiply a row by a nonzero number; add a multiple of one row to another. Each is something you could do to the equations themselves without changing what solves them.
Quick check
From lesson 22: in 3x + 2y = 12 and x − 2y = 4, what single move eliminates y?
Subtract the second from the first
Multiply the first by 2
Swap the equations
Add the two equations
Show the answer
Add the two equations
2y and −2y cancel when added: 4x = 16, so x = 4. A row move is the same idea, written on rows of numbers.
The order of attack. Work column by column, left to right. Use each diagonal entry (the pivot) to make zeros in every row below it, so finished work is never disturbed. Each step is labeled the way people write it: R₂ − 2R₁ → R₂ means "replace row 2 with row 2 minus twice row 1". The flow names the unknowns x₁, x₂ and x₃ for x, y and z.
The picture. Above the number boxes, the flow draws [A | b] as a table, one row per equation: the coefficients are shaded, darker for bigger numbers, the right sides are written plain, and an answer row waits underneath. Each row move lights the row it changes and the pivot it uses, and the cleared cell turns pale, so the staircase of zeros shows as it forms. Then the answers fill in, bottom row first.
Try it now
Then set the equations to 0 1 1 5, 1 1 1 6 and 2 3 1 11, one per line, and press Use these numbers: the first pivot is 0, so the flow swaps two rows before it clears anything.
Symbols and formula. After elimination the left part is upper triangular (lesson 57), a staircase:
1001101−156−115⇒z=3,y=−1+z=2,x=6−y−z=1
In plain words: read the bottom row first, then put each answer into the row above. This is back-substitution.
The three outcomes. Elimination always ends in one of three ways:
One solution: every column has a pivot, as above.
No solution: a row reads 0 0 0 | 5, which says 0 = 5. The equations contradict each other.
Infinitely many: a row turns into all zeros, 0 0 0 | 0. One equation was a mix of the others, so an unknown is left free.
Quick check
Elimination leaves the row 0 0 | 4. What does that mean?
x = 4
Infinitely many solutions
y = 0
No solution: the row says 0 = 4
Show the answer
No solution: the row says 0 = 4
A row of zero coefficients with a nonzero right side says 0 = 4, which can't be true.
Two unknowns, as lines. With two unknowns you can see what a row move does. Each equation is a line of points, and the answer is where the lines cross (lesson 22). Here are the two equations from the opening question, x + y = 5 and x − y = 1, with x and y named x₁ and x₂ as before. Watch the row move swing the second line about the crossing until it lies flat, with no x₁ left in it. Then back-substitution reads x₂ off the flat line, and x₁ at the crossing.
In your own words
In your own words: why does adding a multiple of one equation to another not change the solution?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: row moves, then np.linalg.solve
Purpose. Do the moves as array lines once, then let NumPy do them.
It runs right here in your browser, with nothing to install.
The 1.0 makes the whole array decimals, so later divisions aren't cut to whole numbers. M[1] = M[1] - 2 * M[0] is R₂ − 2R₁ → R₂, and the last three lines are back-substitution, bottom row first.
Code flow. Step through the same lines one at a time. M shows as a grid of boxes, the same rows as the flow's: watch each row move rewrite one row and leave a zero under the diagonal, then z, y and x come out, bottom row first.
One call.np.linalg.solve(A, b) runs elimination for you, on the coefficients A and the right side b kept apart. Always check the answer by putting it back: A @ x should equal b.
import numpy as np
A = np.array([[1, 1, 1], [2, 3, 1], [1, 3, 4]])
b = np.array([6, 11, 19])
x = np.linalg.solve(A, b)
print(np.round(x, 6).tolist(), np.allclose(A @ x, b))
A named mistake: solving a system with no single answer. When A is singular (lesson 59), np.linalg.solve can't give one answer, whether the system has no solution or infinitely many. A full install stops with "Singular matrix"; the NumPy in this browser returns nan ("not a number"). Check abs(np.linalg.det(A)) < 1e-9 first, then work out which of the two it is by eliminating by hand.
Worked example
Worked example: solve and verify three systems
Solve three systems, skipping any whose matrix is singular, and confirm each answer by putting it back.
import numpy as np
systems = [(np.array([[3, 1], [1, 2]]), np.array([9, 8])),
(np.array([[1, 1, 1], [0, 2, 1], [1, 0, 3]]), np.array([6, 7, 10])),
(np.array([[1, 2], [2, 4]]), np.array([3, 7]))]
for A, b in systems:
ifabs(np.linalg.det(A)) < 1e-9:
print("singular: no single answer")
else:
x = np.linalg.solve(A, b)
print(np.round(x, 6).tolist(), np.allclose(A @ x, b))
In the lesson you can change this and run it.
The first system gives (2, 3) and the second (1, 2, 3), each confirmed by A @ x. The third has a second row that's twice the first on the left, but 7 isn't twice 3 on the right, so it has no solution; the determinant test catches it before solve would fail. Each item of systems is a tuple of (A, b), unpacked by the for line.
Quick check
What does this print?
import numpy as np
A = np.array([[2, 1], [1, -1]])
b = np.array([7, 2])
x = np.linalg.solve(A, b)
print(np.round(x, 6).tolist(), np.allclose(A @ x, b))
[3.0, 1.0] False
[3.0, 1.0] True
[1.0, 3.0] True
[7.0, 2.0] True
Show the answer
[3.0, 1.0] True
2x + y = 7 and x − y = 2: adding gives 3x = 9, so x = 3 and y = 1. Putting them back reproduces b.
When a pivot is 0. If the number on the diagonal is 0 when you reach it, it can't clear the rows below. The first row move fixes it: swap in a lower row that has a nonzero number in that column. Software goes further and swaps on purpose to use the biggest number available as the pivot, because dividing by tiny pivots magnifies float errors. That's one reason to trust np.linalg.solve over a hand-written loop on real data. Your own loop is still worth writing once: it's the clearest way to see each row move happen, and to check a small answer by hand.
Quick check
What does this print?
import numpy as np
M = np.array([[1.0, 2, 4], [2, 5, 9]])
M[1] = M[1] - 2 * M[0]
print(M.tolist())
[[1.0, 2.0, 4.0], [4.0, 9.0, 17.0]]
[[1.0, 2.0, 4.0], [2.0, 5.0, 9.0]]
[[1.0, 2.0, 4.0], [0.0, 1.0, 1.0]]
[[0.0, 1.0, 1.0], [2.0, 5.0, 9.0]]
Show the answer
[[1.0, 2.0, 4.0], [0.0, 1.0, 1.0]]
R₂ − 2R₁ → R₂: 2 − 2 = 0, 5 − 4 = 1 and 9 − 8 = 1. The new row says y = 1, and then x + 2 = 4 gives x = 2.
Drill
Solve, or say why not
Fix solve_or_none(A, b) so it returns None when A is singular (determinant within 1e-9 of 0) and otherwise the solution. Then set ok to whether the solution of the first system reproduces its b.
In the lesson, your code is checked as you write it.
In your own words
Why put the answer back into the equations even when NumPy found it?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: weights that fit exactly, or best
Purpose. "Which weights fit these examples?" is a system of equations.
A model's weights are its unknowns, and every example it must get right is one equation about them. With exactly as many examples as weights, elimination can pin the weights down.
Suppose tent rentals follow rentals = w₁ × temperature + w₂ × hikers + w₃. Three days give three equations in the three weights:
202530426111w1w2w3=424668
In plain words: each row is one day, and the weights must make all three days come out right at once.
import numpy as np
days = np.array([[20, 4, 1], [25, 2, 1], [30, 6, 1]])
rentals = np.array([42, 46, 68])
w = np.linalg.solve(days, rentals)
print(np.round(w, 6).tolist(), np.allclose(days @ w, rentals))
The weights are 2 rentals per degree, 3 per hiker, and −10: they fit all three days exactly. The column of 1s is what lets w₃ act as a constant, the trick from lesson 58 that folds a bias into the weights.
Quick check
A fourth day is added: 28 degrees, 5 hikers, 62 rentals. The weights (2, 3, −10) predict 61. What happens if you try to fit all four days exactly?
The fourth day is ignored
There are infinitely many answers
The weights simply change to fit all four
No exact answer: 4 equations disagree on 3 weights
Show the answer
No exact answer: 4 equations disagree on 3 weights
With more equations than unknowns, the days usually contradict each other. The best you can do is the weights that miss by the least: a best fit, in lesson 101.
In PyTorch. The same fit in the real tool, with its loss. torch.linalg.solve takes the same two arguments as NumPy's. F.mse_loss is the loss from the model map: it squares each miss and averages them. torch.round(…, decimals=4) tidies float noise, like np.round.
The weights are 2, 3 and −10, the same as the NumPy cell printed, and the loss is 0: they fit all three days exactly. Add the fourth day and the same weights miss it by 1, so the loss over four days is 1² ÷ 4 = 0.25.
More examples than weights. Real data has thousands of days and a handful of weights, so no weights make the loss 0 and elimination would report "no solution". Models take the weights with the smallest loss instead, the least-squares fit of lesson 101. Training a neural network chases the same thing in a far bigger system, by small steps instead of elimination.
Drill
Fit, then test on a new day
Solve for w from the three days below, then set pred to its prediction for the new day (28, 5) and leftover to the actual 62 minus pred, both rounded to 6 places.
import numpy as np
days = np.array([[20, 4, 1], [25, 2, 1], [30, 6, 1]])
rentals = np.array([42, 46, 68])
w = np.zeros(3)
new_day = np.array([28, 5, 1])
pred = 0
leftover = 0print(w, pred, leftover)
In the lesson, your code is checked as you write it.
In your own words
Why does a model with three weights usually miss some of a thousand examples?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write