Before this lesson:lesson 01 (derivatives in one
variable), lesson 03 (the Jacobian Df 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.
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.
Cut the interval [a,b] into n strips of width h=(b−a)/n. On each strip, put a rectangle
whose height is the value of f at one point of the strip. The sum of the rectangle areas is a
Riemann sum. When n grows, the sum approaches the area under the curve: the integral∫abf(x)dx. Area below the x-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 n random points
u1,…,un, uniform on [a,b], and use (b−a) times the average of f(ui).
Interactive figure: loading…
Change n and the method, and watch the error chart. The shaded strips are the Riemann sum;
the black curve is f. In the log-log chart, each line is the error of one method against n:left sum, midpoint, trapezoid
and the typical Monte Carlo error. The left sum has slope −1 (error
∝1/n). The midpoint and trapezoid rules have slope −2 (error ∝1/n2). Monte Carlo
has slope −1/2: it is the slowest in 1-D.
With n=4, the midpoint rule for ∫01x2dx=1/3 uses the midpoints 0.125,0.375,0.625,0.875:
M4=0.25(0.1252+0.3752+0.6252+0.8752)=0.328125,
so the error is 1/3−0.328125=0.0052.
Quick check
The midpoint rule for ∫01x2dx has error 0.0052 with n=4 strips. About what error do you expect with n=8?
Why.
The midpoint rule has error O(h2). Doubling n halves h, so the error drops by a factor of 22=4:0.0052/4=0.0013. (The exact value is 1/3−0.33203125=0.0013.) The answer 0.0026 assumes an error O(h), which is true for the left sum, not for the midpoint rule.
Now go to two dimensions. A map T sends a point y to a point x=T(y). On a small square
around y0, a smooth map is almost linear: T(y0+h)≈T(y0)+DT(y0)h, where DT(y0)
is the Jacobian matrix (lesson 03). A linear map multiplies
every area by ∣det∣ of its matrix
(linear algebra lesson 03). So the small
square goes to a small curved region with area about ∣detDT(y0)∣ times the area of the square.
Interactive figure: loading…
Drag the violet point, then make the square small. Left: the small square
in the y-coordinates. Right: its image under T and, dashed, the image under
the linear map DT(y0). The readout compares the ratio of the two areas with ∣detDT(y0)∣; they
agree better as the side s shrinks. In the polar map, y=(r,θ) and detDT=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 ∣detDT∣. Each small box of volume
dy in the new coordinates covers a region of volume ∣detDT(y)∣dy in the old ones.
A random variable X with a density pX puts probability pX(x)dx on a small interval of
width dx around x. Take the simplest case: X uniform on (0,1) and Y=2X. Then Y is
uniform on (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/2 on (0,2).
For a general smooth increasing map y=g(x), a small interval [x,x+dx] goes to [y,y+dy]
with dy=g′(x)dx. Both intervals hold the same probability:
pY(y)∣dy∣=pX(x)∣dx∣⟹pY(y)=∣g′(x)∣pX(x),
where x=g−1(y) is the point that g sends to y.
Where g stretches space (∣g′∣>1), the density goes down. Where g compresses space
(∣g′∣<1), the density goes up.
Interactive figure: loading…
Move the violet strip and compare the two violet areas. Top: samples of
X and its density. Bottom: the same samples after the map,
Y=g(X), with the formula pX(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 X2 with
"one branch" and σ(2X), where the density piles up near 0 and 1.
Quick check
X is uniform on (0,1) and Y=2X. What is pY(1)?
Why.
Y is uniform on (0,2), an interval of length 2, and the total probability is 1. So pY=1/2 there. With the formula: pY(y)=pX(y/2)/∣g′∣=1/2. Multiplying by ∣g′∣=2 is the most common mistake: the density goes down where the map stretches.
3.1 The definite integral and the fundamental theorem #
Let f be a function on [a,b]. Cut [a,b] into n pieces [xi−1,xi] of width
h=(b−a)/n, with xi=a+ih, and choose a point ξi in each piece. The Riemann sum is
Sn=i=1∑nf(ξi)h.
f is (Riemann) integrable if Sn tends to the same limit for every choice of the points
ξi as n→∞. This limit is the definite integral∫abf(x)dx. Every
continuous function on [a,b] is integrable.
How fast the rules converge. Let f have a continuous second derivative. Then, for some
points ξ∈[a,b]:
Rule
Height of strip i
Error I−Sn
Order
left sum
f(xi−1)
2h(f(b)−f(a))+O(h2)
O(h)
midpoint
f(2xi−1+xi)
24(b−a)h2f′′(ξ)
O(h2)
trapezoid
21(f(xi−1)+f(xi))
−12(b−a)h2f′′(ξ)
O(h2)
For f(x)=x2 on [0,1],f′′=2, so the midpoint error is exactly h2/12; with h=1/4 this
is 0.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), the left sum equals the trapezoid sum, so it
is also O(h2).)
Theorem (fundamental theorem of calculus, FTC). Let f be continuous on [a,b].
The function F(x)=∫axf(t)dt is differentiable, and F′(x)=f(x).
If G is any antiderivative of f (that is, G′=f on [a,b]), then
∫abf(x)dx=G(b)−G(a).
Proof.
For h>0,F(x+h)−F(x)=∫xx+hf(t)dt. On the small interval [x,x+h],f lies
between its minimum mh and its maximum Mh, so mhh≤F(x+h)−F(x)≤Mhh.
Divide by h. Because f is continuous, mh and Mh both tend to f(x) as h→0. So
(F(x+h)−F(x))/h→f(x). The case h<0 is the same.
For part 2: (F−G)′=f−f=0, so F−G is a constant C (mean value theorem, lesson 01).
Then G(b)−G(a)=F(b)−F(a)=∫abf−0.■
Substitution (the 1-D change of variables). Let g have a continuous derivative on [c,d],
and let f be continuous. Then
∫g(c)g(d)f(x)dx=∫cdf(g(y))g′(y)dy.
Proof. Let G be an antiderivative of f. By the chain rule
(lesson 04), dydG(g(y))=f(g(y))g′(y). Apply
the FTC to both sides: each side equals G(g(d))−G(g(c)).■
If g is one-to-one, write the image interval as I=g([c,d]). When g is decreasing,
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.
This is the form that generalizes to d dimensions. Example: with x=g(y)=y2,∫012yey2dy=∫01exdx=e−1=1.7183.
Integration by parts. From the product rule (uv)′=u′v+uv′ and the FTC:
∫abu(x)v′(x)dx=[u(x)v(x)]ab−∫abu′(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) with density
φ(x)=e−x2/2/2π, so φ′(x)=−xφ(x). Take u=f and v=−φ. If
fφ→0 at ±∞, the boundary term vanishes, and
A random variable X in Rd has a densitypX if pX≥0,∫pX(x)dx=1, and
P(X∈B)=∫BpX(x)dx for every (measurable) set B. 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) is 2.
The expectation of f(X) is the integral
E[f(X)]=∫f(x)pX(x)dx,
defined when ∫∣f(x)∣pX(x)dx<∞. You do not need the density of f(X) for this; the
density of X is enough. A 1-D integral is also an expectation: ∫abf(x)dx=(b−a)E[f(U)]
with U uniform on [a,b]. This is how the Monte Carlo mode of the figure works.
Monte Carlo. Draw x1,…,xN independently from pX, and take the average
μ^N=N1i=1∑Nf(xi).
Unbiased.E[μ^N]=N1∑iE[f(xi)]=μ, where μ=E[f(X)].
Variance. The terms are independent, so their variances add:
Var(μ^N)=N21⋅Nσ2=σ2/N, where σ2=Varf(X).
Standard error. The typical error is σ/N. By the central limit theorem, μ^N is
within ±2σ/N of μ in about 95% of runs. In practice you estimate σ by the
sample standard deviation.
The rate 1/N does not depend on the dimension d. A grid rule with n points in d
dimensions has only n1/d points per axis, so the midpoint error is O(n−2/d). For d>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) and f(x)=x2:μ=1 and σ2=E[X4]−1=3−1=2. With
N=10000 samples, the standard error is 2/10000=0.0141.
Quick check
A Monte Carlo estimate with N=100 samples has standard error 0.2. How many samples do you need for a standard error of 0.05?
Why.
The standard error is σ/N. To divide it by 4, multiply N by 42=16:N=1600. The answer 400 assumes the error falls like 1/N. The square root is the price of Monte Carlo, and it does not depend on the dimension.
A double integral ∫Rf(x,y)d(x,y) over a rectangle R is the limit of sums over small
rectangles of area ΔxΔ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 as (x,y) with x∈Rm,y∈Rk.
Tonelli's theorem. If f≥0, then
∫f(x,y)d(x,y)=∫(∫f(x,y)dy)dx=∫(∫f(x,y)dx)dy.
All three may be +∞, but they are always equal.
Fubini's theorem. The same equalities hold for every f with ∫∣f(x,y)∣d(x,y)<∞.
Product case.∫f(x)g(y)d(x,y)=(∫f(x)dx)(∫g(y)dy).
Example: ∫01∫02xy2dydx=∫01x⋅38dx=34, and in the other order
∫02y2⋅21dy=34. In probability, Fubini's theorem lets you compute an
expectation over (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)2x2−y2 on (0,1)2.
Since ∂y∂x2+y2y=(x2+y2)2x2−y2, the inner integral is
∫01f(x,y)dy=1+x21.
So ∫01∫01fdydx=∫011+x2dx=arctan1=4π.
But f(y,x)=−f(x,y), so the other order gives −4π.
The two orders disagree. Fubini does not apply here, because ∫∣f∣=∞. In polar coordinates
f=cos(2θ)/r2, so near the corner (0,0) the integral of ∣f∣ contains
∫0r21rdr=∫0rdr=∞.
Polar coordinates describe a point of the plane by its distance r from the origin and its angle
θ:T(r,θ)=(rcosθ,rsinθ). The Jacobian is
DT(r,θ)=(cosθsinθ−rsinθrcosθ),
so detDT=rcos2θ+rsin2θ=r.
So the area element is dxdy=rdrdθ. The picture: a small polar cell has a radial side
Δr and an arc side rΔθ (an arc of angle Δθ on a circle of radius r). It is almost a
rectangle, so its area is about rΔrΔθ. Cells far from the origin are bigger.
Interactive figure: loading…
Drag the violet corner of the cell, and change Δr and Δθ. The
cell has a radial side Δr and an
arc rΔθ. Compare its exact area with rΔrΔθ and
with ΔrΔθ. For a small cell, the first ratio is close to 1 everywhere. The second ratio
is close to 1/r: it is wrong except at r=1.
For an integrable f on R2:
∫R2f(x,y)dxdy=∫02π∫0∞f(rcosθ,rsinθ)rdrdθ.
(The origin and the ray θ=0 are missing from the image of (0,∞)×(0,2π), 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=π.
Quick check
In polar coordinates x=rcosθ,y=rsinθ, which expression replaces dxdy?
Why.
detDT(r,θ)=r. A polar cell has sides Δr and rΔθ, so its area is about rΔrΔθ. Without the factor r, cells far from the origin would count as small as cells near it.
A diffeomorphismT:V→U between open sets of Rd is a one-to-one map onto U such that
T and T−1 both have continuous derivatives. For a one-to-one map with a continuous derivative,
this holds exactly when detDT(y)=0 everywhere (inverse function theorem). Then
D(T−1)(x)=[DT(y)]−1 at x=T(y).
Theorem (change of variables). Let T:V→U be a diffeomorphism and f integrable on U. Then
∫Uf(x)dx=∫Vf(T(y))∣detDT(y)∣dy.
In words: substitute x=T(y), and replace dx by ∣detDT(y)∣dy. In 1-D this is the substitution
rule with ∣g′∣. For polar coordinates it gives rdrdθ.
Why it is true (proof sketch)
Linear maps. A linear map A sends a box Q to a parallelepiped of volume ∣detA∣vol(Q)
(linear algebra lesson 03).
Small cubes. Let Q be a cube of side ε centred at y. By the linear approximation
(lesson 03), T(y+h)=T(y)+DT(y)h+o(∥h∥). So T(Q)
differs from the parallelepiped T(y)+DT(y)(Q−y) only by o(ε) near its boundary, and
vol(T(Q))=∣detDT(y)∣εd+o(εd).
Sum over cubes. Cut V into small cubes Qi with centres yi. Their images T(Qi) cut U
into small pieces, so
∫Ufdx=∑i∫T(Qi)fdx≈∑if(T(yi))∣detDT(yi)∣εd.
The right side is a Riemann sum of f(T(y))∣detDT(y)∣ over V. As ε→0 it tends to
∫Vf(T(y))∣detDT(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 X have the density pX on an open set
U⊆Rd, let g:U→V be a diffeomorphism, and let Y=g(X). Then for y∈V, with
x=g−1(y):
pY(y)=pX(g−1(y))detDg−1(y)=∣detDg(x)∣pX(x),
and in log form
logpY(y)=logpX(x)−log∣detDg(x)∣.
Read it as conservation of probability: "density times volume" is the same before and after the map,
pY(y)∣dy∣=pX(x)∣dx∣.
Proof.
1-D, g increasing. The cumulative distribution function (CDF) of Y is FY(y)=P(g(X)≤y)=P(X≤g−1(y))=FX(g−1(y)).
Differentiate with the chain rule: pY(y)=pX(g−1(y))(g−1)′(y), and (g−1)′>0.
1-D, g decreasing. Now g(X)≤y exactly when X≥g−1(y), so
FY(y)=1−FX(g−1(y)) and pY(y)=−pX(g−1(y))(g−1)′(y), with (g−1)′<0.
Both cases give pY(y)=pX(g−1(y))∣(g−1)′(y)∣.
d dimensions. A CDF is not convenient in Rd, so we use sets. For every set B⊆V:P(Y∈B)=P(X∈g−1(B))=∫g−1(B)pX(x)dx.
Change variables with T=g−1, which maps B onto g−1(B) (section 3.5):
P(Y∈B)=∫BpX(g−1(y))∣detDg−1(y)∣dy.
This holds for every B. A density is fixed by its integrals over all sets (up to a set of
volume zero), so the integrand is pY.
By the inverse function theorem, Dg−1(y)=[Dg(x)]−1, and det(M−1)=1/detM. Take
logs. ■
Which way does the Jacobian go? The two maps go in opposite directions. In the integral formula of
section 3.5, T maps the new variable y to the old variable x. Here g maps X to Y, and the
proof uses the integral formula with T=g−1. A quick check: for Y=2X the density must go down,
so you divide by ∣g′∣=2.
Maps that are not one-to-one. Suppose U splits into pieces U1,…,UK (up to a set of
volume zero), and g is a diffeomorphism from each Uk onto its image. Each piece is a branch.
Then P(Y∈B)=∑kP(X∈Uk,g(X)∈B). Apply the theorem on each piece:
pY(y)=k:y∈g(Uk)∑∣detDg(xk)∣pX(xk),xk=the preimage of y in Uk.
Example: Y=X2 with X∼N(0,1). The pieces are x<0 and x>0. The preimages of y>0
are ±y, and ∣g′(x)∣=2∣x∣=2y. So
pY(y)=2yφ(y)+φ(−y)=2πye−y/2,y>0,
the χ12 density. With one branch only, you get half of it, and it integrates to 1/2.
3.7 Compositions, triangular Jacobians and coupling layers #
Let g=gK∘⋯∘g1, with z0=x,zk=gk(zk−1) and y=zK. By the chain rule,
Dg(x)=DgK(zK−1)⋯Dg1(z0), and the determinant of a product is the product of the
determinants. So the log-determinants add:
logpY(y)=logpX(z0)−k=1∑KlogdetDgk(zk−1).
Density evaluation (training by maximum likelihood): start from y, invert the layers in
reverse order (zK−1=gK−1(y), and so on), and add up the log-determinants on the way.
Sampling: draw z0∼pX and apply g1,…,gK.
You never form the Jacobian of the whole composition. Each layer needs a cheap inverse (for
density evaluation) and a cheap log∣det∣.
Why "cheap" matters. A dense d×d determinant costs O(d3) operations (an LU
factorization). For a 64×64 RGB image, d=12288, 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 Dg is triangular, log∣detDg∣=∑ilog∣∂gi/∂xi∣: only O(d) work.
Affine coupling layer (RealNVP). Split x=(xA,xB), where xA holds the first k
coordinates. Let s,t:Rk→Rd−k be any functions (in practice, neural networks), and let
⊙ be the elementwise product:
yA=xA,yB=xB⊙exp(s(xA))+t(xA).
Jacobian.yA does not depend on xB, so the upper-right block is 0. Among the
coordinates of xB, each yB,i depends only on xB,i, so the lower-right block is diagonal:
Dg=(Ik∂yB/∂xA0diag(exp(s(xA)))).
Log-determinant. The matrix is block lower-triangular, so log∣detDg∣=∑isi(xA). The
block ∂yB/∂xA holds the derivatives of the networks s and t, but it never enters
the determinant.
Inverse.xA=yA and xB=(yB−t(yA))⊙exp(−s(yA)). This needs only forward passes of
s and t, never their inverses. So s and t can be any networks.
Price. One layer does not change xA, and it acts on xB as an affine map. So we stack
layers and swap (or permute) the roles of A and B between layers.
Interactive figure: loading…
Add layers with the slider, then drag the violet point y. The
shading is the exact density pY, computed by inverting the layers. The dots
are samples of the base Gaussian pushed through the layers. The
dashed path goes back from y through the layers to the
base point z0. The readout lists each layer's log∣detJ∣=sk and
subtracts their sum from logpZ(z0). The sum of pY times the cell area stays close to 1: the
layers move probability, they do not create it.
Autoregressive flows (MAF, IAF: yi depends on x1,…,xi) also have triangular Jacobians.
Continuous flows dz/dt=f(z,t) use the continuous version
dtdlogp(z(t))=−tr(∂f/∂z); 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∈Rd with d=1000. What does it cost to compute its log∣detJ∣, once s(xA) is known?
Why.
The Jacobian is block lower-triangular with diagonal (1,…,1,es1,…,esd−k). The determinant of a triangular matrix is the product of its diagonal, so log∣detJ∣=∑isi(xA). The O(d3) cost is for a dense matrix; coupling layers are designed to avoid it.
Answers to section 1.
(1) pY(1)=1/2:g−1(y)=y/2, so pY(y)=1⋅21 on (0,2).
(2) No. The mode of Y=eX is at 1/e≈0.368 (computed in section 4). A nonlinear map does not
carry the mode along, because the Jacobian factor 1/y is not constant. The mean does not move that
way either: E[eX]=e1/2=1.6487, not e0.
(3) No. Its area is about rΔrΔθ, because the arc side has length rΔθ. Only at
r=1 is ΔrΔθ right.
So I(R)=π(1−e−R2). For R=1:π(1−e−1)=1.9859. As R→∞,I→π.
In Cartesian coordinates, e−x2 has no elementary antiderivative. The extra factor r from
polar coordinates is exactly what makes the substitution possible.
Lesson 11 uses I(∞)=π to get ∫e−x2dx=π.
(b) The log-normal density.X∼N(0,1) and Y=eX. Then g−1(y)=logy and
(g−1)′(y)=1/y>0, so for y>0:
pY(1)=φ(0)=0.3989 and pY(e)=φ(1)/e=0.2420/2.7183=0.0890.
Mode.dydlogpY(y)=−ylogy−y1=0 gives logy=−1, so y=1/e≈0.368.
There pY(1/e)=φ(−1)e=0.2420⋅2.7183=0.6577. The term −logy (the log-Jacobian)
moves the peak away from e0=1.
(c) One coupling layer in 2-D. The base is X∼N(0,I2). Keep x1, and transform x2 with
s(x1)=x1/2 and t(x1)=x12:y1=x1,y2=x2ex1/2+x12. Evaluate logpY at
y=(1,2). (This is the "coupling layer" map of the second figure.)
Invert.x1=y1=1, and x2=(y2−t(1))e−s(1)=(2−1)e−0.5=0.6065.
Jacobian at x.∂y2/∂x1=x2ess′(x1)+t′(x1)=1⋅0.5+2=2.5 (because
x2es=y2−t=1). So Dg=(12.50e0.5),detDg=e0.5=1.6487, and log∣detDg∣=0.5=s(x1). The entry 2.5 plays no role.
Base log-density.logpX(x)=−log2π−21(12+0.60652)=−1.8379−0.6839=−2.5218.
Result.logpY(1,2)=−2.5218−0.5=−3.0218, so pY(1,2)=0.0487.
In closed form, pY(y1,y2)=φ(y1)φ((y2−y12)e−y1/2)e−y1/2. It must
integrate to 1; the code checks this.
NumPy and SciPy check the hand computations. The notebook has these cells and the exercises.
importnumpyasnpfromscipyimportintegrate,stats# (1) midpoint rule for the integral of x^2 on [0, 1], and Monte Carlo for E[X^2]fornin[4,8]:m=(np.arange(n)+0.5)/n# midpoints, h = 1/nM=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)**2print(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 diskval,_=integrate.dblquad(lambday,x:np.exp(-(x*x+y*y)),-1,1,lambdax:-np.sqrt(1-x*x),lambdax: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 scipyphi=stats.norm.pdfforyin[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 pdefg(x):returnnp.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-6J=np.column_stack([(g(x+eps*e)-g(x-eps*e))/(2*eps)foreinnp.eye(2)])print(J.round(4))# [[1. 0.] [2.5 1.6487]]: lower triangularlogp=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 1p_y=lambday2,y1:phi(y1)*phi((y2-y1**2)*np.exp(-y1/2))*np.exp(-y1/2)total,_=integrate.dblquad(p_y,-9,9,lambdaa:a**2-12*np.exp(a/2),lambdaa:a**2+12*np.exp(a/2))print(round(total,6))# 1.0
In real code, never compute det and then log: for large d 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.
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/B in the batch
size B. 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 logpZ(z0)−∑klog∣detJk∣. See the
generative models track.
Continuous flows and diffusion likelihoods. Neural ODE flows, flow matching and the
probability-flow ODE of diffusion models compute logp by integrating
−tr(∂f/∂z) along the trajectory. The PDE behind it is conservation of
probability, the continuity equation ∂tp+∇⋅(pf)=0.
Sampling. Inverse-CDF sampling (X=F−1(U) for U uniform); Box–Muller, which uses polar
coordinates to turn two uniform numbers into two independent N(0,1) samples
(X=−2logU1cos(2πU2)); and the reparameterization x=μ+σ⊙ϵ of VAEs.
Priors and parameterizations. A flat prior on σ is not flat on logσ:p(logσ)=p(σ)σ. 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=logy has
−logpY(y)=−logpU(logy)+logy. So you must add the mean of logy before you compare its
negative log-likelihood with a model trained on y. In the same way, a flow on images that rescales
pixels from [0,256) to [0,1) must add the log-determinant of that scaling before it reports bits
per dimension.
Wrong direction.pY(y)=pX(x)/∣detDg(x)∣, not pX(x)∣detDg(x)∣. Check with Y=2X: the
density must go down.
Wrong sign in the log form. Going forward through a layer, you subtractlog∣detDg∣. Going
backward (from data to base), you addlog∣detDg−1∣. They are the same number with opposite
signs.
Forgetting the absolute value. A reflection has det=−1, but densities and volumes are never
negative.
Forgetting the r in polar coordinates.dxdy=rdrdθ, not drdθ.
Missing branches. For Y=X2 you need both ±y; one branch gives half the density.
Moving the mode or the mean with the map. The mode of g(X) is not g(mode of X), and
E[g(X)]=g(E[X]) in general (E[eX]=e1/2 for X∼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∣<∞ (or f≥0
for Tonelli); otherwise the two orders can give different answers.
A full determinant for a stacked flow. Never build the d×d Jacobian of the whole flow. Add
the per-layer log-determinants, and use log of the diagonal, not log(det).
Dimension change. The density formula needs g:Rd→Rd. A map from Rd into RD with
D>d has no density on RD; the volume factor on its image surface is det(Dg⊤Dg).
X is uniform on (0,1) and Y=−logX. What is pY?Answerg is decreasing; g−1(y)=e−y and ∣(g−1)′(y)∣=e−y. So pY(y)=1⋅e−y for y>0:Y∼Exp(1). This is inverse-CDF sampling for the exponential distribution.
x∼N(0,I2) and y=Ax with A=(1012). Compute logpY(3,2).Answerx=A−1y=(2,1);logpX(x)=−log2π−5/2=−4.3379;log∣detA∣=log2=0.6931; so logpY=−5.0310. Check: Y∼N(0,AA⊤) with AA⊤=(2224),det=4,y⊤(AA⊤)−1y=5, and −log2π−21log4−25=−5.0310.
X∼N(0,1) and Y=∣X∣. What is pY?AnswerTwo branches, x=±y, each with ∣dx/dy∣=1:pY(y)=2φ(y) for y>0 (the half-normal density). For example pY(1)=0.4839.
Use polar coordinates to compute ∬x2+y2≤4(x2+y2)dxdy.Answer∫02π∫02r2⋅rdrdθ=2π⋅424=8π≈25.13. Without the factor r you would get 2π⋅38=16.76, which is wrong.
A 3-layer flow maps z0↦z1↦z2↦y. At one sample, logpZ(z0)=−3.0, and the forward log-determinants are 0.2,−0.5 and 1.1. What is logpY(y)?Answer−3.0−(0.2−0.5+1.1)=−3.8.
Model A is trained on u=logy and has a test negative log-likelihood (NLL) of 1.20 nats per point on the u scale. Model B is trained on y and has a test NLL of 1.50 nats on the y scale. The test mean of logy is 0.5. Which model is better?AnswerConvert A to the y scale: −logpY(y)=−logpU(logy)+logy, so its NLL is 1.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.
State the fundamental theorem of calculus (both parts).
For continuous f:dxd∫axf(t)dt=f(x), and ∫abf(x)dx=G(b)−G(a) for any G with G′=f.
Write the 1-D substitution rule with an absolute value.
For a one-to-one g with I=g([c,d]):∫If(x)dx=∫cdf(g(y))∣g′(y)∣dy.
Write E[f(X)] for a random variable X with density p.
E[f(X)]=∫f(x)p(x)dx (when ∫∣f∣p<∞).
What is the standard error of a Monte Carlo average of N independent samples?
σ/N, where σ2=Varf(X). It does not depend on the dimension.
When may you swap the order of a double integral?
When f≥0 (Tonelli), or when ∫∣f∣<∞ (Fubini).
Why is dxdy=rdrdθ in polar coordinates?
detDT(r,θ)=r. A small polar cell has sides Δr and rΔθ.
State the change-of-variables formula for integrals.
∫Uf(x)dx=∫Vf(T(y))∣detDT(y)∣dy for a diffeomorphism T:V→U.
Give the log-density of Y=g(X) for a diffeomorphism g.
logpY(y)=logpX(x)−log∣detDg(x)∣, with x=g−1(y).
X∼N(0,1). What is the density of Y=X2, and why?
pY(y)=2yφ(y)+φ(−y)=2πye−y/2: two branches ±y, each divided by ∣g′∣=2y.
What is log∣detJ∣ of the affine coupling layer yB=xB⊙es(xA)+t(xA), and why?
∑isi(xA). The Jacobian is block lower-triangular with diagonal (1,…,1,es(xA)).
"Derive the density of Y=eX for X∼N(μ,σ2)." — pY(y)=N(logy;μ,σ2)/y for y>0;
the mode is eμ−σ2 and the mean is eμ+σ2/2.
"Why must a normalizing flow be invertible, and why do people use coupling layers?" — The likelihood
needs g−1 and log∣det∣. Coupling layers make both cheap (O(d) log-determinant, closed-form
inverse), while s and t can still be any networks.
"Write the log-likelihood of a flow." — logpZ(g−1(y))+∑klog∣detDgk−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 does not depend on
the dimension, while a grid rule needs exponentially many points in d.
"How does a continuous normalizing flow compute logp?" — It integrates
−tr(∂f/∂z) along the ODE, with a stochastic (Hutchinson) trace estimate.
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
Deisenroth, Faisal and Ong, Mathematics for Machine Learning, free PDF:
§6.4 (expectations) and §6.7 (change of variables, theorem 6.16).
Papamakarios, Nalisnick, Rezende, Mohamed and Lakshminarayanan,
Normalizing Flows for Probabilistic Modeling and Inference (JMLR 2021):
§2.1 (change of variables and compositions), §3.1 (autoregressive flows and coupling layers), §4
(continuous-time flows).