AI from scratch · Calculus 4 · Foundations

Integrals: adding up the infinitely small

Derivatives cut things into tiny changes; integrals add tiny pieces back up. In ML that's how probability works for anything continuous (a height, a delay, a pixel value), and it's what a loss really is: an average over every input the model could ever see. You never get to compute that average exactly. You estimate it from a batch, and this lesson shows how good that estimate is and what it costs to make it better.

1. Area as a sum of thin strips

To find the area under a curve, slice it into \(n\) strips, treat each as a rectangle, and add them up. The rectangle's height can come from the strip's left edge, its middle, or its right edge. Add strips and all three close in on the same number, the integral:

\[ \int_a^b f(x)\,dx = \lim_{n \to \infty} \sum_{i=1}^{n} f(x_i)\,\Delta x, \qquad \Delta x = \frac{b - a}{n} \]

Left and right edges miss by an amount proportional to \(1/n\); the middle is far better, with errors like \(1/n^2\), the same pattern as forward vs central differences in Calculus 1.

An integral adds up thin strips. Taking each strip's height from its middle makes the sum accurate long before the strips get thin.

What is the exact area under \(x^2\) from 0 to 1? (Slide n up and watch where the sums go.)

\(\int_0^1 x^2\,dx = \tfrac13\). Section 2 shows how to get it without any strips: an antiderivative of \(x^2\) is \(x^3/3\), and \(1/3 - 0 = 1/3\).

2. The fundamental theorem: area grows at the speed of the curve

Let \(A(x)\) be the area under \(f\) from 0 up to \(x\). Push \(x\) a bit further by \(dx\) and the area gains one thin strip of height \(f(x)\), so \(dA = f(x)\,dx\). In other words, the slope of the area function is the curve itself: \(A'(x) = f(x)\). Integration undoes differentiation.

f(t) = 1 + 0.8 sin 2t area so far A(x) A's tangent

So to compute \(\int_a^b f\), find any function \(F\) whose derivative is \(f\) (an antiderivative) and subtract: \(\int_a^b f(x)\,dx = F(b) - F(a)\). Every rule from Calculus 1 read backwards is an integration rule.

The area grows at a rate equal to the curve's height, so integrating undoes differentiating.

Antiderivatives worth knowing
\(f(x)\)an antiderivative \(F(x)\)
\(x^n\) (\(n \ne -1\))\(x^{n+1}/(n+1)\)
\(1/x\)\(\ln x\)
\(e^{x}\), \(e^{kx}\)\(e^x\), \(e^{kx}/k\)
\(\sin x\), \(\cos x\)\(-\cos x\), \(\sin x\)
\(e^{-x^2/2}\)no formula with ordinary functions: it's \(\sqrt{\pi/2}\,\mathrm{erf}(x/\sqrt2)\), which computers tabulate

The last row is why the normal distribution's probabilities come from a special function, used in the next section.

3. Densities: probability is area

A continuous random number, say tomorrow's subway delay, can take infinitely many values, so any single exact value has probability 0. What it has instead is a density \(p(x)\): probability per unit of \(x\). The probability of landing in an interval is the area under the density there, and the total area is 1. The most important density is the normal (Gaussian), the bell curve with center \(\mu\) and width \(\sigma\):

\[ p(x) = \frac{1}{\sigma\sqrt{2\pi}}\, e^{-(x - \mu)^2 / 2\sigma^2}, \qquad P(a < X < b) = \int_a^b p(x)\,dx \]

For continuous values, probability is area under a density. The density is probability per unit; only its total area has to be 1.

Can a density be bigger than 1?

A density is probability per unit. With \(\sigma = 0.1\) the bell's peak is \(1/(0.1\sqrt{2\pi}) \approx 3.99\): tall but narrow, still area 1. This is why a model's "likelihood" for continuous data can be above 1, and its negative log-likelihood negative.

Set \(a = \mu - \sigma\) and \(b = \mu + \sigma\). What is \(P(|X - \mu| < \sigma)\)?

About 0.683, whatever \(\mu\) and \(\sigma\) are: \(\mathrm{erf}(1/\sqrt2)\). Within 2σ it's 0.954, within 3σ 0.997, the "68–95–99.7 rule".
Change of variables: where the Jacobian's determinant comes back

If \(X\) has density \(p\) and \(Y = 2X\), \(Y\) is spread over twice the range, so its density must be half as tall to keep area 1: \(p_Y(y) = p(y/2)/2\). In general, for an invertible map \(y = F(x)\) in any number of dimensions, \(p_Y(y) = p_X(x) / |\det J_F(x)|\), the area scale from Calculus 2. Normalizing flows, a family of generative models, are built entirely on this formula: they stack invertible layers whose Jacobian determinants are cheap to compute.

4. The loss is an integral; a batch is a guess at it

The average of \(f(X)\) when \(X\) has density \(p\) is the expectation, an integral that weighs each value by how likely it is:

\[ \mathbb{E}[f(X)] = \int f(x)\,p(x)\,dx \]

The loss you really care about is one of these: the average error over every input the world could send, \(\mathbb{E}_{x \sim p}[\text{loss}(x)]\) (\(x \sim p\) reads "x drawn from p"). Nobody knows \(p\), so nobody can compute it. What you can do is draw \(N\) examples and average: \(\frac1N \sum \text{loss}(x_i)\). That is a Monte Carlo estimate, and a minibatch's loss and gradient are exactly that. How good is it? Here are estimates of \(\mathbb{E}[X^2] = 1\) for a standard normal \(X\) (the bell curve with \(\mu = 0\) and \(\sigma = 1\)), as samples pile up (the x-axis is logarithmic: each grid line is ten times more samples):

running estimate truth ± one standard error

The estimate wanders inside a band that narrows like \(\sigma/\sqrt N\), where \(\sigma\) is the spread of a single sample (here \(\sqrt2\)). That square root is the law of the land for every minibatch: to halve the noise you need four times the data. It's why gradient noise drops slowly as batches grow, and why huge batches give diminishing returns.

The loss you care about is an average over every possible input; a batch estimates it, with noise that shrinks only like one over the square root of its size.

Why does the noise shrink like \(1/\sqrt{N}\), and not like \(1/N\)?
  1. Each sample's loss \(\ell_i\) wanders around the true average with spread \(\sigma\), that is variance \(\sigma^2\).
  2. For independent samples, variances add: the sum \(\ell_1 + \dots + \ell_N\) has variance \(N\sigma^2\). (Square the sum's distance from its average and the cross terms, one sample's error times another's, average out to zero because neither tells you anything about the other.)
  3. The batch average divides the sum by \(N\), which divides its variance by \(N^2\): \(N\sigma^2 / N^2 = \sigma^2 / N\).
  4. Spread is the square root of variance: \(\sigma / \sqrt{N}\). The errors partly cancel each other, but only partly: their total grows like \(\sqrt N\) while the count grows like \(N\).
Where it breaks: when a sample isn't the world

Your batch gradient is too noisy. How many times bigger must the batch be to cut its noise in half?

Noise \(\propto 1/\sqrt N\), so half the noise needs \(\sqrt N\) twice as big: \(N\) four times as big. Ten times less noise costs a hundred times more data.

Why sample at all, when section 1's strips are so accurate? In one dimension, strips win easily. But a grid with 10 points per axis needs \(10^d\) points in \(d\) dimensions, and an image has hundreds of thousands of dimensions. The Monte Carlo error is \(\sigma/\sqrt N\) in any number of dimensions:

5. What to carry forward

All chapters: AI from scratch

Last updated