Discover: two loops in a famous algorithm
In 2015 Sergey Ioffe and Christian Szegedy at Google introduced batch normalisation, a layer that rescales the numbers flowing through a network so that, over each mini-batch, they have mean 0 and variance 1. On an image classifier it reached the same accuracy in 14 times fewer training steps, and ResNet (Chamber 4) puts one after every convolution. The whole method is four lines:
Spotted in the wild
You can already read much of this. The arrows are assignments and the hat marks a modified value (Chamber 1). is a set, the mini-batch (Chamber 2). is a function with its parameters in the subscript (Chamber 4). What's new is the tall Greek letter in the first two lines: , capital sigma. Each one is a loop. The first adds up the values in the batch, and the second adds up their squared distances from the mean.
This chamber teaches you to read, write and manipulate those loops. You'll see why the sits outside, prove the fact the paper uses to check its own work, and run the algorithm by hand. Start with the first line.
A mini-batch holds values: , and . Using the first line of Algorithm 1, , what is ?
Learn: the anatomy of a sum
Every sum has four parts:
Read it as “the sum from equals 1 to of sub ”. Below the sit the index and its lower bound; above it, the upper bound; after it, the term, which usually depends on the index. The index takes every integer value from the lower bound to the upper bound, both included, and the terms are added. For example,
A sum from to has terms, not . That “+ 1” is the fencepost problem: a fence 10 metres long with a post every metre needs 11 posts. In Python it shows up as the + 1 inside range, which stops just before its second argument:
total = 0 # an empty sum is 0
for i in range(1, n + 1): # i = 1, 2, ..., n
total += i**2 # the term
or in one line, sum(i**2 for i in range(1, n + 1)). Three more habits of the notation:
- The index is a dummy variable. and are the same sum, just as renaming a loop variable doesn't change a loop. The index means nothing outside its sum, so write with brackets, never .
- An empty sum is 0. If the upper bound is below the lower bound, there are no terms, and the total never leaves its starting value: .
- Bounds are often left out. means “over every that makes sense here”, usually all the data.
- “the sum from i equals 1 to n of x sub i”Add for . Below the : the index and where it starts. Above: where it stops. Both ends are included.
- “the index”The dummy variable: a loop counter that exists only inside the sum. Renaming it changes nothing.
- “the sum over i of x sub i”Bounds left out: add over every that makes sense in context, usually all the data.
- “the sum over i in B of x sub i”Add over the elements of a set, such as a mini-batch . There are terms.
- “the sum over j not equal to i”A condition under the : add over every except .
- “the double sum over i and j of a sub i j”A sum of sums: two nested loops over a grid of terms. For finite sums the two sums can be swapped.
- “x 1 plus dots plus x n”An ellipsis: “and so on, following the pattern”. Centred dots go between operations, low dots in lists.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “the sum from i equals 1 to n of x sub i” | Add for . Below the : the index and where it starts. Above: where it stops. Both ends are included. | ||
| “the index” | The dummy variable: a loop counter that exists only inside the sum. Renaming it changes nothing. | ||
| “the sum over i of x sub i” | Bounds left out: add over every that makes sense in context, usually all the data. | ||
| “the sum over i in B of x sub i” | Add over the elements of a set, such as a mini-batch . There are terms. | ||
| “the sum over j not equal to i” | A condition under the : add over every except . | ||
| “the double sum over i and j of a sub i j” | A sum of sums: two nested loops over a grid of terms. For finite sums the two sums can be swapped. | ||
| “x 1 plus dots plus x n” | An ellipsis: “and so on, following the pattern”. Centred dots go between operations, low dots in lists. |
Expand and evaluate .
Now sculpt some sums yourself. Pick a term, set the bounds, and watch the notation, the expansion and the Python change together. Each of the three targets can be reached in more than one way, and product mode is there to explore when you reach products later in this chamber.
Interactive lab
Sigma sculptor
Term by term
Closed form (with n = 5):
Pick a term and move the bounds until the sum lands on a target.
Term
terms
5
targets hit
0 / 3
The same loop in Python
sum(i for i in range(1, 5 + 1))
range(a, b + 1) gives a, a + 1, …, b. The + 1 is there because range stops just before its second argument, while includes both bounds. Forgetting it is the classic off-by-one error.
Current term: i.
Learn: the algebra of sums
Sums obey three rules, and each one is ordinary arithmetic applied to a long line of additions.
- A constant term: . Adding to itself times gives .
- A constant factor comes out: . Every term has the factor , so factor it out once: . That's why batch normalisation writes rather than : they're equal, and the first divides once instead of times.
- A sum of terms splits: . Addition can be reordered, so gather all the 's, then all the 's.
Together they say that sums are linear:
Two more moves change the bounds rather than the terms. You can split the range, , which lets you compute as . And you can shift the index. Substituting gives
The bounds go down by one and the subscript goes up by one, so the terms are the same. This is exactly the translation between a paper that counts from 1 and Python, which counts from 0: the paper's is x[j].
A proof: deviations from the mean add up to zero
Here is the rulebook in action, on the first fact the batch normalisation paper uses to check its own algorithm.
Claim. Let be the mean of . Then .
Proof. The key observation is that has no in it: inside the sum it is a constant. Split the sum (rule 3), then use the constant rule (rule 1):
By the definition of the mean, . So the two terms cancel, and the sum is 0.
Every step names its rule, and the only idea was to notice what doesn't depend on the index. In batch normalisation the normalised values are : deviations from the mean, divided by a constant. Pull the constant out and this proof shows , exactly as the paper says.
Which expression equals ?
Learn: Gauss's formula, two ways
What is ? Here are two routes to the answer. The first finds the formula; the second proves one you already have.
The derivation: pair the terms
Write the sum forwards, then backwards, and add the two lines column by column:
Every column adds up to , and there are columns, so :
The same trick works in notation. As runs from 1 to , the number runs through the same values backwards, so as well. Add the two expressions for and use linearity: , by the constant rule.
The proof: induction
Pairing is clever, but it doesn't generalise easily. A more mechanical technique proves statements about every positive integer , and it fits sums perfectly. It's called proof by induction, and it joins the techniques of Chamber 3. You prove two things:
- Base case: the statement is true for .
- Inductive step: if it is true for some , then it is true for .
Then it's true for every : true for 1, so for 2, so for 3, and so on, like a line of dominoes where the first falls and each knocks over the next.
Claim. For every integer , .
Proof. Base case. For the sum has one term, 1, and . They agree.
Inductive step. Suppose that for some we have . This is the inductive hypothesis. Split the last term off the sum for , then use the hypothesis:
That is the formula with . The statement holds for , and whenever it holds for it holds for , so by induction it holds for every .
Notice where the sum notation did the work: splitting off the last term is what connects case to case . The same pattern proves many sum formulas, such as (so , one of the lab's targets) and , which you'll assemble yourself at the end of the chamber.
Learn: the geometric series
In a geometric series each term is the previous one multiplied by a fixed ratio :
The derivation: multiply and subtract
Call the sum and multiply it by . Every power moves up by one:
Subtract the second line from the first. Everything in the middle cancels, leaving . Factor out to get , and divide by , which is allowed because . In notation, the multiplication is an index shift: , and the two sums share every term except and .
With and you get : every bit of a 10-bit number switched on. When , the power shrinks to 0 as grows, and the infinite series settles at . (What “settles” means precisely is the limit of Chamber 7.)
Geometric series turn up all over machine learning:
- In reinforcement learning, a reward received steps in the future is discounted by , and the return is . With a reward of 1 at every step and , the return is , so sets how far ahead the agent effectively looks.
- Adam's running average (Chamber 1) gives the gradient from steps ago a weight of . Over steps these weights add up to : exactly the denominator in Adam's bias correction . Chamber 9 takes this further.
Learn: sums over sets, with conditions, and sums of sums
The index doesn't have to run over a range of integers. It can run over a set: adds for every in the mini-batch , and the mean loss over the batch is , with the batch size from Chamber 2. It can also carry conditions. adds every except , and adds only the examples whose label is 1. In code, a condition under the becomes an if inside the loop.
Here is a famous example, from the paper that introduced word2vec's skip-gram model:
Spotted in the wild
Read it from the outside in. The text is a sequence of words . The outer sum visits every position . The inner sum visits the offsets from to , the window around the word, and the condition skips the word itself. Each term is the log probability the model gives to seeing the neighbour near the centre word , and the turns the total into an average. Training makes this number as large as possible.
In word2vec's objective, the inner sum runs over . With window size , how many terms does it have (for a word far from either end of the text)?
That was a double sum: a sum whose term is itself a sum. It's two nested loops. Over a grid of numbers with rows and columns,
The left side adds row by row and the right side column by column. Both add every entry once, so for finite sums you may swap the order freely. When the term splits into a part for and a part for , the double sum factorises: .
When the inner bounds depend on the outer index, swapping takes care. adds the lower triangle of the grid, the pairs with . To add the same triangle column by column, fix first; then runs from to :
Draw the triangle and both sides are obvious. You'll meet this shape again in language models, where a causal attention mask lets position look only at positions .
Learn: products, factorials and logs
Capital pi does for multiplication what capital sigma does for addition:
read “the product from equals 1 to of sub ”. An empty product is 1, for the same reason an empty sum is 0: a running product starts at 1, and multiplying by nothing leaves it there. The most famous product is the factorial, , the number of ways to put things in order: . By the empty-product rule, .
- “the product from i equals 1 to n of x sub i”Multiply the terms instead of adding them. An empty product is 1.
- “n factorial”, the number of ways to put things in order. By the empty-product rule, .
- “the log of the product of p sub i”Equals : a product of many small probabilities becomes a sum that a computer can store.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “the product from i equals 1 to n of x sub i” | Multiply the terms instead of adding them. An empty product is 1. | ||
| “n factorial” | , the number of ways to put things in order. By the empty-product rule, . | ||
| “the log of the product of p sub i” | Equals : a product of many small probabilities becomes a sum that a computer can store. |
Products matter in ML because probabilities multiply. If a model gives probability to each of independent observations, the probability of all of them together, the likelihood, is . That is a problem for a computer. With and , the product is , smaller than the smallest positive number a standard float can hold, so Python returns exactly 0.0.
Chamber 4's product rule for logs fixes it. Apply over and over, one factor at a time:
The log-likelihood of those 1100 observations is , a perfectly ordinary number. And because is strictly increasing, whatever parameters make the log-likelihood largest also make the likelihood largest. That's why papers maximise sums of logs, and why a loss function is so often a of s.
Learn: mean and variance are sums
Two of the most common expressions in all of statistics are sums you can now read. The mean is the average, and the variance is the average squared distance from the mean:
Read them as “mu” and “sigma squared”. The standard deviation measures spread in the same units as the data. Batch normalisation's first two lines are exactly these, computed over one mini-batch and labelled with a subscript .
Take the batch from the quiz. The mean is 5, the deviations are (which add up to 0, as proved above), their squares are , and the variance is . The third line of Algorithm 1 divides each deviation by , so the normalised values have mean 0 and a spread of about 1, whatever the scale of the numbers you started with.
- “mu, the mean”The average, . Also written .
- “sigma squared, the variance”The average squared distance from the mean: how spread out the values are.
- “sigma, the standard deviation”: the spread in the same units as the data.
- “mu B and sigma squared B”The mean and variance of one mini-batch , as in batch normalisation.
- “x hat sub i, normalised”In batch normalisation, minus the batch mean, divided by the batch standard deviation: how many standard deviations sits from the mean.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “mu, the mean” | The average, . Also written . | ||
| “sigma squared, the variance” | The average squared distance from the mean: how spread out the values are. | ||
| “sigma, the standard deviation” | : the spread in the same units as the data. | ||
| “mu B and sigma squared B” | The mean and variance of one mini-batch , as in batch normalisation. | ||
| “x hat sub i, normalised” | In batch normalisation, minus the batch mean, divided by the batch standard deviation: how many standard deviations sits from the mean. |
Two practical notes. First, there's another way to compute the variance, as the mean of the squares minus the square of the mean: . You'll prove it in Your turn. Second, statisticians often divide by instead of when estimating the variance of a whole population from a sample (Bessel's correction). Algorithm 1 divides by . The paper switches to only for the statistics it keeps for use after training. Tools differ too: NumPy's np.var divides by by default, while Python's statistics.variance divides by . When you implement a formula, check which one it means.
Read beyond the course
Lecture notes · free online · ~15 min
Summation NotationPaul Dawkins, Paul's Online Math Notes · Calculus I, Appendix A.8
A compact reference page: the notation, the linearity rules, the warning about products and quotients, and the standard formulas for , and with worked examples. Keep it open while you do this chamber's exercises.
Book · free online · ~30 min
Book of ProofRichard Hammack · Chapter 10: Mathematical Induction (§10.1)
Induction, carefully, with many examples that are sum formulas like the ones in this chamber. Read §10.1 now while the dominoes are fresh, and try a few of the exercises at the end of the chapter.
Book · free online · ~20 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Chapter 6, §6.4.2–6.4.3: Empirical Means and Covariances; Three Expressions for the Variance
Three ways to write the variance: the definition, the “raw-score” formula you'll prove in this chamber, and a double sum over all pairs of data points. Skim past the vectors and expectations if they're unfamiliar. The sums are what matter here.
Book · free online · ~25 min
Dive into Deep LearningAston Zhang, Zachary C. Lipton, Mu Li & Alexander J. Smola · §8.5: Batch Normalization
Batch normalisation again, written as sums over a set: . Comparing it with the paper's Algorithm 1 is good practice in recognising one idea in two notations, and the section includes runnable code.
Papers and lectures
The batch normalisation paper is a good one to open now. Read Section 3 up to Algorithm 1 on page 3, and the paragraph just after it. The paragraph before the algorithm sets up the notation (, and ), and the one after explains why the normalised values have mean 0 and variance 1, using the sums and . Then flip back to the introduction, where the training objective appears as a sum over the whole training set, . Skip the derivatives that close Section 3, and the experiments, for now.
For word2vec, read Section 2 up to Eq. (2). Eq. (1) is the double sum you've just met, and Eq. (2) is a softmax, whose denominator is a sum over the entire vocabulary. The paper's point is that this sum is too expensive when the vocabulary has millions of words, and much of the rest of the paper is about ways around it.
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate ShiftSergey Ioffe, Christian Szegedy · ICML, 2015Four lines of sums and assignments that became a standard layer in deep networks. It's also a model of how to present an algorithm: inputs, outputs and a short box of pseudocode.
Distributed Representations of Words and Phrases and their CompositionalityTomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean · NIPS, 2013The skip-gram paper behind word2vec's word vectors, whose arithmetic famously works: in the paper's own example, vec(“Madrid”) − vec(“Spain”) + vec(“France”) is closer to vec(“Paris”) than to any other word vector. Its objective is a double sum with conditions under the Σ.
Decode the paper · Algorithm 1, Section 3
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate ShiftSergey Ioffe, Christian Szegedy · ICML, 2015
The Batch Normalizing Transform, applied to one activation over a mini-batch . The paper labels its four lines “mini-batch mean”, “mini-batch variance”, “normalize” and “scale and shift”. Match each symbol to its job.
Options
Decode the paper · Eq. (1), Section 2
Distributed Representations of Words and Phrases and their CompositionalityTomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean · NIPS, 2013
The skip-gram objective behind word2vec's word vectors: “given a sequence of training words , the objective of the Skip-gram model is to maximize the average log probability” below. Two sums, one with conditions under it.
Options
Watch
A short introduction to reading and expanding a . Watch it if the anatomy of a sum still feels shaky, and pause before each expansion to do it yourself.
Andrew Ng writes out batch normalisation's equations step by step. Watch for the same sums in slightly different clothes: he writes the -th example as , with the bracketed superscript of Chamber 1, and calls the result .
Your turn
Expand, translate, prove and code. The two proofs use this chamber's big ideas, induction and linearity, and the coding problems end with two real algorithms run by hand.
Match · Notation ↔ Written out
Expand it
Match each expression to its expansion. Watch the bounds: both ends are included.
Options
Match · Maths ↔ Python
From Σ to Python
Match each formula to the Python that computes it (with import math). The lists x and p hold and at positions 0 to n - 1.
Options
Proofs
Put the induction proof in order, then prove the variance shortcut yourself with the algebra of sums.
Proof puzzle
Odd numbers add up to squares
Claim
For every integer , the sum of the first odd numbers is a perfect square:
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
The mean of the square minus the square of the mean
Claim
Let be real numbers with mean . Prove that their variance can be computed as
Your typeset proof appears here.
Code it up
Every becomes a loop and every condition an if. Read each statement's bounds carefully: they're where most bugs hide.
Problem 13·Warm-up
Plus, minus, plus, minus
Compute
The factor is when is even and when is odd, so the sum is . Give the exact integer.
Problem 14·Standard
Apply the paper: batch norm by hand
Batch normalisation's Algorithm 1 transforms a mini-batch :
Take values for (so , , , , …), with , and .
What is ? Give it rounded to 4 decimal places.
Problem 15·Challenge
Apply the paper: a toy skip-gram objective
word2vec's skip-gram model is trained to maximise the average log probability (Eq. 1 of the paper)
where is the training text and is the window size. The paper leaves one condition implicit: we also require , so neighbours that would fall off either end of the text are skipped.
Build a toy version. The vocabulary is the integers , the text has words , and the window is . In place of the paper's Eq. (2), use the toy model
the probability that word appears near word . The log is natural. Compute , rounded to 4 decimal places.
Key takeaways
- A is a loop. adds the terms for every integer from to , both included: terms, which is
range(a, b + 1)in Python. An empty sum is 0 and an empty product is 1. - Sums are linear. Constants come out, sums of terms split, . Ranges split and indices shift. Sums do not split over products or squares.
- Two formulas to know: (by pairing, or by induction) and (multiply and subtract).
- Indices can run over sets and carry conditions, as in and . Double sums are nested loops, and finite ones can be swapped.
- Logs turn products into sums: , which is why likelihoods become sums of logs.
- Mean and variance are sums, and batch normalisation's Algorithm 1 is those two sums followed by a normalisation and a learned scale and shift.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
Which of these equals for every list ?
What is ?
Use Gauss's formula to compute .
Compute .
Which of these is not true for all lists of numbers?
Compute .
A model gives probability to each of 1100 independent observations. Why do papers maximise rather than ?
What is the variance of the values ?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Sigma sculptor (+40 XP)
- Bonus: Problem 13: Plus, minus, plus, minus (+20 XP)
- Bonus: Problem 14: Apply the paper: batch norm by hand (+35 XP)
- Bonus: Problem 15: Apply the paper: a toy skip-gram objective (+50 XP)
- Bonus: Proof: Odd numbers add up to squares (+25 XP)
- Bonus: Proof: The mean of the square minus the square of the mean (+40 XP)
- Bonus: Decode the paper (1) (+30 XP)
- Bonus: Decode the paper (2) (+30 XP)
- Bonus: Match: Expand it (+25 XP)
- Bonus: Match: From Σ to Python (+25 XP)