Skip to content
AriadneTechnology

The Middle Ring · Chamber 5 of 9

Σ and Π: Loops Written in Maths

Sigma and pi notation, indices and bounds, and the algebra of sums behind every loss function.

40 min 60 XP + 12 questions + 1 challengeNotationVideoPapersProofsCodeLab

In this chamber you will

  • Expand and evaluate Σ and Π expressions by hand and in code
  • Pull constants out, split sums and shift indices
  • Derive Gauss's formula and the geometric series
  • Read batch normalisation's equations symbol by symbol
DiscoverLearnRead beyondPapers & lecturesYour turn

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

μB←1m∑i=1mxi// mini-batch meanσB2←1m∑i=1m(xi−μB)2// mini-batch variancex^i←xi−μBσB2+ϵ// normalizeyi←γx^i+β≡BNγ,β(xi)// scale and shift\begin{aligned} \mu_{\mathcal{B}} &\leftarrow \frac{1}{m}\sum_{i=1}^{m} x_i && \text{// mini-batch mean} \\[4pt] \sigma_{\mathcal{B}}^2 &\leftarrow \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu_{\mathcal{B}})^2 && \text{// mini-batch variance} \\[4pt] \widehat{x}_i &\leftarrow \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}} && \text{// normalize} \\[4pt] y_i &\leftarrow \gamma\widehat{x}_i + \beta \equiv \mathrm{BN}_{\gamma,\beta}(x_i) && \text{// scale and shift} \end{aligned}
Ioffe & Szegedy (2015), “Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift”, Algorithm 1

You can already read much of this. The arrows are assignments and the hat marks a modified value (Chamber 1). B\mathcal{B} is a set, the mini-batch (Chamber 2). BNγ,β\mathrm{BN}_{\gamma,\beta} is a function with its parameters in the subscript (Chamber 4). What's new is the tall Greek letter in the first two lines: ∑\sum, capital sigma. Each one is a loop. The first adds up the mm 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 1m\frac{1}{m} sits outside, prove the fact the paper uses to check its own work, and run the algorithm by hand. Start with the first line.

Quick check +20 XP

A mini-batch holds m=3m = 3 values: x1=2x_1 = 2, x2=4x_2 = 4 and x3=9x_3 = 9. Using the first line of Algorithm 1, μB←1m∑i=1mxi\mu_{\mathcal{B}} \leftarrow \frac{1}{m}\sum_{i=1}^{m} x_i, what is μB\mu_{\mathcal{B}}?

DiscoverLearnRead beyondPapers & lecturesYour turn

Learn: the anatomy of a sum

Every sum has four parts:

∑i=1n⏟add, for i = 1 to nxi⏟the term  =  x1+x2+⋯+xn.\underbrace{\sum_{i=1}^{n}}_{\text{add, for } i \,=\, 1 \text{ to } n} \underbrace{x_i}_{\text{the term}} \;=\; x_1 + x_2 + \cdots + x_n.

Read it as “the sum from ii equals 1 to nn of xx sub ii”. Below the Σ\Sigma sit the index ii 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,

∑i=14i2=1+4+9+16=30,∑k=032k=1+2+4+8=15.\sum_{i=1}^{4} i^2 = 1 + 4 + 9 + 16 = 30, \qquad \sum_{k=0}^{3} 2^k = 1 + 2 + 4 + 8 = 15.

A sum from aa to bb has b−a+1b - a + 1 terms, not b−ab - a. 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:

Python
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. ∑i=1nxi\sum_{i=1}^{n} x_i and ∑k=1nxk\sum_{k=1}^{n} x_k are the same sum, just as renaming a loop variable doesn't change a loop. The index means nothing outside its sum, so write ∑i(xi+i)\sum_{i}(x_i + i) with brackets, never ∑ixi+i\sum_i x_i + i.
  • 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: ∑i=10xi=0\sum_{i=1}^{0} x_i = 0.
  • Bounds are often left out. ∑ixi\sum_i x_i means “over every ii that makes sense here”, usually all the data.
Sigma notation
  • ∑i=1nxi\sum_{i=1}^{n} x_i“the sum from i equals 1 to n of x sub i”
    Add xix_i for i=1,2,…,ni = 1, 2, \ldots, n. Below the Σ\Sigma: the index and where it starts. Above: where it stops. Both ends are included.
    ∑i=13i=6\sum_{i=1}^{3} i = 6
  • ii“the index”
    The dummy variable: a loop counter that exists only inside the sum. Renaming it changes nothing.
    ∑i=1nxi=∑k=1nxk\sum_{i=1}^{n} x_i = \sum_{k=1}^{n} x_k
  • ∑ixi\sum_{i} x_i“the sum over i of x sub i”
    Bounds left out: add over every ii that makes sense in context, usually all the data.
  • ∑i∈Bxi\sum_{i \in \mathcal{B}} x_i“the sum over i in B of x sub i”
    Add over the elements of a set, such as a mini-batch B\mathcal{B}. There are ∣B∣|\mathcal{B}| terms.
    1∣B∣∑i∈Bℓi\frac{1}{|\mathcal{B}|}\sum_{i \in \mathcal{B}} \ell_i
  • ∑j≠ixj\sum_{j \ne i} x_j“the sum over j not equal to i”
    A condition under the Σ\Sigma: add over every jj except j=ij = i.
    ∑j≠ixj=∑jxj−xi\sum_{j \ne i} x_j = \sum_j x_j - x_i
  • ∑i=1m∑j=1naij\sum_{i=1}^{m}\sum_{j=1}^{n} a_{ij}“the double sum over i and j of a sub i j”
    A sum of sums: two nested loops over a grid of mnmn terms. For finite sums the two sums can be swapped.
  • x1+⋯+xnx_1 + \cdots + x_n“x 1 plus dots plus x n”
    An ellipsis: “and so on, following the pattern”. Centred dots ⋯\cdots go between operations, low dots …\ldots in lists.
    1+2+⋯+n1 + 2 + \cdots + n
Quick check +20 XP

Expand and evaluate ∑k=25(2k−1)\sum_{k=2}^{5} (2k - 1).

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

A sum is a loop. Choose what to add (the term) and where the index i starts and stops (the bounds). Watch the notation, the expansion and the Python change together.
Targets1003851023
∑i=15i=15\sum_{i=1}^{5} i = 15

Term by term

1+2+3+4+5=151 + 2 + 3 + 4 + 5 = 15

Closed form (with n = 5): n(n+1)2=5⋅62\frac{n(n+1)}{2} = \frac{5 \cdot 6}{2}

Pick a term and move the bounds until the sum lands on a target.

Term

lower bound a
1
upper bound b
5

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 ∑i=ab\sum_{i=a}^{b} includes both bounds. Forgetting it is the classic off-by-one error.

Current term: i.

Challenge: Sigma sculptorBuild a sum that hits each of the three target values.+40 XP

Learn: the algebra of sums

Sums obey three rules, and each one is ordinary arithmetic applied to a long line of additions.

  1. A constant term: ∑i=1nc=nc\sum_{i=1}^{n} c = nc. Adding cc to itself nn times gives ncnc.
  2. A constant factor comes out: ∑i=1nc xi=c∑i=1nxi\sum_{i=1}^{n} c\,x_i = c\sum_{i=1}^{n} x_i. Every term has the factor cc, so factor it out once: cx1+⋯+cxn=c(x1+⋯+xn)c x_1 + \cdots + c x_n = c(x_1 + \cdots + x_n). That's why batch normalisation writes 1m∑i=1mxi\frac{1}{m}\sum_{i=1}^{m} x_i rather than ∑i=1mxim\sum_{i=1}^{m} \frac{x_i}{m}: they're equal, and the first divides once instead of mm times.
  3. A sum of terms splits: ∑i=1n(xi+yi)=∑i=1nxi+∑i=1nyi\sum_{i=1}^{n} (x_i + y_i) = \sum_{i=1}^{n} x_i + \sum_{i=1}^{n} y_i. Addition can be reordered, so gather all the xx's, then all the yy's.

Together they say that sums are linear:

∑i=1n(a xi+b yi)=a∑i=1nxi+b∑i=1nyi.\sum_{i=1}^{n} (a\,x_i + b\,y_i) = a\sum_{i=1}^{n} x_i + b\sum_{i=1}^{n} y_i.

Two more moves change the bounds rather than the terms. You can split the range, ∑i=1nxi=∑i=1kxi+∑i=k+1nxi\sum_{i=1}^{n} x_i = \sum_{i=1}^{k} x_i + \sum_{i=k+1}^{n} x_i, which lets you compute ∑i=1120i\sum_{i=11}^{20} i as ∑i=120i−∑i=110i=210−55=155\sum_{i=1}^{20} i - \sum_{i=1}^{10} i = 210 - 55 = 155. And you can shift the index. Substituting j=i−1j = i - 1 gives

∑i=1nxi=∑j=0n−1xj+1.\sum_{i=1}^{n} x_i = \sum_{j=0}^{n-1} x_{j+1}.

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 xj+1x_{j+1} 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 xˉ=1n∑i=1nxi\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i be the mean of x1,…,xnx_1, \ldots, x_n. Then ∑i=1n(xi−xˉ)=0\sum_{i=1}^{n} (x_i - \bar{x}) = 0.

Proof. The key observation is that xˉ\bar{x} has no ii in it: inside the sum it is a constant. Split the sum (rule 3), then use the constant rule (rule 1):

∑i=1n(xi−xˉ)=∑i=1nxi−∑i=1nxˉ=∑i=1nxi−nxˉ.\sum_{i=1}^{n} (x_i - \bar{x}) = \sum_{i=1}^{n} x_i - \sum_{i=1}^{n} \bar{x} = \sum_{i=1}^{n} x_i - n\bar{x}.

By the definition of the mean, nxˉ=n⋅1n∑i=1nxi=∑i=1nxin\bar{x} = n \cdot \frac{1}{n}\sum_{i=1}^{n} x_i = \sum_{i=1}^{n} x_i. So the two terms cancel, and the sum is 0. ■\blacksquare

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 x^i=(xi−μB)/σB2+ϵ\widehat{x}_i = (x_i - \mu_{\mathcal{B}}) / \sqrt{\sigma^2_{\mathcal{B}} + \epsilon}: deviations from the mean, divided by a constant. Pull the constant out and this proof shows ∑i=1mx^i=0\sum_{i=1}^{m} \widehat{x}_i = 0, exactly as the paper says.

Quick check +20 XP

Which expression equals ∑i=1n(3xi+2)\sum_{i=1}^{n} (3x_i + 2)?

Learn: Gauss's formula, two ways

What is 1+2+3+⋯+n1 + 2 + 3 + \cdots + n? 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 SS forwards, then backwards, and add the two lines column by column:

S=1+2+  ⋯  +(n−1)+nS=n+(n−1)+  ⋯  +2+12S=(n+1)+(n+1)+  ⋯  +(n+1)+(n+1)\begin{array}{rcccccccc} S & = & 1 & + & 2 & + \;\cdots\; + & (n-1) & + & n \\ S & = & n & + & (n-1) & + \;\cdots\; + & 2 & + & 1 \\ \hline 2S & = & (n+1) & + & (n+1) & + \;\cdots\; + & (n+1) & + & (n+1) \end{array}

Every column adds up to n+1n + 1, and there are nn columns, so 2S=n(n+1)2S = n(n+1):

∑i=1ni=n(n+1)2.\sum_{i=1}^{n} i = \frac{n(n+1)}{2}.

The same trick works in Σ\Sigma notation. As ii runs from 1 to nn, the number n+1−in + 1 - i runs through the same values backwards, so S=∑i=1n(n+1−i)S = \sum_{i=1}^{n} (n + 1 - i) as well. Add the two expressions for SS and use linearity: 2S=∑i=1n(i+(n+1−i))=∑i=1n(n+1)=n(n+1)2S = \sum_{i=1}^{n} \big(i + (n + 1 - i)\big) = \sum_{i=1}^{n} (n+1) = n(n+1), 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 nn, and it fits sums perfectly. It's called proof by induction, and it joins the techniques of Chamber 3. You prove two things:

  1. Base case: the statement is true for n=1n = 1.
  2. Inductive step: if it is true for some n=kn = k, then it is true for n=k+1n = k + 1.

Then it's true for every nn: 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 n≥1n \ge 1, ∑i=1ni=n(n+1)2\sum_{i=1}^{n} i = \frac{n(n+1)}{2}.

Proof. Base case. For n=1n = 1 the sum has one term, 1, and 1⋅22=1\frac{1 \cdot 2}{2} = 1. They agree.

Inductive step. Suppose that for some k≥1k \ge 1 we have ∑i=1ki=k(k+1)2\sum_{i=1}^{k} i = \frac{k(k+1)}{2}. This is the inductive hypothesis. Split the last term off the sum for k+1k + 1, then use the hypothesis:

∑i=1k+1i=∑i=1ki+(k+1)=k(k+1)2+(k+1)=(k+1)(k2+1)=(k+1)(k+2)2.\sum_{i=1}^{k+1} i = \sum_{i=1}^{k} i + (k + 1) = \frac{k(k+1)}{2} + (k+1) = (k+1)\left(\frac{k}{2} + 1\right) = \frac{(k+1)(k+2)}{2}.

That is the formula with n=k+1n = k + 1. The statement holds for n=1n = 1, and whenever it holds for kk it holds for k+1k + 1, so by induction it holds for every n≥1n \ge 1. ■\blacksquare

Notice where the sum notation did the work: splitting off the last term is what connects case k+1k + 1 to case kk. The same pattern proves many sum formulas, such as ∑i=1ni2=n(n+1)(2n+1)6\sum_{i=1}^{n} i^2 = \frac{n(n+1)(2n+1)}{6} (so ∑i=110i2=385\sum_{i=1}^{10} i^2 = 385, one of the lab's targets) and ∑i=1n(2i−1)=n2\sum_{i=1}^{n} (2i - 1) = n^2, 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 rr:

∑i=0n−1ri=1+r+r2+⋯+rn−1=1−rn1−r(r≠1).\sum_{i=0}^{n-1} r^i = 1 + r + r^2 + \cdots + r^{n-1} = \frac{1 - r^n}{1 - r} \qquad (r \ne 1).

The derivation: multiply and subtract

Call the sum SS and multiply it by rr. Every power moves up by one:

S=1+r+r2+⋯+rn−1,rS=1+r+r2+⋯+rn−1+rn.\begin{aligned} S &= 1 + r + r^2 + \cdots + r^{n-1}, \\ rS &= \phantom{1 + {}} r + r^2 + \cdots + r^{n-1} + r^{n}. \end{aligned}

Subtract the second line from the first. Everything in the middle cancels, leaving S−rS=1−rnS - rS = 1 - r^n. Factor out SS to get S(1−r)=1−rnS(1 - r) = 1 - r^n, and divide by 1−r1 - r, which is allowed because r≠1r \ne 1. In Σ\Sigma notation, the multiplication is an index shift: rS=∑i=0n−1ri+1=∑i=1nrirS = \sum_{i=0}^{n-1} r^{i+1} = \sum_{i=1}^{n} r^{i}, and the two sums share every term except r0r^0 and rnr^n.

With r=2r = 2 and n=10n = 10 you get 1−2101−2=1023\frac{1 - 2^{10}}{1 - 2} = 1023: every bit of a 10-bit number switched on. When ∣r∣<1|r| < 1, the power rnr^n shrinks to 0 as nn grows, and the infinite series settles at ∑i=0∞ri=11−r\sum_{i=0}^{\infty} r^i = \frac{1}{1 - r}. (What “settles” means precisely is the limit of Chamber 7.)

Geometric series turn up all over machine learning:

  • In reinforcement learning, a reward rtr_t received tt steps in the future is discounted by γt\gamma^t, and the return is ∑t=0∞γtrt\sum_{t=0}^{\infty} \gamma^t r_t. With a reward of 1 at every step and γ=0.99\gamma = 0.99, the return is 11−0.99=100\frac{1}{1 - 0.99} = 100, so γ\gamma sets how far ahead the agent effectively looks.
  • Adam's running average (Chamber 1) gives the gradient from kk steps ago a weight of (1−β)βk(1 - \beta)\beta^{k}. Over tt steps these weights add up to (1−β)(1+β+⋯+βt−1)=1−βt(1 - \beta)(1 + \beta + \cdots + \beta^{t-1}) = 1 - \beta^t: exactly the denominator in Adam's bias correction m^t=mt/(1−βt)\hat{m}_t = m_t / (1 - \beta^t). 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: ∑i∈Bℓi\sum_{i \in \mathcal{B}} \ell_i adds ℓi\ell_i for every ii in the mini-batch B\mathcal{B}, and the mean loss over the batch is 1∣B∣∑i∈Bℓi\frac{1}{|\mathcal{B}|}\sum_{i \in \mathcal{B}} \ell_i, with ∣B∣|\mathcal{B}| the batch size from Chamber 2. It can also carry conditions. ∑j≠ixj\sum_{j \ne i} x_j adds every xjx_j except xix_i, and ∑i : yi=1xi\sum_{i \,:\, y_i = 1} x_i adds only the examples whose label is 1. In code, a condition under the Σ\Sigma 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

1T∑t=1T∑−c≤j≤c,j≠0log⁡p(wt+j∣wt)\frac{1}{T}\sum_{t=1}^{T}\sum_{-c\leq j\leq c,j\neq 0}\log p(w_{t+j}|w_t)
Mikolov et al. (2013), “Distributed Representations of Words and Phrases and their Compositionality”, Eq. (1)

Read it from the outside in. The text is a sequence of words w1,…,wTw_1, \ldots, w_T. The outer sum visits every position tt. The inner sum visits the offsets jj from −c-c to cc, the window around the word, and the condition j≠0j \ne 0 skips the word itself. Each term is the log probability the model gives to seeing the neighbour wt+jw_{t+j} near the centre word wtw_t, and the 1T\frac{1}{T} turns the total into an average. Training makes this number as large as possible.

Quick check +20 XP

In word2vec's objective, the inner sum runs over −c≤j≤c, j≠0-c \le j \le c,\ j \ne 0. With window size c=5c = 5, 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 aija_{ij} with mm rows and nn columns,

∑i=1m∑j=1naij=∑j=1n∑i=1maij.\sum_{i=1}^{m}\sum_{j=1}^{n} a_{ij} = \sum_{j=1}^{n}\sum_{i=1}^{m} a_{ij}.

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 ii and a part for jj, the double sum factorises: ∑i∑jxi yj=(∑ixi)(∑jyj)\sum_{i}\sum_{j} x_i\,y_j = \left(\sum_i x_i\right)\left(\sum_j y_j\right).

When the inner bounds depend on the outer index, swapping takes care. ∑i=1n∑j=1iaij\sum_{i=1}^{n}\sum_{j=1}^{i} a_{ij} adds the lower triangle of the grid, the pairs with 1≤j≤i≤n1 \le j \le i \le n. To add the same triangle column by column, fix jj first; then ii runs from jj to nn:

∑i=1n∑j=1iaij=∑j=1n∑i=jnaij.\sum_{i=1}^{n}\sum_{j=1}^{i} a_{ij} = \sum_{j=1}^{n}\sum_{i=j}^{n} a_{ij}.

Draw the triangle and both sides are obvious. You'll meet this shape again in language models, where a causal attention mask lets position ii look only at positions j≤ij \le i.

Learn: products, factorials and logs

Capital pi does for multiplication what capital sigma does for addition:

∏i=1nxi=x1 x2⋯xn,\prod_{i=1}^{n} x_i = x_1 \, x_2 \cdots x_n,

read “the product from ii equals 1 to nn of xx sub ii”. 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, n!=∏k=1nkn! = \prod_{k=1}^{n} k, the number of ways to put nn things in order: 5!=1205! = 120. By the empty-product rule, 0!=10! = 1.

Products
  • ∏i=1nxi\prod_{i=1}^{n} x_i“the product from i equals 1 to n of x sub i”
    Multiply the terms instead of adding them. An empty product is 1.
    ∏i=13xi=x1x2x3\prod_{i=1}^{3} x_i = x_1 x_2 x_3
  • n!n!“n factorial”
    1⋅2⋯n=∏k=1nk1 \cdot 2 \cdots n = \prod_{k=1}^{n} k, the number of ways to put nn things in order. By the empty-product rule, 0!=10! = 1.
    5!=1205! = 120
  • log⁡∏ipi\log \prod_i p_i“the log of the product of p sub i”
    Equals ∑ilog⁡pi\sum_i \log p_i: a product of many small probabilities becomes a sum that a computer can store.
    log⁡∏ipi=∑ilog⁡pi\log \prod_i p_i = \sum_i \log p_i

Products matter in ML because probabilities multiply. If a model gives probability pip_i to each of nn independent observations, the probability of all of them together, the likelihood, is ∏i=1npi\prod_{i=1}^{n} p_i. That is a problem for a computer. With pi=0.5p_i = 0.5 and n=1100n = 1100, the product is 0.51100≈10−3310.5^{1100} \approx 10^{-331}, 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 log⁡(ab)=log⁡a+log⁡b\log(ab) = \log a + \log b over and over, one factor at a time:

log⁡∏i=1npi=∑i=1nlog⁡pi.\log \prod_{i=1}^{n} p_i = \sum_{i=1}^{n} \log p_i.

The log-likelihood of those 1100 observations is 1100log⁡0.5≈−762.51100 \log 0.5 \approx -762.5, a perfectly ordinary number. And because log⁡\log 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 ∑\sum of log⁡\logs.

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:

μ=1n∑i=1nxi,σ2=1n∑i=1n(xi−μ)2.\mu = \frac{1}{n}\sum_{i=1}^{n} x_i, \qquad \sigma^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i - \mu)^2.

Read them as “mu” and “sigma squared”. The standard deviation σ=σ2\sigma = \sqrt{\sigma^2} 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 B\mathcal{B}.

Take the batch 2,4,92, 4, 9 from the quiz. The mean is 5, the deviations are −3,−1,4-3, -1, 4 (which add up to 0, as proved above), their squares are 9,1,169, 1, 16, and the variance is 263≈8.67\frac{26}{3} \approx 8.67. The third line of Algorithm 1 divides each deviation by σ2+ϵ≈2.94\sqrt{\sigma^2 + \epsilon} \approx 2.94, so the normalised values have mean 0 and a spread of about 1, whatever the scale of the numbers you started with.

Mean and variance
  • μ\mu“mu, the mean”
    The average, 1n∑ixi\frac{1}{n}\sum_i x_i. Also written xˉ\bar{x}.
    μ=1n∑ixi\mu = \tfrac{1}{n}\sum_{i} x_i
  • σ2\sigma^2“sigma squared, the variance”
    The average squared distance from the mean: how spread out the values are.
    σ2=1n∑i(xi−μ)2\sigma^2 = \tfrac{1}{n}\sum_{i} (x_i - \mu)^2
  • σ\sigma“sigma, the standard deviation”
    σ2\sqrt{\sigma^2}: the spread in the same units as the data.
    σ=σ2\sigma = \sqrt{\sigma^2}
  • μB,σB2\mu_{\mathcal{B}}, \sigma^2_{\mathcal{B}}“mu B and sigma squared B”
    The mean and variance of one mini-batch B\mathcal{B}, as in batch normalisation.
  • x^i\widehat{x}_i“x hat sub i, normalised”
    In batch normalisation, xix_i minus the batch mean, divided by the batch standard deviation: how many standard deviations xix_i 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: σ2=1n∑ixi2−μ2\sigma^2 = \frac{1}{n}\sum_i x_i^2 - \mu^2. You'll prove it in Your turn. Second, statisticians often divide by n−1n - 1 instead of nn when estimating the variance of a whole population from a sample (Bessel's correction). Algorithm 1 divides by mm. The paper switches to mm−1\frac{m}{m-1} only for the statistics it keeps for use after training. Tools differ too: NumPy's np.var divides by nn by default, while Python's statistics.variance divides by n−1n - 1. When you implement a formula, check which one it means.

DiscoverLearnRead beyondPapers & lecturesYour turn

Read beyond the course

Lecture notes · free online · ~15 min

Summation Notation

Paul 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 ∑i\sum i, ∑i2\sum i^2 and ∑i3\sum i^3 with worked examples. Keep it open while you do this chamber's exercises.

Book · free online · ~30 min

Book of Proof

Richard 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 Learning

Marc 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 Learning

Aston Zhang, Zachary C. Lipton, Mu Li & Alexander J. Smola · §8.5: Batch Normalization

Batch normalisation again, written as sums over a set: 1∣B∣∑x∈Bx\frac{1}{|\mathcal{B}|}\sum_{\mathbf{x} \in \mathcal{B}} \mathbf{x}. Comparing it with the paper's Algorithm 1 is good practice in recognising one idea in two notations, and the section includes runnable code.

DiscoverLearnRead beyondPapers & lecturesYour turn

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 (B\mathcal{B}, mm and BNγ,β\mathrm{BN}_{\gamma,\beta}), and the one after explains why the normalised values have mean 0 and variance 1, using the sums ∑i=1mx^i=0\sum_{i=1}^{m} \widehat{x}_i = 0 and 1m∑i=1mx^i2=1\frac{1}{m}\sum_{i=1}^{m} \widehat{x}_i^2 = 1. Then flip back to the introduction, where the training objective appears as a sum over the whole training set, 1N∑i=1Nℓ(xi,Θ)\frac{1}{N}\sum_{i=1}^{N} \ell(\mathrm{x}_i, \Theta). 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, 2015

Four 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, 2013

The 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 Shift

Sergey Ioffe, Christian Szegedy · ICML, 2015

+30 XP
μB←1m∑i=1mxiσB2←1m∑i=1m(xi−μB)2x^i←xi−μBσB2+ϵyi←γx^i+β≡BNγ,β(xi)\begin{aligned} \mu_{\mathcal{B}} &\leftarrow \frac{1}{m}\sum_{i=1}^{m} x_i \\ \sigma_{\mathcal{B}}^2 &\leftarrow \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu_{\mathcal{B}})^2 \\ \widehat{x}_i &\leftarrow \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}} \\ y_i &\leftarrow \gamma\widehat{x}_i + \beta \equiv \mathrm{BN}_{\gamma,\beta}(x_i) \end{aligned}

The Batch Normalizing Transform, applied to one activation over a mini-batch B={x1…m}\mathcal{B} = \{x_{1 \ldots m}\}. The paper labels its four lines “mini-batch mean”, “mini-batch variance”, “normalize” and “scale and shift”. Match each symbol to its job.

mm
∑i=1m\sum_{i=1}^{m}
μB\mu_{\mathcal{B}}
σB2\sigma_{\mathcal{B}}^2
x^i\widehat{x}_i
ϵ\epsilon
γ,β\gamma, \beta

Options

Decode the paper · Eq. (1), Section 2

Distributed Representations of Words and Phrases and their Compositionality

Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, Jeffrey Dean · NIPS, 2013

+30 XP
1T∑t=1T∑−c≤j≤c,j≠0log⁡p(wt+j∣wt)\frac{1}{T}\sum_{t=1}^{T}\sum_{-c\leq j\leq c,j\neq 0}\log p(w_{t+j}|w_t)

The skip-gram objective behind word2vec's word vectors: “given a sequence of training words w1,w2,w3,…,wTw_1, w_2, w_3, \ldots, w_T, the objective of the Skip-gram model is to maximize the average log probability” below. Two sums, one with conditions under it.

TT
∑t=1T\sum_{t=1}^{T}
wtw_t
cc
∑−c≤j≤c,j≠0\sum_{-c\leq j\leq c,j\neq 0}
log⁡p(wt+j∣wt)\log p(w_{t+j}|w_t)
1T\frac{1}{T}

Options

Watch

Sigma notation for sumsKhan Academy · 4 min

A short introduction to reading and expanding a Σ\Sigma. Watch it if the anatomy of a sum still feels shaky, and pause before each expansion to do it yourself.

Normalizing Activations in a Network (C2W3L04)DeepLearningAI · 9 min

Andrew Ng writes out batch normalisation's equations step by step. Watch for the same sums in slightly different clothes: he writes the ii-th example as z(i)z^{(i)}, with the bracketed superscript of Chamber 1, and calls the result z~(i)\tilde{z}^{(i)}.

DiscoverLearnRead beyondPapers & lecturesYour turn

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

+25 XP

Match each expression to its expansion. Watch the bounds: both ends are included.

∑i=14i\sum_{i=1}^{4} i
∑i=142i\sum_{i=1}^{4} 2^{i}
∑i=032i\sum_{i=0}^{3} 2^{i}
∏i=14i\prod_{i=1}^{4} i
∑i=14(−1)i\sum_{i=1}^{4} (-1)^{i}
∑i=135\sum_{i=1}^{3} 5
∑i=24xi−1\sum_{i=2}^{4} x_{i-1}

Options

Match · Maths ↔ Python

From Σ to Python

+25 XP

Match each formula to the Python that computes it (with import math). The lists x and p hold x1,…,xnx_1, \ldots, x_n and p1,…,pnp_1, \ldots, p_n at positions 0 to n - 1.

∑i=1ni2\sum_{i=1}^{n} i^2
∑i=0n−1i2\sum_{i=0}^{n-1} i^2
∏i=1ni\prod_{i=1}^{n} i
1n∑i=1nxi\frac{1}{n}\sum_{i=1}^{n} x_i
∑j≠ixj\sum_{j \ne i} x_j
∑i=1nlog⁡pi\sum_{i=1}^{n} \log p_i
∑i=1n(xi−xˉ)2\sum_{i=1}^{n} (x_i - \bar{x})^2

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

+25 XP

Claim

For every integer n≥1n \ge 1, the sum of the first nn odd numbers is a perfect square:

∑i=1n(2i−1)=n2.\sum_{i=1}^{n} (2i - 1) = n^2.

Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.

Your proof

  1. Pick the first line below.

Available lines

Prove it yourself

The mean of the square minus the square of the mean

+40 XP

Claim

Let x1,…,xnx_1, \ldots, x_n be real numbers with mean μ=1n∑i=1nxi\mu = \frac{1}{n}\sum_{i=1}^{n} x_i. Prove that their variance can be computed as

1n∑i=1n(xi−μ)2=1n∑i=1nxi2−μ2.\frac{1}{n}\sum_{i=1}^{n} (x_i - \mu)^2 = \frac{1}{n}\sum_{i=1}^{n} x_i^2 - \mu^2.

Preview

Your typeset proof appears here.

Code it up

Every Σ\Sigma 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

+20 XP

Compute

∑k=150(−1)kk2.\sum_{k=1}^{50} (-1)^k k^2.

The factor (−1)k(-1)^k is +1+1 when kk is even and −1-1 when kk is odd, so the sum is −1+4−9+16−⋯+2500-1 + 4 - 9 + 16 - \cdots + 2500. Give the exact integer.

An exact integer (or a fraction like 7/12)

Problem 14·Standard

Apply the paper: batch norm by hand

+35 XP

Batch normalisation's Algorithm 1 transforms a mini-batch B={x1,…,xm}\mathcal{B} = \{x_1, \ldots, x_m\}:

μB←1m∑i=1mxi,σB2←1m∑i=1m(xi−μB)2,\mu_{\mathcal{B}} \leftarrow \frac{1}{m}\sum_{i=1}^{m} x_i, \qquad \sigma_{\mathcal{B}}^2 \leftarrow \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu_{\mathcal{B}})^2,

x^i←xi−μBσB2+ϵ,yi←γ x^i+β.\widehat{x}_i \leftarrow \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}}, \qquad y_i \leftarrow \gamma\,\widehat{x}_i + \beta.

Take m=10m = 10 values xi=i2 mod 11x_i = i^2 \bmod 11 for i=1,…,10i = 1, \ldots, 10 (so x1=1x_1 = 1, x2=4x_2 = 4, x3=9x_3 = 9, x4=5x_4 = 5, …), with γ=2\gamma = 2, β=0.5\beta = 0.5 and ϵ=10−5\epsilon = 10^{-5}.

What is y3y_3? Give it rounded to 4 decimal places.

A number, rounded to 4 decimal places

Problem 15·Challenge

Apply the paper: a toy skip-gram objective

+50 XP

word2vec's skip-gram model is trained to maximise the average log probability (Eq. 1 of the paper)

J=1T∑t=1T ∑−c≤j≤c, j≠0log⁡p(wt+j∣wt),J = \frac{1}{T}\sum_{t=1}^{T}\ \sum_{-c \le j \le c,\ j \ne 0} \log p(w_{t+j} \mid w_t),

where w1,…,wTw_1, \ldots, w_T is the training text and cc is the window size. The paper leaves one condition implicit: we also require 1≤t+j≤T1 \le t + j \le T, so neighbours that would fall off either end of the text are skipped.

Build a toy version. The vocabulary is the integers 0,1,…,60, 1, \ldots, 6, the text has T=200T = 200 words wt=t2 mod 7w_t = t^2 \bmod 7, and the window is c=2c = 2. In place of the paper's Eq. (2), use the toy model

p(o∣i)=exp⁡(−∣o−i∣)∑w=06exp⁡(−∣w−i∣),p(o \mid i) = \frac{\exp(-|o - i|)}{\sum_{w=0}^{6} \exp(-|w - i|)},

the probability that word oo appears near word ii. The log is natural. Compute JJ, rounded to 4 decimal places.

A number, rounded to 4 decimal places

Key takeaways

  • A Σ\Sigma is a loop. ∑i=abxi\sum_{i=a}^{b} x_i adds the terms for every integer ii from aa to bb, both included: b−a+1b - a + 1 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, ∑i=1nc=nc\sum_{i=1}^{n} c = nc. Ranges split and indices shift. Sums do not split over products or squares.
  • Two formulas to know: ∑i=1ni=n(n+1)2\sum_{i=1}^{n} i = \frac{n(n+1)}{2} (by pairing, or by induction) and ∑i=0n−1ri=1−rn1−r\sum_{i=0}^{n-1} r^i = \frac{1 - r^n}{1 - r} (multiply and subtract).
  • Indices can run over sets and carry conditions, as in ∑i∈B\sum_{i \in \mathcal{B}} and ∑j≠i\sum_{j \ne i}. Double sums are nested loops, and finite ones can be swapped.
  • Logs turn products into sums: log⁡∏ipi=∑ilog⁡pi\log \prod_i p_i = \sum_i \log p_i, 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.

0/8
Question 1 of 8 +20 XP

Which of these equals ∑i=1nxi\sum_{i=1}^{n} x_i for every list x1,…,xnx_1, \ldots, x_n?

Question 2 of 8 +20 XP

What is ∑i=43i2+∏i=43i\sum_{i=4}^{3} i^2 + \prod_{i=4}^{3} i?

Question 3 of 8 +20 XP

Use Gauss's formula ∑i=1ni=n(n+1)2\sum_{i=1}^{n} i = \frac{n(n+1)}{2} to compute ∑i=51100i\sum_{i=51}^{100} i.

Question 4 of 8 +20 XP

Compute ∑i=073i\sum_{i=0}^{7} 3^i.

Question 5 of 8 +20 XP

Which of these is not true for all lists of numbers?

Question 6 of 8 +20 XP

Compute ∑i=13∑j=12i j\sum_{i=1}^{3}\sum_{j=1}^{2} i\,j.

Question 7 of 8 +20 XP

A model gives probability 0.50.5 to each of 1100 independent observations. Why do papers maximise ∑ilog⁡pi\sum_i \log p_i rather than ∏ipi\prod_i p_i?

Question 8 of 8 +20 XP

What is the variance σ2=1n∑i=1n(xi−μ)2\sigma^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i - \mu)^2 of the values 1,3,5,71, 3, 5, 7?

End of the chamber

Clear this chamber

+60 XPSigma NotationPi NotationLinearity of SumsMean and Variance