Type at least 2 letters. Enter opens the first result, Esc closes.

    Calculus for ML · Lesson 10 · Integrals for ML

    Integrals, expectations and the change of variables

    Intermediate 85 min 5 interactive figures 5 videos Colab notebook

    Before this lesson: lesson 01 (derivatives in one variable), lesson 03 (the Jacobian DfDf and the linear approximation), linear algebra lesson 03 (the determinant as a volume factor). It helps to know random variables and densities from the probability and statistics track; we repeat what we need. Time: about 85 minutes, plus the notebook.


    Why this matters #

    Expectations are everywhere in ML. The training loss is an average that estimates an expected loss. The evidence lower bound (ELBO) of a variational autoencoder, a policy's expected return in reinforcement learning and the marginal likelihood of a Bayesian model are all integrals. Most of them have no closed form, so we estimate them with Monte Carlo averages, and we need to know how fast these averages converge.

    The change-of-variables rule is the other main tool. It gives the density of a transformed random variable. This is the basis of normalizing flows (exact likelihoods for generative models), of the likelihood of continuous flows and of the probability-flow ODE of diffusion models, and of sampling by the inverse CDF, by Box–Muller and by reparameterization. In science, many models predict a log-quantity (log-precipitation, log-permeability, the log of a ground-motion amplitude). To report a likelihood for the quantity itself, you need the Jacobian factor of the logarithm.

    1. Predict first #

    2. The picture #

    An integral is a limit of sums #

    Cut the interval [a,b][a, b] into nn strips of width h=(b−a)/nh = (b - a)/n. On each strip, put a rectangle whose height is the value of ff at one point of the strip. The sum of the rectangle areas is a Riemann sum. When nn grows, the sum approaches the area under the curve: the integral ∫abf(x) dx\int_a^b f(x)\,dx. Area below the xx-axis counts as negative.

    The choice of the point changes how fast the sum converges. The left sum uses the left end of each strip. The midpoint rule uses the middle. The trapezoid rule joins the two end values by a straight line. A completely different idea is Monte Carlo: pick nn random points u1,…,unu_1, \dots, u_n, uniform on [a,b][a, b], and use (b−a)(b - a) times the average of f(ui)f(u_i).

    Interactive figure: loading…

    Change nn and the method, and watch the error chart. The shaded strips are the Riemann sum; the black curve is ff. In the log-log chart, each line is the error of one method against nn: left sum, midpoint, trapezoid and the typical Monte Carlo error. The left sum has slope −1-1 (error ∝1/n\propto 1/n). The midpoint and trapezoid rules have slope −2-2 (error ∝1/n2\propto 1/n^2). Monte Carlo has slope −1/2-1/2: it is the slowest in 1-D.

    With n=4n = 4, the midpoint rule for ∫01x2 dx=1/3\int_0^1 x^2\,dx = 1/3 uses the midpoints 0.125,0.375,0.625,0.8750.125, 0.375, 0.625, 0.875:

    M4=0.25 (0.1252+0.3752+0.6252+0.8752)=0.328125,M_4 = 0.25\,\big(0.125^2 + 0.375^2 + 0.625^2 + 0.875^2\big) = 0.328125,

    so the error is 1/3−0.328125=0.00521/3 - 0.328125 = 0.0052.

    Quick check

    The midpoint rule for ∫01x2 dx\int_0^1 x^2\,dx has error 0.00520.0052 with n=4n = 4 strips. About what error do you expect with n=8n = 8?

    A smooth map scales small areas by ∣det⁡DT∣|\det DT| #

    Now go to two dimensions. A map TT sends a point yy to a point x=T(y)x = T(y). On a small square around y0y_0, a smooth map is almost linear: T(y0+h)≈T(y0)+DT(y0) hT(y_0 + h) \approx T(y_0) + DT(y_0)\,h, where DT(y0)DT(y_0) is the Jacobian matrix (lesson 03). A linear map multiplies every area by ∣det⁡∣|\det| of its matrix (linear algebra lesson 03). So the small square goes to a small curved region with area about ∣det⁡DT(y0)∣|\det DT(y_0)| times the area of the square.

    Interactive figure: loading…

    Drag the violet point, then make the square small. Left: the small square in the yy-coordinates. Right: its image under TT and, dashed, the image under the linear map DT(y0)DT(y_0). The readout compares the ratio of the two areas with ∣det⁡DT(y0)∣|\det DT(y_0)|; they agree better as the side ss shrinks. In the polar map, y=(r,θ)y = (r, \theta) and det⁡DT=r\det DT = r: the same square gives a bigger image far from the origin. With "linear, det < 0" the map flips the orientation, and the area factor is still the absolute value.

    This is why an integral in new coordinates needs the factor ∣det⁡DT∣|\det DT|. Each small box of volume dydy in the new coordinates covers a region of volume ∣det⁡DT(y)∣ dy|\det DT(y)|\,dy in the old ones.

    Probability moves, so the density must change #

    A random variable XX with a density pXp_X puts probability pX(x) dxp_X(x)\,dx on a small interval of width dxdx around xx. Take the simplest case: XX uniform on (0,1)(0, 1) and Y=2XY = 2X. Then YY is uniform on (0,2)(0, 2). The interval got twice as long, and the total probability is still 1, so the density must be half as high: pY=1/2p_Y = 1/2 on (0,2)(0, 2).

    For a general smooth increasing map y=g(x)y = g(x), a small interval [x,x+dx][x, x + dx] goes to [y,y+dy][y, y + dy] with dy=g′(x) dxdy = g'(x)\,dx. Both intervals hold the same probability:

    pY(y) ∣dy∣=pX(x) ∣dx∣⟹pY(y)=pX(x)∣g′(x)∣,p_Y(y)\,|dy| = p_X(x)\,|dx| \quad\Longrightarrow\quad p_Y(y) = \frac{p_X(x)}{|g'(x)|},

    where x=g−1(y)x = g^{-1}(y) is the point that gg sends to yy.

    Where gg stretches space (∣g′∣>1|g'| > 1), the density goes down. Where gg compresses space (∣g′∣<1|g'| < 1), the density goes up.

    Interactive figure: loading…

    Move the violet strip and compare the two violet areas. Top: samples of XX and its density. Bottom: the same samples after the map, Y=g(X)Y = g(X), with the formula pX(x)/∣g′(x)∣p_X(x)/|g'(x)| on top. The violet strip holds the same probability in both charts, so where its image is wider, it is lower. Then choose a wrong formula in the menu: it no longer fits the histogram, and its integral is not 1. Try X2X^2 with "one branch" and σ(2X)\sigma(2X), where the density piles up near 0 and 1.

    Quick check

    XX is uniform on (0,1)(0, 1) and Y=2XY = 2X. What is pY(1)p_Y(1)?

    3. Definitions and main results #

    3.1 The definite integral and the fundamental theorem #

    Let ff be a function on [a,b][a, b]. Cut [a,b][a, b] into nn pieces [xi−1,xi][x_{i-1}, x_i] of width h=(b−a)/nh = (b - a)/n, with xi=a+ihx_i = a + ih, and choose a point ξi\xi_i in each piece. The Riemann sum is

    Sn=∑i=1nf(ξi) h.S_n = \sum_{i=1}^{n} f(\xi_i)\,h .

    ff is (Riemann) integrable if SnS_n tends to the same limit for every choice of the points ξi\xi_i as n→∞n \to \infty. This limit is the definite integral ∫abf(x) dx\int_a^b f(x)\,dx. Every continuous function on [a,b][a, b] is integrable.

    How fast the rules converge. Let ff have a continuous second derivative. Then, for some points ξ∈[a,b]\xi \in [a, b]:

    Rule Height of strip ii Error I−SnI - S_n Order
    left sum f(xi−1)f(x_{i-1}) h2(f(b)−f(a))+O(h2)\frac h2\big(f(b) - f(a)\big) + O(h^2) O(h)O(h)
    midpoint f(xi−1+xi2)f\big(\frac{x_{i-1} + x_i}{2}\big) (b−a)h224f′′(ξ)\frac{(b - a)h^2}{24} f''(\xi) O(h2)O(h^2)
    trapezoid 12(f(xi−1)+f(xi))\frac12\big(f(x_{i-1}) + f(x_i)\big) −(b−a)h212f′′(ξ)-\frac{(b - a)h^2}{12} f''(\xi) O(h2)O(h^2)

    For f(x)=x2f(x) = x^2 on [0,1][0, 1], f′′=2f'' = 2, so the midpoint error is exactly h2/12h^2/12; with h=1/4h = 1/4 this is 0.00520.0052, as in section 2. The midpoint and trapezoid errors have opposite signs, and the midpoint error is about half as large. (If f(a)=f(b)f(a) = f(b), the left sum equals the trapezoid sum, so it is also O(h2)O(h^2).)

    Theorem (fundamental theorem of calculus, FTC). Let ff be continuous on [a,b][a, b].

    1. The function F(x)=∫axf(t) dtF(x) = \int_a^x f(t)\,dt is differentiable, and F′(x)=f(x)F'(x) = f(x).
    2. If GG is any antiderivative of ff (that is, G′=fG' = f on [a,b][a, b]), then ∫abf(x) dx=G(b)−G(a)\int_a^b f(x)\,dx = G(b) - G(a).

    Proof.

    1. For h>0h > 0, F(x+h)−F(x)=∫xx+hf(t) dtF(x + h) - F(x) = \int_x^{x + h} f(t)\,dt. On the small interval [x,x+h][x, x + h], ff lies between its minimum mhm_h and its maximum MhM_h, so mh h≤F(x+h)−F(x)≤Mh hm_h\,h \le F(x + h) - F(x) \le M_h\,h.
    2. Divide by hh. Because ff is continuous, mhm_h and MhM_h both tend to f(x)f(x) as h→0h \to 0. So (F(x+h)−F(x))/h→f(x)(F(x + h) - F(x))/h \to f(x). The case h<0h < 0 is the same.
    3. For part 2: (F−G)′=f−f=0(F - G)' = f - f = 0, so F−GF - G is a constant CC (mean value theorem, lesson 01).
    4. Then G(b)−G(a)=F(b)−F(a)=∫abf−0G(b) - G(a) = F(b) - F(a) = \int_a^b f - 0. ■\blacksquare

    Substitution (the 1-D change of variables). Let gg have a continuous derivative on [c,d][c, d], and let ff be continuous. Then

    ∫g(c)g(d)f(x) dx=∫cdf(g(y)) g′(y) dy.\int_{g(c)}^{g(d)} f(x)\,dx = \int_c^d f(g(y))\,g'(y)\,dy .

    Proof. Let GG be an antiderivative of ff. By the chain rule (lesson 04), ddyG(g(y))=f(g(y)) g′(y)\frac{d}{dy}G(g(y)) = f(g(y))\,g'(y). Apply the FTC to both sides: each side equals G(g(d))−G(g(c))G(g(d)) - G(g(c)). ■\blacksquare

    If gg is one-to-one, write the image interval as I=g([c,d])I = g([c, d]). When gg is decreasing, g(d)<g(c)g(d) < g(c): the limits come out swapped, and swapping them back changes the sign. Both cases give one formula with an absolute value:

    ∫If(x) dx=∫cdf(g(y)) ∣g′(y)∣ dy.\int_I f(x)\,dx = \int_c^d f(g(y))\,|g'(y)|\,dy .

    This is the form that generalizes to dd dimensions. Example: with x=g(y)=y2x = g(y) = y^2, ∫012y ey2 dy=∫01ex dx=e−1=1.7183\int_0^1 2y\,e^{y^2}\,dy = \int_0^1 e^x\,dx = e - 1 = 1.7183.

    Integration by parts. From the product rule (uv)′=u′v+uv′(uv)' = u'v + uv' and the FTC:

    ∫abu(x) v′(x) dx=[u(x) v(x)]ab−∫abu′(x) v(x) dx.\int_a^b u(x)\,v'(x)\,dx = \big[u(x)\,v(x)\big]_a^b - \int_a^b u'(x)\,v(x)\,dx .

    Lessons 12 and 13 use it all the time. One example that appears in ML is Stein's lemma. Let X∼N(0,1)X \sim N(0, 1) with density φ(x)=e−x2/2/2π\varphi(x) = e^{-x^2/2}/\sqrt{2\pi}, so φ′(x)=−x φ(x)\varphi'(x) = -x\,\varphi(x). Take u=fu = f and v=−φv = -\varphi. If fφ→0f\varphi \to 0 at ±∞\pm\infty, the boundary term vanishes, and

    E[Xf(X)]=∫f(x) xφ(x) dx=∫f′(x) φ(x) dx=E[f′(X)].\mathbb E[X f(X)] = \int f(x)\,x\varphi(x)\,dx = \int f'(x)\,\varphi(x)\,dx = \mathbb E[f'(X)] .

    For f=sin⁡f = \sin: E[Xsin⁡X]=E[cos⁡X]=e−1/2=0.6065\mathbb E[X\sin X] = \mathbb E[\cos X] = e^{-1/2} = 0.6065.

    3.2 Expectations are integrals #

    A random variable XX in Rd\R^d has a density pXp_X if pX≥0p_X \ge 0, ∫pX(x) dx=1\int p_X(x)\,dx = 1, and P(X∈B)=∫BpX(x) dxP(X \in B) = \int_B p_X(x)\,dx for every (measurable) set BB. A density is not a probability: it is probability per unit volume. So it can be larger than 1. The uniform density on (0,1/2)(0, 1/2) is 2.

    The expectation of f(X)f(X) is the integral

    E[f(X)]=∫f(x) pX(x) dx,\mathbb E[f(X)] = \int f(x)\,p_X(x)\,dx ,

    defined when ∫∣f(x)∣ pX(x) dx<∞\int |f(x)|\,p_X(x)\,dx < \infty. You do not need the density of f(X)f(X) for this; the density of XX is enough. A 1-D integral is also an expectation: ∫abf(x) dx=(b−a) E[f(U)]\int_a^b f(x)\,dx = (b - a)\,\mathbb E[f(U)] with UU uniform on [a,b][a, b]. This is how the Monte Carlo mode of the figure works.

    Monte Carlo. Draw x1,…,xNx_1, \dots, x_N independently from pXp_X, and take the average

    μ^N=1N∑i=1Nf(xi).\hat\mu_N = \frac1N \sum_{i=1}^{N} f(x_i) .
    1. Unbiased. E[μ^N]=1N∑iE[f(xi)]=μ\mathbb E[\hat\mu_N] = \frac1N \sum_i \mathbb E[f(x_i)] = \mu, where μ=E[f(X)]\mu = \mathbb E[f(X)].
    2. Variance. The terms are independent, so their variances add: Var⁡(μ^N)=1N2⋅Nσ2=σ2/N\operatorname{Var}(\hat\mu_N) = \frac{1}{N^2}\cdot N\sigma^2 = \sigma^2/N, where σ2=Var⁡f(X)\sigma^2 = \operatorname{Var} f(X).
    3. Standard error. The typical error is σ/N\sigma/\sqrt N. By the central limit theorem, μ^N\hat\mu_N is within ±2σ/N\pm 2\sigma/\sqrt N of μ\mu in about 95% of runs. In practice you estimate σ\sigma by the sample standard deviation.

    The rate 1/N1/\sqrt N does not depend on the dimension dd. A grid rule with nn points in dd dimensions has only n1/dn^{1/d} points per axis, so the midpoint error is O(n−2/d)O(n^{-2/d}). For d>4d > 4, Monte Carlo wins. This is why high-dimensional expectations in ML are estimated by sampling. Variance reduction and importance sampling are in the probability and statistics track.

    Example. X∼N(0,1)X \sim N(0, 1) and f(x)=x2f(x) = x^2: μ=1\mu = 1 and σ2=E[X4]−1=3−1=2\sigma^2 = \mathbb E[X^4] - 1 = 3 - 1 = 2. With N=10 000N = 10\,000 samples, the standard error is 2/10 000=0.0141\sqrt{2/10\,000} = 0.0141.

    Quick check

    A Monte Carlo estimate with N=100N = 100 samples has standard error 0.20.2. How many samples do you need for a standard error of 0.050.05?

    3.3 Multiple integrals and Fubini's theorem #

    A double integral ∫Rf(x,y) d(x,y)\int_R f(x, y)\,d(x, y) over a rectangle RR is the limit of sums over small rectangles of area Δx Δy\Delta x\,\Delta y, in the same way as in 1-D. To compute it, we integrate one variable at a time: an iterated integral. The theorems below say when the order does not matter. Write a point of Rm+k\R^{m+k} as (x,y)(x, y) with x∈Rmx \in \R^m, y∈Rky \in \R^k.

    • Tonelli's theorem. If f≥0f \ge 0, then ∫f(x,y) d(x,y)=∫(∫f(x,y) dy) dx=∫(∫f(x,y) dx) dy\int f(x, y)\,d(x, y) = \int \big(\int f(x, y)\,dy\big)\,dx = \int \big(\int f(x, y)\,dx\big)\,dy. All three may be +∞+\infty, but they are always equal.
    • Fubini's theorem. The same equalities hold for every ff with ∫∣f(x,y)∣ d(x,y)<∞\int |f(x, y)|\,d(x, y) < \infty.
    • Product case. ∫f(x) g(y) d(x,y)=(∫f(x) dx)(∫g(y) dy)\int f(x)\,g(y)\,d(x, y) = \big(\int f(x)\,dx\big)\big(\int g(y)\,dy\big).

    Example: ∫01 ⁣∫02xy2 dy dx=∫01x⋅83 dx=43\int_0^1\!\int_0^2 x y^2\,dy\,dx = \int_0^1 x \cdot \tfrac83\,dx = \tfrac43, and in the other order ∫02y2⋅12 dy=43\int_0^2 y^2 \cdot \tfrac12\,dy = \tfrac43. In probability, Fubini's theorem lets you compute an expectation over (X,Y)(X, Y) one variable at a time, and swap a sum and an expectation.

    When the order matters: a counterexample

    Take f(x,y)=x2−y2(x2+y2)2f(x, y) = \dfrac{x^2 - y^2}{(x^2 + y^2)^2} on (0,1)2(0, 1)^2.

    1. Since ∂∂yyx2+y2=x2−y2(x2+y2)2\frac{\partial}{\partial y}\frac{y}{x^2 + y^2} = \frac{x^2 - y^2}{(x^2 + y^2)^2}, the inner integral is ∫01f(x,y) dy=11+x2\int_0^1 f(x, y)\,dy = \frac{1}{1 + x^2}.
    2. So ∫01 ⁣∫01f dy dx=∫01dx1+x2=arctan⁡1=π4\int_0^1\!\int_0^1 f\,dy\,dx = \int_0^1 \frac{dx}{1 + x^2} = \arctan 1 = \frac\pi4.
    3. But f(y,x)=−f(x,y)f(y, x) = -f(x, y), so the other order gives −π4-\frac\pi4.

    The two orders disagree. Fubini does not apply here, because ∫∣f∣=∞\int |f| = \infty. In polar coordinates f=cos⁡(2θ)/r2f = \cos(2\theta)/r^2, so near the corner (0,0)(0, 0) the integral of ∣f∣|f| contains ∫01r2 r dr=∫0drr=∞\int_0 \frac{1}{r^2}\,r\,dr = \int_0 \frac{dr}{r} = \infty.

    3.4 Polar coordinates #

    Polar coordinates describe a point of the plane by its distance rr from the origin and its angle θ\theta: T(r,θ)=(rcos⁡θ, rsin⁡θ)T(r, \theta) = (r\cos\theta,\ r\sin\theta). The Jacobian is

    DT(r,θ)=(cos⁡θ−rsin⁡θsin⁡θrcos⁡θ),DT(r, \theta) = \begin{pmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{pmatrix},

    so det⁡DT=rcos⁡2θ+rsin⁡2θ=r\det DT = r\cos^2\theta + r\sin^2\theta = r.

    So the area element is dx dy=r dr dθdx\,dy = r\,dr\,d\theta. The picture: a small polar cell has a radial side Δr\Delta r and an arc side r Δθr\,\Delta\theta (an arc of angle Δθ\Delta\theta on a circle of radius rr). It is almost a rectangle, so its area is about r Δr Δθr\,\Delta r\,\Delta\theta. Cells far from the origin are bigger.

    Interactive figure: loading…

    Drag the violet corner of the cell, and change Δr\Delta r and Δθ\Delta\theta. The cell has a radial side Δr\Delta r and an arc r Δθr\,\Delta\theta. Compare its exact area with r Δr Δθr\,\Delta r\,\Delta\theta and with Δr Δθ\Delta r\,\Delta\theta. For a small cell, the first ratio is close to 1 everywhere. The second ratio is close to 1/r1/r: it is wrong except at r=1r = 1.

    For an integrable ff on R2\R^2:

    ∫R2f(x,y) dx dy=∫02π ⁣ ⁣∫0∞f(rcos⁡θ,rsin⁡θ) r dr dθ.\int_{\R^2} f(x, y)\,dx\,dy = \int_0^{2\pi}\!\!\int_0^\infty f(r\cos\theta, r\sin\theta)\,r\,dr\,d\theta .

    (The origin and the ray θ=0\theta = 0 are missing from the image of (0,∞)×(0,2π)(0, \infty) \times (0, 2\pi), but they have area 0, so they do not change the integral.) Worked example (a) uses this formula, and lesson 11 uses it to compute ∫e−x2dx=π\int e^{-x^2}dx = \sqrt\pi.

    Quick check

    In polar coordinates x=rcos⁡θx = r\cos\theta, y=rsin⁡θy = r\sin\theta, which expression replaces dx dydx\,dy?

    3.5 Change of variables in dd dimensions #

    A diffeomorphism T:V→UT: V \to U between open sets of Rd\R^d is a one-to-one map onto UU such that TT and T−1T^{-1} both have continuous derivatives. For a one-to-one map with a continuous derivative, this holds exactly when det⁡DT(y)≠0\det DT(y) \ne 0 everywhere (inverse function theorem). Then D(T−1)(x)=[DT(y)]−1D(T^{-1})(x) = [DT(y)]^{-1} at x=T(y)x = T(y).

    Theorem (change of variables). Let T:V→UT: V \to U be a diffeomorphism and ff integrable on UU. Then

    ∫Uf(x) dx=∫Vf(T(y)) ∣det⁡DT(y)∣ dy.\int_U f(x)\,dx = \int_V f(T(y))\,|\det DT(y)|\,dy .

    In words: substitute x=T(y)x = T(y), and replace dxdx by ∣det⁡DT(y)∣ dy|\det DT(y)|\,dy. In 1-D this is the substitution rule with ∣g′∣|g'|. For polar coordinates it gives r dr dθr\,dr\,d\theta.

    Why it is true (proof sketch)
    1. Linear maps. A linear map AA sends a box QQ to a parallelepiped of volume ∣det⁡A∣ vol(Q)|\det A|\,\mathrm{vol}(Q) (linear algebra lesson 03).
    2. Small cubes. Let QQ be a cube of side ε\varepsilon centred at yy. By the linear approximation (lesson 03), T(y+h)=T(y)+DT(y) h+o(∥h∥)T(y + h) = T(y) + DT(y)\,h + o(\|h\|). So T(Q)T(Q) differs from the parallelepiped T(y)+DT(y)(Q−y)T(y) + DT(y)(Q - y) only by o(ε)o(\varepsilon) near its boundary, and vol(T(Q))=∣det⁡DT(y)∣ εd+o(εd)\mathrm{vol}(T(Q)) = |\det DT(y)|\,\varepsilon^d + o(\varepsilon^d).
    3. Sum over cubes. Cut VV into small cubes QiQ_i with centres yiy_i. Their images T(Qi)T(Q_i) cut UU into small pieces, so ∫Uf dx=∑i∫T(Qi)f dx≈∑if(T(yi)) ∣det⁡DT(yi)∣ εd\int_U f\,dx = \sum_i \int_{T(Q_i)} f\,dx \approx \sum_i f(T(y_i))\,|\det DT(y_i)|\,\varepsilon^d.
    4. The right side is a Riemann sum of f(T(y)) ∣det⁡DT(y)∣f(T(y))\,|\det DT(y)| over VV. As ε→0\varepsilon \to 0 it tends to ∫Vf(T(y)) ∣det⁡DT(y)∣ dy\int_V f(T(y))\,|\det DT(y)|\,dy.

    A full proof must show that the errors in steps 2–3 are small uniformly over all cubes. See Spivak, Calculus on Manifolds, theorem 3-13, or Munkres, Analysis on Manifolds, §17–19.

    3.6 The density of a transformed random variable #

    Theorem (change of variables for densities). Let XX have the density pXp_X on an open set U⊆RdU \subseteq \R^d, let g:U→Vg: U \to V be a diffeomorphism, and let Y=g(X)Y = g(X). Then for y∈Vy \in V, with x=g−1(y)x = g^{-1}(y):

    pY(y)=pX(g−1(y)) ∣det⁡Dg−1(y)∣=pX(x)∣det⁡Dg(x)∣,p_Y(y) = p_X\big(g^{-1}(y)\big)\,\big|\det Dg^{-1}(y)\big| = \frac{p_X(x)}{|\det Dg(x)|},

    and in log form

    log⁡pY(y)=log⁡pX(x)−log⁡∣det⁡Dg(x)∣.\log p_Y(y) = \log p_X(x) - \log|\det Dg(x)| .

    Read it as conservation of probability: "density times volume" is the same before and after the map, pY(y) ∣dy∣=pX(x) ∣dx∣p_Y(y)\,|dy| = p_X(x)\,|dx|.

    Proof.

    1. 1-D, gg increasing. The cumulative distribution function (CDF) of YY is FY(y)=P(g(X)≤y)=P(X≤g−1(y))=FX(g−1(y))F_Y(y) = P(g(X) \le y) = P(X \le g^{-1}(y)) = F_X(g^{-1}(y)). Differentiate with the chain rule: pY(y)=pX(g−1(y)) (g−1)′(y)p_Y(y) = p_X(g^{-1}(y))\,(g^{-1})'(y), and (g−1)′>0(g^{-1})' > 0.
    2. 1-D, gg decreasing. Now g(X)≤yg(X) \le y exactly when X≥g−1(y)X \ge g^{-1}(y), so FY(y)=1−FX(g−1(y))F_Y(y) = 1 - F_X(g^{-1}(y)) and pY(y)=−pX(g−1(y)) (g−1)′(y)p_Y(y) = -p_X(g^{-1}(y))\,(g^{-1})'(y), with (g−1)′<0(g^{-1})' < 0. Both cases give pY(y)=pX(g−1(y)) ∣(g−1)′(y)∣p_Y(y) = p_X(g^{-1}(y))\,|(g^{-1})'(y)|.
    3. dd dimensions. A CDF is not convenient in Rd\R^d, so we use sets. For every set B⊆VB \subseteq V: P(Y∈B)=P(X∈g−1(B))=∫g−1(B)pX(x) dxP(Y \in B) = P(X \in g^{-1}(B)) = \int_{g^{-1}(B)} p_X(x)\,dx.
    4. Change variables with T=g−1T = g^{-1}, which maps BB onto g−1(B)g^{-1}(B) (section 3.5): P(Y∈B)=∫BpX(g−1(y)) ∣det⁡Dg−1(y)∣ dyP(Y \in B) = \int_B p_X(g^{-1}(y))\,|\det Dg^{-1}(y)|\,dy.
    5. This holds for every BB. A density is fixed by its integrals over all sets (up to a set of volume zero), so the integrand is pYp_Y.
    6. By the inverse function theorem, Dg−1(y)=[Dg(x)]−1Dg^{-1}(y) = [Dg(x)]^{-1}, and det⁡(M−1)=1/det⁡M\det(M^{-1}) = 1/\det M. Take logs. ■\blacksquare

    Which way does the Jacobian go? The two maps go in opposite directions. In the integral formula of section 3.5, TT maps the new variable yy to the old variable xx. Here gg maps XX to YY, and the proof uses the integral formula with T=g−1T = g^{-1}. A quick check: for Y=2XY = 2X the density must go down, so you divide by ∣g′∣=2|g'| = 2.

    Maps that are not one-to-one. Suppose UU splits into pieces U1,…,UKU_1, \dots, U_K (up to a set of volume zero), and gg is a diffeomorphism from each UkU_k onto its image. Each piece is a branch. Then P(Y∈B)=∑kP(X∈Uk, g(X)∈B)P(Y \in B) = \sum_k P(X \in U_k,\ g(X) \in B). Apply the theorem on each piece:

    pY(y)=∑k: y∈g(Uk)pX(xk)∣det⁡Dg(xk)∣,xk=the preimage of y in Uk.p_Y(y) = \sum_{k:\ y \in g(U_k)} \frac{p_X(x_k)}{|\det Dg(x_k)|}, \qquad x_k = \text{the preimage of } y \text{ in } U_k .

    Example: Y=X2Y = X^2 with X∼N(0,1)X \sim N(0, 1). The pieces are x<0x < 0 and x>0x > 0. The preimages of y>0y > 0 are ±y\pm\sqrt y, and ∣g′(x)∣=2∣x∣=2y|g'(x)| = 2|x| = 2\sqrt y. So

    pY(y)=φ(y)+φ(−y)2y=e−y/22πy,y>0,p_Y(y) = \frac{\varphi(\sqrt y) + \varphi(-\sqrt y)}{2\sqrt y} = \frac{e^{-y/2}}{\sqrt{2\pi y}}, \qquad y > 0,

    the χ12\chi^2_1 density. With one branch only, you get half of it, and it integrates to 1/21/2.

    3.7 Compositions, triangular Jacobians and coupling layers #

    Let g=gK∘⋯∘g1g = g_K \circ \dots \circ g_1, with z0=xz_0 = x, zk=gk(zk−1)z_k = g_k(z_{k-1}) and y=zKy = z_K. By the chain rule, Dg(x)=DgK(zK−1)⋯Dg1(z0)Dg(x) = Dg_K(z_{K-1}) \cdots Dg_1(z_0), and the determinant of a product is the product of the determinants. So the log-determinants add:

    log⁡pY(y)=log⁡pX(z0)−∑k=1Klog⁡∣det⁡Dgk(zk−1)∣.\log p_Y(y) = \log p_X(z_0) - \sum_{k=1}^{K} \log\big|\det Dg_k(z_{k-1})\big| .
    • Density evaluation (training by maximum likelihood): start from yy, invert the layers in reverse order (zK−1=gK−1(y)z_{K-1} = g_K^{-1}(y), and so on), and add up the log-determinants on the way.
    • Sampling: draw z0∼pXz_0 \sim p_X and apply g1,…,gKg_1, \dots, g_K.
    • You never form the Jacobian of the whole composition. Each layer needs a cheap inverse (for density evaluation) and a cheap log⁡∣det⁡∣\log|\det|.

    Why "cheap" matters. A dense d×dd \times d determinant costs O(d3)O(d^3) operations (an LU factorization). For a 64×6464 \times 64 RGB image, d=12 288d = 12\,288, for every layer and every sample. This is far too slow inside a training loop.

    Triangular Jacobians. The determinant of a triangular matrix is the product of its diagonal entries. So if DgDg is triangular, log⁡∣det⁡Dg∣=∑ilog⁡∣∂gi/∂xi∣\log|\det Dg| = \sum_i \log|\partial g_i/\partial x_i|: only O(d)O(d) work.

    Affine coupling layer (RealNVP). Split x=(xA,xB)x = (x_A, x_B), where xAx_A holds the first kk coordinates. Let s,t:Rk→Rd−ks, t: \R^k \to \R^{d-k} be any functions (in practice, neural networks), and let ⊙\odot be the elementwise product:

    yA=xA,yB=xB⊙exp⁡(s(xA))+t(xA).y_A = x_A, \qquad y_B = x_B \odot \exp(s(x_A)) + t(x_A) .
    1. Jacobian. yAy_A does not depend on xBx_B, so the upper-right block is 00. Among the coordinates of xBx_B, each yB,iy_{B,i} depends only on xB,ix_{B,i}, so the lower-right block is diagonal:
    Dg=(Ik0∂yB/∂xAdiag⁡(exp⁡(s(xA)))).Dg = \begin{pmatrix} I_k & 0 \\ \partial y_B/\partial x_A & \operatorname{diag}\big(\exp(s(x_A))\big) \end{pmatrix}.
    1. Log-determinant. The matrix is block lower-triangular, so log⁡∣det⁡Dg∣=∑isi(xA)\log|\det Dg| = \sum_i s_i(x_A). The block ∂yB/∂xA\partial y_B/\partial x_A holds the derivatives of the networks ss and tt, but it never enters the determinant.
    2. Inverse. xA=yAx_A = y_A and xB=(yB−t(yA))⊙exp⁡(−s(yA))x_B = (y_B - t(y_A)) \odot \exp(-s(y_A)). This needs only forward passes of ss and tt, never their inverses. So ss and tt can be any networks.
    3. Price. One layer does not change xAx_A, and it acts on xBx_B as an affine map. So we stack layers and swap (or permute) the roles of AA and BB between layers.
    Interactive figure: loading…

    Add layers with the slider, then drag the violet point yy. The shading is the exact density pYp_Y, computed by inverting the layers. The dots are samples of the base Gaussian pushed through the layers. The dashed path goes back from yy through the layers to the base point z0z_0. The readout lists each layer's log⁡∣det⁡J∣=sk\log|\det J| = s_k and subtracts their sum from log⁡pZ(z0)\log p_Z(z_0). The sum of pYp_Y times the cell area stays close to 1: the layers move probability, they do not create it.

    Autoregressive flows (MAF, IAF: yiy_i depends on x1,…,xix_1, \dots, x_i) also have triangular Jacobians. Continuous flows dz/dt=f(z,t)dz/dt = f(z, t) use the continuous version ddtlog⁡p(z(t))=−tr⁡(∂f/∂z)\frac{d}{dt}\log p(z(t)) = -\operatorname{tr}\big(\partial f/\partial z\big); the trace is estimated without forming the Jacobian (lesson 08). Both are treated in the generative models track (normalizing flows, flow matching).

    Quick check

    A coupling layer acts on x∈Rdx \in \R^{d} with d=1000d = 1000. What does it cost to compute its log⁡∣det⁡J∣\log|\det J|, once s(xA)s(x_A) is known?

    Answers to section 1. (1) pY(1)=1/2p_Y(1) = 1/2: g−1(y)=y/2g^{-1}(y) = y/2, so pY(y)=1⋅12p_Y(y) = 1 \cdot \frac12 on (0,2)(0, 2). (2) No. The mode of Y=eXY = e^X is at 1/e≈0.3681/e \approx 0.368 (computed in section 4). A nonlinear map does not carry the mode along, because the Jacobian factor 1/y1/y is not constant. The mean does not move that way either: E[eX]=e1/2=1.6487\mathbb E[e^X] = e^{1/2} = 1.6487, not e0e^0. (3) No. Its area is about r Δr Δθr\,\Delta r\,\Delta\theta, because the arc side has length r Δθr\,\Delta\theta. Only at r=1r = 1 is Δr Δθ\Delta r\,\Delta\theta right.

    4. Worked example #

    (a) A Gaussian bump over a disk, in polar coordinates. Compute I(R)=∬x2+y2≤R2e−(x2+y2) dx dyI(R) = \iint_{x^2 + y^2 \le R^2} e^{-(x^2 + y^2)}\,dx\,dy.

    1. In polar coordinates the disk is 0≤r≤R0 \le r \le R, 0≤θ<2π0 \le \theta < 2\pi, the integrand is e−r2e^{-r^2}, and dx dy=r dr dθdx\,dy = r\,dr\,d\theta.
    2. The integrand is a product of a function of θ\theta (the constant 1) and a function of rr, so by Fubini: I(R)=∫02πdθ⋅∫0Re−r2 r dr=2π∫0Re−r2 r drI(R) = \int_0^{2\pi} d\theta \cdot \int_0^R e^{-r^2}\,r\,dr = 2\pi \int_0^R e^{-r^2}\,r\,dr.
    3. Substitute u=r2u = r^2, du=2r drdu = 2r\,dr: ∫0Re−r2 r dr=12∫0R2e−u du=12(1−e−R2)\int_0^R e^{-r^2}\,r\,dr = \frac12\int_0^{R^2} e^{-u}\,du = \frac12\big(1 - e^{-R^2}\big).
    4. So I(R)=π(1−e−R2)I(R) = \pi\big(1 - e^{-R^2}\big). For R=1R = 1: π(1−e−1)=1.9859\pi(1 - e^{-1}) = 1.9859. As R→∞R \to \infty, I→πI \to \pi.

    In Cartesian coordinates, e−x2e^{-x^2} has no elementary antiderivative. The extra factor rr from polar coordinates is exactly what makes the substitution possible. Lesson 11 uses I(∞)=πI(\infty) = \pi to get ∫e−x2dx=π\int e^{-x^2}dx = \sqrt\pi.

    (b) The log-normal density. X∼N(0,1)X \sim N(0, 1) and Y=eXY = e^X. Then g−1(y)=log⁡yg^{-1}(y) = \log y and (g−1)′(y)=1/y>0(g^{-1})'(y) = 1/y > 0, so for y>0y > 0:

    pY(y)=φ(log⁡y)y,log⁡pY(y)=−12(log⁡y)2−log⁡y−12log⁡2π.p_Y(y) = \frac{\varphi(\log y)}{y}, \qquad \log p_Y(y) = -\tfrac12(\log y)^2 - \log y - \tfrac12\log 2\pi .
    • pY(1)=φ(0)=0.3989p_Y(1) = \varphi(0) = 0.3989 and pY(e)=φ(1)/e=0.2420/2.7183=0.0890p_Y(e) = \varphi(1)/e = 0.2420/2.7183 = 0.0890.
    • Mode. ddylog⁡pY(y)=−log⁡yy−1y=0\frac{d}{dy}\log p_Y(y) = -\frac{\log y}{y} - \frac1y = 0 gives log⁡y=−1\log y = -1, so y=1/e≈0.368y = 1/e \approx 0.368. There pY(1/e)=φ(−1) e=0.2420⋅2.7183=0.6577p_Y(1/e) = \varphi(-1)\,e = 0.2420 \cdot 2.7183 = 0.6577. The term −log⁡y-\log y (the log-Jacobian) moves the peak away from e0=1e^0 = 1.

    (c) One coupling layer in 2-D. The base is X∼N(0,I2)X \sim N(0, I_2). Keep x1x_1, and transform x2x_2 with s(x1)=x1/2s(x_1) = x_1/2 and t(x1)=x12t(x_1) = x_1^2: y1=x1y_1 = x_1, y2=x2 ex1/2+x12y_2 = x_2\,e^{x_1/2} + x_1^2. Evaluate log⁡pY\log p_Y at y=(1,2)y = (1, 2). (This is the "coupling layer" map of the second figure.)

    1. Invert. x1=y1=1x_1 = y_1 = 1, and x2=(y2−t(1)) e−s(1)=(2−1) e−0.5=0.6065x_2 = (y_2 - t(1))\,e^{-s(1)} = (2 - 1)\,e^{-0.5} = 0.6065.
    2. Jacobian at xx. ∂y2/∂x1=x2es s′(x1)+t′(x1)=1⋅0.5+2=2.5\partial y_2/\partial x_1 = x_2 e^{s}\,s'(x_1) + t'(x_1) = 1 \cdot 0.5 + 2 = 2.5 (because x2es=y2−t=1x_2 e^{s} = y_2 - t = 1). So Dg=(102.5e0.5)Dg = \begin{pmatrix}1 & 0\\ 2.5 & e^{0.5}\end{pmatrix}, det⁡Dg=e0.5=1.6487\det Dg = e^{0.5} = 1.6487, and log⁡∣det⁡Dg∣=0.5=s(x1)\log|\det Dg| = 0.5 = s(x_1). The entry 2.52.5 plays no role.
    3. Base log-density. log⁡pX(x)=−log⁡2π−12(12+0.60652)=−1.8379−0.6839=−2.5218\log p_X(x) = -\log 2\pi - \tfrac12(1^2 + 0.6065^2) = -1.8379 - 0.6839 = -2.5218.
    4. Result. log⁡pY(1,2)=−2.5218−0.5=−3.0218\log p_Y(1, 2) = -2.5218 - 0.5 = -3.0218, so pY(1,2)=0.0487p_Y(1, 2) = 0.0487.

    In closed form, pY(y1,y2)=φ(y1) φ((y2−y12)e−y1/2) e−y1/2p_Y(y_1, y_2) = \varphi(y_1)\,\varphi\big((y_2 - y_1^2)e^{-y_1/2}\big)\,e^{-y_1/2}. It must integrate to 1; the code checks this.

    5. In code #

    NumPy and SciPy check the hand computations. The notebook has these cells and the exercises.

    import numpy as np
    from scipy import integrate, stats
    
    # (1) midpoint rule for the integral of x^2 on [0, 1], and Monte Carlo for E[X^2]
    for n in [4, 8]:
        m = (np.arange(n) + 0.5) / n                 # midpoints, h = 1/n
        M = np.mean(m**2)                            # h * sum f(m_i)
        print(n, M, 1/3 - M)
    # 4 0.328125 0.0052083...
    # 8 0.33203125 0.0013020...      (error / 4 when n doubles)
    rng = np.random.default_rng(0)
    fx = rng.standard_normal(10_000) ** 2
    print(fx.mean().round(4), (fx.std(ddof=1) / np.sqrt(len(fx))).round(4))
    # 0.9962 0.014                   (true value 1, standard error about 0.0141)
    
    # (2) polar coordinates: integral of exp(-(x^2 + y^2)) over the unit disk
    val, _ = integrate.dblquad(lambda y, x: np.exp(-(x*x + y*y)), -1, 1,
                               lambda x: -np.sqrt(1 - x*x), lambda x: np.sqrt(1 - x*x))
    print(round(val, 5), round(np.pi * (1 - np.exp(-1)), 5))   # 1.98587 1.98587
    
    # (3) log-normal density phi(log y) / y against scipy
    phi = stats.norm.pdf
    for y in [1, np.e, np.exp(-1)]:
        print(round(phi(np.log(y)) / y, 4), round(stats.lognorm(s=1).pdf(y), 4))
    # 0.3989 0.3989 / 0.089 0.089 / 0.6577 0.6577
    
    # (4) the coupling layer of example (c): Jacobian by central differences, then log p
    def g(x):
        return np.array([x[0], x[1] * np.exp(x[0] / 2) + x[0]**2])
    
    x = np.array([1.0, np.exp(-0.5)])
    print(g(x))                                     # [1. 2.]
    eps = 1e-6
    J = np.column_stack([(g(x + eps * e) - g(x - eps * e)) / (2 * eps) for e in np.eye(2)])
    print(J.round(4))                               # [[1. 0.] [2.5 1.6487]]: lower triangular
    logp = stats.norm.logpdf(x).sum() - np.log(abs(np.linalg.det(J)))
    print(round(logp, 4))                           # -3.0218
    
    # the closed-form density of Y integrates to 1
    p_y = lambda y2, y1: phi(y1) * phi((y2 - y1**2) * np.exp(-y1 / 2)) * np.exp(-y1 / 2)
    total, _ = integrate.dblquad(p_y, -9, 9, lambda a: a**2 - 12 * np.exp(a / 2),
                                 lambda a: a**2 + 12 * np.exp(a / 2))
    print(round(total, 6))                          # 1.0
    

    In real code, never compute det and then log: for large dd the determinant overflows or underflows. Add up the logs of the diagonal of a triangular Jacobian, or use np.linalg.slogdet. Libraries such as torch.distributions.TransformedDistribution do exactly the sum of section 3.7: they invert each transform in reverse order and subtract each log_abs_det_jacobian.

    6. Where it shows up #

    • Training losses are Monte Carlo estimates. The average loss over a mini-batch estimates the expected loss over the data distribution, with an error that falls like 1/B1/\sqrt{B} in the batch size BB. The ELBO of a VAE and the policy-gradient objective are expectations estimated by sampling; their gradients are the topic of lesson 12.
    • Normalizing flows. RealNVP and Glow (coupling layers), MAF and IAF (autoregressive layers) are trained with the exact log-likelihood log⁡pZ(z0)−∑klog⁡∣det⁡Jk∣\log p_Z(z_0) - \sum_k \log|\det J_k|. See the generative models track.
    • Continuous flows and diffusion likelihoods. Neural ODE flows, flow matching and the probability-flow ODE of diffusion models compute log⁡p\log p by integrating −tr⁡(∂f/∂z)-\operatorname{tr}(\partial f/\partial z) along the trajectory. The PDE behind it is conservation of probability, the continuity equation ∂tp+∇⋅(pf)=0\partial_t p + \nabla \cdot (p f) = 0.
    • Sampling. Inverse-CDF sampling (X=F−1(U)X = F^{-1}(U) for UU uniform); Box–Muller, which uses polar coordinates to turn two uniform numbers into two independent N(0,1)N(0, 1) samples (X=−2log⁡U1cos⁡(2πU2)X = \sqrt{-2\log U_1}\cos(2\pi U_2)); and the reparameterization x=μ+σ⊙ϵx = \mu + \sigma \odot \epsilon of VAEs.
    • Priors and parameterizations. A flat prior on σ\sigma is not flat on log⁡σ\log\sigma: p(log⁡σ)=p(σ) σp(\log\sigma) = p(\sigma)\,\sigma. So MAP estimates and the Laplace approximation (lesson 11) change when you reparameterize. The maximum likelihood estimate does not, because the likelihood is a function of the parameter, not a density over it.
    • ML for science. Models often predict log-transformed targets (log-amplitudes of ground motion, log-precipitation, log-permeability). A model trained on u=log⁡yu = \log y has −log⁡pY(y)=−log⁡pU(log⁡y)+log⁡y-\log p_Y(y) = -\log p_U(\log y) + \log y. So you must add the mean of log⁡y\log y before you compare its negative log-likelihood with a model trained on yy. In the same way, a flow on images that rescales pixels from [0,256)[0, 256) to [0,1)[0, 1) must add the log-determinant of that scaling before it reports bits per dimension.

    7. Common mistakes #

    • Wrong direction. pY(y)=pX(x)/∣det⁡Dg(x)∣p_Y(y) = p_X(x)/|\det Dg(x)|, not pX(x) ∣det⁡Dg(x)∣p_X(x)\,|\det Dg(x)|. Check with Y=2XY = 2X: the density must go down.
    • Wrong sign in the log form. Going forward through a layer, you subtract log⁡∣det⁡Dg∣\log|\det Dg|. Going backward (from data to base), you add log⁡∣det⁡Dg−1∣\log|\det Dg^{-1}|. They are the same number with opposite signs.
    • Forgetting the absolute value. A reflection has det⁡=−1\det = -1, but densities and volumes are never negative.
    • Forgetting the rr in polar coordinates. dx dy=r dr dθdx\,dy = r\,dr\,d\theta, not dr dθdr\,d\theta.
    • Missing branches. For Y=X2Y = X^2 you need both ±y\pm\sqrt y; one branch gives half the density.
    • Moving the mode or the mean with the map. The mode of g(X)g(X) is not g(mode of X)g(\text{mode of } X), and E[g(X)]≠g(E[X])\mathbb E[g(X)] \ne g(\mathbb E[X]) in general (E[eX]=e1/2\mathbb E[e^X] = e^{1/2} for X∼N(0,1)X \sim N(0, 1)).
    • "A density is at most 1." A density is probability per unit volume. It can be any large number, as long as it integrates to 1.
    • Swapping the order of integration without checking. Fubini needs ∫∣f∣<∞\int|f| < \infty (or f≥0f \ge 0 for Tonelli); otherwise the two orders can give different answers.
    • A full determinant for a stacked flow. Never build the d×dd \times d Jacobian of the whole flow. Add the per-layer log-determinants, and use log⁡\log of the diagonal, not log⁡(det⁡)\log(\det).
    • Dimension change. The density formula needs g:Rd→Rdg: \R^d \to \R^d. A map from Rd\R^d into RD\R^D with D>dD > d has no density on RD\R^D; the volume factor on its image surface is det⁡(Dg⊤Dg)\sqrt{\det(Dg^\top Dg)}.

    8. Check yourself #

    1. XX is uniform on (0,1)(0, 1) and Y=−log⁡XY = -\log X. What is pYp_Y?
      Answergg is decreasing; g−1(y)=e−yg^{-1}(y) = e^{-y} and ∣(g−1)′(y)∣=e−y|(g^{-1})'(y)| = e^{-y}. So pY(y)=1⋅e−yp_Y(y) = 1 \cdot e^{-y} for y>0y > 0: Y∼Exp(1)Y \sim \mathrm{Exp}(1). This is inverse-CDF sampling for the exponential distribution.
    2. x∼N(0,I2)x \sim N(0, I_2) and y=Axy = Ax with A=(1102)A = \begin{pmatrix}1 & 1\\0 & 2\end{pmatrix}. Compute log⁡pY(3,2)\log p_Y(3, 2).
      Answerx=A−1y=(2,1)x = A^{-1}y = (2, 1); log⁡pX(x)=−log⁡2π−5/2=−4.3379\log p_X(x) = -\log 2\pi - 5/2 = -4.3379; log⁡∣det⁡A∣=log⁡2=0.6931\log|\det A| = \log 2 = 0.6931; so log⁡pY=−5.0310\log p_Y = -5.0310. Check: Y∼N(0,AA⊤)Y \sim N(0, AA^\top) with AA⊤=(2224)AA^\top = \begin{pmatrix}2 & 2\\2 & 4\end{pmatrix}, det⁡=4\det = 4, y⊤(AA⊤)−1y=5y^\top(AA^\top)^{-1}y = 5, and −log⁡2π−12log⁡4−52=−5.0310-\log 2\pi - \frac12\log 4 - \frac52 = -5.0310.
    3. X∼N(0,1)X \sim N(0, 1) and Y=∣X∣Y = |X|. What is pYp_Y?
      AnswerTwo branches, x=±yx = \pm y, each with ∣dx/dy∣=1|dx/dy| = 1: pY(y)=2φ(y)p_Y(y) = 2\varphi(y) for y>0y > 0 (the half-normal density). For example pY(1)=0.4839p_Y(1) = 0.4839.
    4. Use polar coordinates to compute ∬x2+y2≤4(x2+y2) dx dy\iint_{x^2 + y^2 \le 4} (x^2 + y^2)\,dx\,dy.
      Answer∫02π ⁣∫02r2⋅r dr dθ=2π⋅244=8π≈25.13\int_0^{2\pi}\!\int_0^2 r^2 \cdot r\,dr\,d\theta = 2\pi \cdot \frac{2^4}{4} = 8\pi \approx 25.13. Without the factor rr you would get 2π⋅83=16.762\pi \cdot \frac83 = 16.76, which is wrong.
    5. A 3-layer flow maps z0↦z1↦z2↦yz_0 \mapsto z_1 \mapsto z_2 \mapsto y. At one sample, log⁡pZ(z0)=−3.0\log p_Z(z_0) = -3.0, and the forward log-determinants are 0.20.2, −0.5-0.5 and 1.11.1. What is log⁡pY(y)\log p_Y(y)?
      Answer−3.0−(0.2−0.5+1.1)=−3.8-3.0 - (0.2 - 0.5 + 1.1) = -3.8.
    6. Model A is trained on u=log⁡yu = \log y and has a test negative log-likelihood (NLL) of 1.201.20 nats per point on the uu scale. Model B is trained on yy and has a test NLL of 1.501.50 nats on the yy scale. The test mean of log⁡y\log y is 0.50.5. Which model is better?
      AnswerConvert A to the yy scale: −log⁡pY(y)=−log⁡pU(log⁡y)+log⁡y-\log p_Y(y) = -\log p_U(\log y) + \log y, so its NLL is 1.20+0.5=1.70>1.501.20 + 0.5 = 1.70 > 1.50. Model B is better.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. State the fundamental theorem of calculus (both parts).

    2. Write the 1-D substitution rule with an absolute value.

    3. Write E[f(X)]\mathbb E[f(X)] for a random variable XX with density pp.

    4. What is the standard error of a Monte Carlo average of NN independent samples?

    5. When may you swap the order of a double integral?

    6. Why is dx dy=r dr dθdx\,dy = r\,dr\,d\theta in polar coordinates?

    7. State the change-of-variables formula for integrals.

    8. Give the log-density of Y=g(X)Y = g(X) for a diffeomorphism gg.

    9. X∼N(0,1)X \sim N(0, 1). What is the density of Y=X2Y = X^2, and why?

    10. What is log⁡∣det⁡J∣\log|\det J| of the affine coupling layer yB=xB⊙es(xA)+t(xA)y_B = x_B \odot e^{s(x_A)} + t(x_A), and why?

    Open the review →

    9. Interview angle #

    • "Derive the density of Y=eXY = e^X for X∼N(μ,σ2)X \sim N(\mu, \sigma^2)." — pY(y)=N(log⁡y;μ,σ2)/yp_Y(y) = N(\log y; \mu, \sigma^2)/y for y>0y > 0; the mode is eμ−σ2e^{\mu - \sigma^2} and the mean is eμ+σ2/2e^{\mu + \sigma^2/2}.
    • "Why must a normalizing flow be invertible, and why do people use coupling layers?" — The likelihood needs g−1g^{-1} and log⁡∣det⁡∣\log|\det|. Coupling layers make both cheap (O(d)O(d) log-determinant, closed-form inverse), while ss and tt can still be any networks.
    • "Write the log-likelihood of a flow." — log⁡pZ(g−1(y))+∑klog⁡∣det⁡Dgk−1∣\log p_Z(g^{-1}(y)) + \sum_k \log|\det Dg_k^{-1}| along the inverse path (equivalently, minus the forward log-determinants).
    • "Is the MAP estimate invariant under reparameterization? The MLE?" — The MLE is; the MAP is not, because the posterior density picks up the Jacobian of the parameter map.
    • "Why is Monte Carlo used for high-dimensional integrals?" — Its error σ/N\sigma/\sqrt N does not depend on the dimension, while a grid rule needs exponentially many points in dd.
    • "How does a continuous normalizing flow compute log⁡p\log p?" — It integrates −tr⁡(∂f/∂z)-\operatorname{tr}(\partial f/\partial z) along the ODE, with a stochastic (Hutchinson) trace estimate.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write riemann_mid and trapezoid, measure their error orders, and write a Monte Carlo estimator with a standard error.
    2. Write pushforward_logpdf_1d for maps with one or more branches, and check it against SciPy and against a histogram.
    3. Write affine_logpdf for Y=AX+bY = AX + b with slogdet, and compare it with scipy.stats.multivariate_normal.
    4. Write coupling_forward and coupling_inverse with their log-determinants, and check that the density of a 2-layer flow integrates to about 1 on a grid.
    5. Compute ∬e−(x2+y2)\iint e^{-(x^2 + y^2)} over a disk on a Cartesian grid and with a 1-D integral in polar coordinates.

    11. Watch and read #

    The integral as a limit of sums of thin rectangles, and why the area function has derivative f.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    What a probability density is, and why it can be larger than 1.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The determinant of the Jacobian as the local area scale factor of a nonlinear map.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Polar coordinates and general substitutions in double integrals, with the Jacobian.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The change-of-variables formula for densities, composition of layers, and coupling layers.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play