The same expression can be written in different shapes, and some shapes are more useful than others. Expanding multiplies brackets out; factoring pulls them back together. Both are the same rule run in opposite directions, and a picture of rectangles makes it obvious. In machine learning, expanding a squared error shows that it's a bowl in the weight, which is why there's a single best weight to find.
What you'll be able to do
Expand brackets with the area model, from a(b + c) to a three-term bracket
Factor by pulling out a common factor, and factor a simple quadratic by un-expanding
Check that two expressions are the same in Python by trying inputs and subtracting
Expand a squared error to see it as a bowl-shaped expression in the weight
Quick check
Have a guess before you start. What is (x + 3)(x + 2) when x = 10?
130
156
106
25
Show the answer
156
Brackets first: x + 3 = 13 and x + 2 = 12, and 13 × 12 = 156. Two brackets side by side multiply.
The math: one expression, two shapes
Purpose. Rewrite an expression into the shape that's most useful right now: brackets multiplied out, or pulled back in.
The key rule is the distributive law: a number outside a bracket multiplies everything inside.
a(b+c)=ab+ac
In plain words: a rectangle a wide and b + c long splits into two smaller rectangles, a × b and a × c. The total area is the same either way.
So 3(x + 4) = 3x + 12: three lots of x, and three lots of 4. Multiplying brackets out like this is called expanding.
Quick check
From the last lesson: simplify 2x + 5x + 3.
7x³
10x + 3
10x
7x + 3
Show the answer
7x + 3
2x and 5x are like terms: 7x. The 3 has no x, so it stays: 7x + 3.
Two brackets make four rectangles. For (a + b)(c + d), each part of the first bracket meets each part of the second: a × c, a × d, b × c and b × d. Then add the four areas.
So (x + 3)(x + 2) = x² + 2x + 3x + 6. The two middle rectangles are like terms, so it tidies to x² + 5x + 6. Watch it with x = 10, where the four rectangles have real sizes. The picture draws the whole product as one big rectangle, x + 3 down the side and x + 2 across the top, each part drawn to its length. Each step lights one of the four rectangles and writes its area in it; the last adds them up.
Try it now
Then set the first bracket to 20, 3 and the second to 10, 4 and press Use these numbers: it's how 23 × 14 is done by hand.
Symbols and formula. The four-rectangle rule, and the square of a sum:
(a+b)(c+d)=ac+ad+bc+bd(a+b)2=a2+2ab+b2
In plain words: every part of one bracket times every part of the other. Squaring a sum gives the two squares and a middle term, twice a × b.
Two named mistakes.
(a + b)² is not a² + b². The two middle rectangles, ab and ab, are missing: (3 + 4)² is 49, but 3² + 4² is only 25.
A minus in front of a bracket reaches every term: −(x − 3) = −x + 3, not −x − 3.
The grid works for longer brackets too. (x + 1)(x² + x + 2) has six rectangles, two rows of three, where a rhyme for two brackets would stop working.
Quick check
Expand (x + 5)².
x² + 5x + 25
x² + 25
2x + 10
x² + 10x + 25
Show the answer
x² + 10x + 25
(x + 5)(x + 5): x², then x × 5 twice (10x), then 25. So x² + 10x + 25.
Quick check
What is −(2x − 7) without the bracket?
−2x − 7x
−2x − 7
−2x + 7
2x + 7
Show the answer
−2x + 7
The minus reaches both terms: −(2x) is −2x, and −(−7) is +7.
Factoring: expanding in reverse. To factor is to pull out what the terms share. 6x + 9: both terms are 3 times something, so 6x + 9 = 3(2x + 3). Check by multiplying back: 3 × 2x + 3 × 3 = 6x + 9.
A simple quadratic factors by un-expanding. For x² + 5x + 6, look for two numbers that multiply to 6 and add to 5: 2 and 3. So x² + 5x + 6 = (x + 2)(x + 3). Always check by expanding again.
One more named mistake, about fractions. A sum over one bottom splits: (8 + 4)/2 = 8/2 + 4/2. But a bottom that is a sum doesn't: 12/(2 + 4) is 2, while 12/2 + 12/4 is 9.
In your own words
In your own words: why is (a + b)² not equal to a² + b²?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: are two expressions the same?
Purpose. After expanding or factoring by hand, check your work. Two expressions are the same when they give the same number for every input. Python can't try every input, but it can try several. Write each side as a function and subtract: the same expression gives 0 every time.
It runs right here in your browser, with nothing to install.
Three zeros at three different inputs make a slip very unlikely. One nonzero answer is enough to prove a mistake.
Now step through the same check, one line at a time. At each input, watch the program jump into left, come back with a number, jump into right, come back with another, and subtract the two. Two shapes of one expression hand back the same number every time.
The first line matches: a sum over one bottom splits into separate fractions, 6.0 both ways. The second line doesn't: 12 over (2 + 4) is 2.0, but splitting the bottom gives 9.0. Dividing by a sum is not the same as dividing by each part. When you're unsure whether a rewrite is allowed, one line of Python with easy numbers settles it.
f(2) = 3 × 6 = 18 and g(2) = 6 + 4 = 10, so the difference is 8. Not 0, so g isn't the expansion of f: the 3 should multiply the 4 too.
Quick check
Which test best shows two functions f and g are the same expression?
f(0) - g(0) is 0 at x = 0
f(2) is bigger than g(2)
f(x) - g(x) is 0 at several x
f(1) == g(1), at one input
Show the answer
f(x) - g(x) is 0 at several x
Matching at several different inputs makes a slip very unlikely. One input can match by chance.
Choosing inputs for a check. Some inputs hide slips. At x = 0 every term with an x vanishes, so only the constants get compared. At x = 1 every power of x is 1, so x² and x look identical. Good test inputs are a few ordinary, different numbers, like 2, 7 and −3, including a negative so the signs get tested too. Three different inputs that each give a difference of 0 make a wrong expansion very unlikely.
Drill
Find and fix the wrong expansion
expanded(x) should be the expansion of (x + 4) ** 2. Compare it at three inputs to see that it's wrong, then fix it so d1, d2 and d3 are all 0.
In the lesson, your code is checked as you write it.
In your own words
Why does one nonzero difference prove two expressions are different, while three zeros only make them very likely the same?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: a squared error is a bowl
Purpose. A model ŷ = w·x has one weight to choose. Expanding its squared error shows there is exactly one best choice.
The map below is the same in every lesson of this course: a model learning, with the part this lesson's math lives in lit.
For one example with input x and target y, the squared error is (w·x − y)². Expand it, treating w as the letter and x and y as numbers:
(wx−y)2=x2w2−2xyw+y2
In plain words: a number times w², minus a number times w, plus a number. That's a quadratic in w: a bowl.
For x = 2 and y = 6 it's 4w² − 24w + 36. Python confirms both shapes match, and shows the bowl's bottom:
defsq_err(w):
return (w * 2 - 6) ** 2defexpanded(w):
return4 * w ** 2 - 24 * w + 36print(sq_err(1.5) - expanded(1.5), sq_err(10) - expanded(10))
print(sq_err(1), sq_err(2), sq_err(3), sq_err(4), sq_err(5))
The first line prints two zeros: the two shapes agree. The second prints the error at five weights. Plot those five against the weight, and the bowl appears.
Quick check
In the run and the picture above, which weight gives the smallest squared error?
Every weight gives the same error
w = 5, the largest weight tried
w = 1, the smallest weight tried
w = 3, where the error is 0
Show the answer
w = 3, where the error is 0
The errors go 16, 4, 0, 4, 16: down to 0 at w = 3, then up again. That's the bottom of the bowl, where 3 × 2 = 6 hits the target exactly.
Why the bowl matters. A bowl has exactly one lowest point, and training a model is a search for it. In lesson 23 you'll find the bottom straight from the expanded form's three numbers, and in Module 5 by walking downhill, which is how real models learn.
In the real tools. In PyTorch, the library most models are built with, the squared error is a single line, and it can work on many weights at once. Here it is for the five weights above:
Reading the bowl's numbers. In 4w² − 24w + 36, the first number sets how steep the bowl is: bigger inputs make it steeper. The last number, 36, is the loss at w = 0, where the model predicts 0 for everything. And the bottom sits where the w² and w terms balance, which lesson 23 turns into a formula. Predict the bowl's values at three weights before running them.
Quick check
What does this print?
defbowl(w):
return4 * w ** 2 - 24 * w + 36print(bowl(0), bowl(3), bowl(6))
36 0 36
36 0 72
36 3 36
0 36 0
Show the answer
36 0 36
At w = 0 only the 36 is left. At w = 3: 36 − 72 + 36 = 0, the bottom. At w = 6: 144 − 144 + 36 = 36. The bowl is symmetric around 3.
Drill
Expand another squared error
For one example with x = 3 and y = 12, the squared error is (3w − 12)². Set a, b and c to the three numbers of its expansion a·w² + b·w + c, then make expanded(w) use them. The checks compare it with sq_err(w).
defsq_err(w):
return (w * 3 - 12) ** 2
a = 3
b = -12
c = 144defexpanded(w):
return a * w ** 2 + b * w + c
print(sq_err(2) - expanded(2), sq_err(5) - expanded(5))
In the lesson, your code is checked as you write it.
In your own words
Why does expanding (w·x − y)² help when training a model?
Write a sentence or two, then compare it with a good answer in the lesson.
Goes deeper in
Formulas: rewriting and checking formulas in more Python.
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