AI from scratch · Start 3 · Stage 0: start here

Math warm-up

Machine learning papers look scary mostly because of their notation. Underneath, the first few stages use school math: functions, powers, logarithms and adding things up. This lesson goes over exactly those, each with a picture you drag and a box you run, and ends with you reading real ML formulas out loud like sentences. If something here already feels easy, skim it and do the questions.

1. Functions and their graphs

A function takes a number in and gives a number out. \(f(x) = x^2\) says "call the input \(x\), the output is \(x\) times \(x\)": so \(f(3) = 9\). The graph of a function is every pair (input, output) drawn as a dot: across is the input, up is the output. Pick a function and drag \(x\): the yellow dot is \((x, f(x))\).

You'll meet all five again. The line is the taxi model from Start 1. The bowl is what an error looks like as you turn a knob: one lowest point, and training rolls into it. \(e^x\) and \(\ln x\) are the next two sections. The S-curve, called the sigmoid, squeezes any number into the range 0 to 1, so a model can turn a score into a probability (chapter 3 builds a neuron with it).

If \(f(x) = x^2 - 2x\), what is \(f(3)\)?

Put 3 in for every \(x\): \(3^2 - 2 \times 3 = 9 - 6 = 3\).

Pick the sigmoid and drag \(x\) far to the right, then far to the left. What happens to the output?

That's exactly why it's used for "probability of yes": any score, however big or negative, lands strictly between 0 and 1, and a score of 0 means 50/50.

Many functions take several inputs: \(f(a, b) = a \times 4 + b\) is the taxi model's guess for a 4 km ride as you turn both knobs. Stage 1 draws functions of two inputs as landscapes you walk over.

A function turns an input number into an output number, and its graph is every such pair drawn as a dot.

2. Powers, and very big and very small numbers

\(2^5\) means five 2s multiplied: \(2 \times 2 \times 2 \times 2 \times 2 = 32\). Three rules follow just from counting how many copies get multiplied:

ruleexamplewhy
\(a^m \times a^n = a^{m+n}\)\(2^3 \times 2^4 = 2^7 = 128\)3 copies, then 4 more
\(a^{-n} = 1 / a^n\)\(2^{-3} = 1/8 = 0.125\)each step down the powers divides by 2: 8, 4, 2, 1, ½, ¼, ⅛
\(a^{1/2} = \sqrt{a}\)\(9^{1/2} = 3\)\(9^{1/2} \times 9^{1/2} = 9^1\), so it's the number that squares to 9

ML numbers come in wildly different sizes: a learning rate of 0.001, a model with 7,000,000,000 weights. Scientific notation writes them as a number times a power of 10: \(0.001 = 10^{-3}\) and \(7{,}000{,}000{,}000 = 7 \times 10^9\). Code writes the same thing as 1e-3 and 7e9: "e" here means "times ten to the", nothing to do with the number \(e\).

What is \(2^{-3}\) as a decimal?

\(2^{-3} = 1 / 2^3 = 1/8 = 0.125\).

A config file says lr = 3e-4. Write that learning rate as a plain decimal.

\(3 \times 10^{-4} = 3 \times 0.0001 = 0.0003\). 3e-4 is a famously common learning rate for the Adam optimizer (stage 4).

The number \(e \approx 2.718\) is special because \(e^x\) grows at a rate equal to its own value (Calculus 1 shows why that makes it the easy one). You'll mostly see it in \(e^x\), written np.exp(x) in code.

A power counts how many copies are multiplied, and scientific notation tames very big and very small numbers.

3. Logarithms: counting the multiplications

A logarithm answers "what power?". \(\log_2 8 = 3\) because \(2^3 = 8\): it counts how many 2s you multiply to get 8. \(\log_{10} 1000 = 3\) counts the zeros. And the natural log \(\ln x\) is the power of \(e\): \(\ln x = t\) means \(e^t = x\). So \(\ln\) undoes \(e^x\), and the two graphs are mirror images across the dashed line \(y = x\). Drag \(t\):

The one rule that matters most in ML: a log turns multiplying into adding, \(\ln(ab) = \ln a + \ln b\). (It follows from the first power rule: multiplying powers of \(e\) adds the exponents.) A model's probability of a whole dataset is the product of its probabilities for each example: thousands of numbers below 1 multiplied together. That underflows to exactly 0 on a computer, so models work with the sum of the logs instead. Run it:

What is \(\log_2 1024\)? (How many times do you double 1 to reach 1024?)

1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024: ten doublings, so 10. Logs turn huge ranges into small, even steps, which is why plots of training loss often use a log scale.

Three examples each get probability 0.5. What is \(\ln(0.5 \times 0.5 \times 0.5)\)? (\(\ln 0.5 \approx -0.693\).)

\(\ln 0.5 + \ln 0.5 + \ln 0.5 = 3 \times (-0.693) = -2.079\). Logs of probabilities are always negative or zero (since probabilities are at most 1), which is why the loss in chapter 5, cross-entropy, puts a minus sign in front.

What is \(\ln 1\)?

\(e^0 = 1\), so \(\ln 1 = 0\). A model that gives the right answer probability 1 has a log-probability of 0: no loss at all.

A logarithm counts multiplications, so it turns multiplying into adding.

Why ML works with logs of probabilities
  1. A model's probability for a whole dataset is a product: one probability per example, all multiplied.
  2. Say a model gives each of 1,000 examples probability 0.5. The product is \(0.5^{1000} \approx 9 \times 10^{-302}\): the computer can just about hold that.
  3. With 1,100 examples it's smaller than the smallest number a computer stores, and it comes out as exactly 0. Every model would score the same, 0, and nothing could be compared.
  4. Take the log instead: \(\ln(0.5^{1000}) = 1000 \times \ln 0.5 \approx -693\), an ordinary number, and it stays ordinary for a billion examples.
  5. Because a log only ever goes up when its input goes up, the model with the bigger product also has the bigger sum of logs. Nothing is lost by switching, and that's why losses in ML are sums of logs.

4. The Σ sign is a loop

The big Greek S, \(\Sigma\) (sigma), means "add these up". The bits around it say what to add:

\[ \sum_{i=1}^{4} i^2 = 1^2 + 2^2 + 3^2 + 4^2 = 30 \]

Read it as: "for \(i\) from 1 to 4, add up \(i^2\)". Underneath is where the counter starts, on top is where it stops, and to the right is what you add each time. It's exactly the loop from Start 2. Change the sum below:

Datasets are written with a counter too: \(x_1, x_2, \dots, x_n\) are the \(n\) examples, and \(x_i\) is "the \(i\)-th one". With that, the mean is

\[ \bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i \]

"x-bar is one over n times the sum of all the x's": add them up, divide by how many. (The 1/n out front does the dividing.) And a product of many terms uses the big Greek P, \(\prod\), the same way.

What is \(\sum_{i=1}^{4} 2i\)?

\(2 + 4 + 6 + 8 = 20\). Or take the 2 outside: \(2 \times (1 + 2 + 3 + 4) = 2 \times 10\). Constants can always come out of a sum, a trick that tidies up a lot of derivations.

Set the sum to \(1/2^i\) and slide \(n\) up to 12. If you kept adding forever, what number would the sum get closer and closer to?

\(\frac12 + \frac14 + \frac18 + \dots\) heads to 1: each new term covers half the gap that's left. Infinitely many terms can add up to a finite number. Stage 4's momentum optimizer is built on a sum just like this one.

Σ is a loop written in math: start, stop, and what to add each time.

5. The symbols you'll meet

ML borrows Greek letters for its knobs and settings. There are only a handful, and each one is used for the same thing almost everywhere:

symbolsay itusually means
\(w, b\)w, bweights and bias: a model's knobs
\(\theta\)thetaall the knobs together
\(\eta\) or \(\alpha\)eta, alphalearning rate: how big a step training takes
\(\lambda\)lambdahow hard to punish big weights (regularization, stage 3)
\(\sigma\)sigma (small)the sigmoid function, or a spread (standard deviation)
\(\mu\)mua mean
\(\epsilon\)epsilona tiny number, or noise
\(\hat{y}\)y-hatthe model's guess (the true answer is plain \(y\))
\(L\)Lthe loss: one number saying how wrong the model is
\(\nabla L\)grad L, the gradientwhich way each knob should move to raise the loss (stage 1)
\(|x|\)the absolute value of xx without its sign, its distance from 0: \(|-3| = |3| = 3\)
\(\approx\), \(\leftarrow\), \(\in\)about, becomes, is in\(x \in [0, 1]\): x is between 0 and 1; \(w \leftarrow w - 1\): w becomes w − 1
\(\mathbf{x}\), \(W\)bold x, capital Wa list of numbers (a vector) and a table of numbers (a matrix), chapter 1

Don't memorize the table: come back to it. After a few lessons the letters read like words.

A handful of Greek letters do the same jobs almost everywhere: come back to the table until they read like words.

6. Reading a formula out loud

Every formula is a sentence. Read it left to right, say each symbol's name, and turn it into a recipe. Try each one before revealing.

Read this one out loud, as a recipe: \[ \hat{y} = \sigma(w x + b) \]

"y-hat equals sigma of w x plus b." Recipe: multiply the input by the weight, add the bias, push the result through the S-curve. The output is the model's guess, a number between 0 and 1. That is one neuron, the whole of chapter 3.

And this one: \[ L = \frac{1}{n} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2 \]

"L equals one over n times the sum, for i from 1 to n, of y-hat i minus y i, squared." Recipe: for every example, take the guess minus the truth and square it; add those up; divide by how many. That's the mean squared error you computed in Start 2's last box.

And the most important line in all of ML: \[ \theta \leftarrow \theta - \eta \, \nabla L(\theta) \]

"theta becomes theta minus eta times the gradient of L at theta." Recipe: find which way each knob would raise the loss, step every knob a small amount (\(\eta\)) the other way, repeat. That's gradient descent, the "Let the computer train it" button from Start 1. Stage 1 is about computing \(\nabla L\).

Do one step of that by hand: the knob is \(\theta = 3\), the learning rate is \(\eta = 0.1\), and the gradient is \(\nabla L = 4\). What is \(\theta\) after the step?

\(3 - 0.1 \times 4 = 3 - 0.4 = 2.6\). The gradient is positive, meaning a bigger \(\theta\) gives a bigger loss, so the knob moves down.

Here are all three formulas as code. Notice how directly each line matches its formula:

One small trap: math counts examples from 1 (\(x_1\) to \(x_n\)), code counts from 0 (xs[0] to xs[n - 1]). Same examples, shifted labels.

Every formula is a sentence and a recipe: read it left to right and it turns into code.

Where it breaks: when the math is fine and the computer isn't

7. What to carry forward

All lessons: AI from scratch.

Last updated