Module contents
Lesson 6 of 24Core 90 min

Measure theory II: densities, Radon-Nikodym and change of measure

A density is a Radon–Nikodym derivative: probability mass measured relative to a reference measure. This unifies mass functions and densities, explains mixed distributions, change of measure and likelihood ratios, and clarifies why a distribution concentrated on a low-dimensional manifold has no density.

After this lesson you can

  • Explain absolute continuity and state the Radon–Nikodym theorem and Lebesgue decomposition.
  • Express pmfs and pdfs as Radon–Nikodym derivatives with respect to counting and Lebesgue measures, and work with mixed distributions.
  • Apply the change of measure 𝔼_P[f] = 𝔼_Q[f · dP/dQ] and detect when it is invalid.
  • Reason about distributions supported on low-dimensional manifolds and their consequences for generative models.

Before you start

Motivation: the density of what has no density

You have spent weeks writing p(x)p(x) without asking what it means. Four real situations make the question pressing:

  • A ReLU activation. If Z∼N(0,1)Z \sim \Normal(0, 1) and X=ReLU⁡(Z)=max⁡(0,Z)X = \relu(Z) = \max(0, Z), half the mass falls exactly at X=0X = 0 and the rest follows a bell curve. XX is neither discrete (it takes a continuum of values) nor continuous (it has an atom). What is its density? Any model with censored data, inflated zeros, saturation or quantization encounters the same issue.
  • Off-policy learning and rare-event simulation. You want EP[f]\E_P[f] but can only sample from another law QQ. You reweight each sample by p(x)/q(x)p(x)/q(x). When is that ratio legitimate? What is the ratio when PP has atoms or QQ is discrete?
  • An image generator. A network maps noise z∈R64\vb{z} \in \R^{64} to an image in R3⋅256⋅256\R^{3 \cdot 256 \cdot 256}. The generated-image law lives on a set of dimension at most 6464 inside a space of dimension almost 200 000200\,000. What is its density relative to Lebesgue measure in that space? None, which is why KL\mathrm{KL} and likelihood behave so poorly with GANs.
  • A change of units. A model assigns log⁡p(x)=−1200\log p(\vb{x}) = -1200 to an image of 28×28=78428 \times 28 = 784 pixels with values in [0,1][0, 1]. With pixels in [0,255][0, 255] it gives −5544-5544. The model is unchanged; only the units changed. What, then, does a density value measure?

One idea answers all four and drives this lesson: a density is the derivative of one measure with respect to another. There is no single density of a law, only its density relative to a reference measure μ\mu. When μ\mu is counting measure we get a mass function; when it is Lebesgue measure we get a pdf; when the law cannot be measured by either, a third measure is needed. The Radon–Nikodym theorem says when that derivative exists, and its proof using Hilbert spaces uses the orthogonal projections you have seen.

The plan:

  1. Measures with densities. Build new measures from a function and see a necessary condition: absolute continuity.
  2. Radon–Nikodym. That condition is also sufficient. A complete proof for finite measures.
  3. Density as a derivative. Pmfs and pdfs are the same object, and mixed laws finally find their place.
  4. Lebesgue decomposition. The part of a measure without a density is isolated precisely.
  5. Change of measure. Reweight to move from QQ to PP, with its cost, variance, and its silent failure.
  6. Disjoint supports. Why a generative model may have no density and what is done in practice.

Measures with densities

Start with the easy direction: constructing measures. If you already have a measure μ\mu and a function f≥0f \ge 0, you can redistribute μ\mu by weighting it with ff:

ν(A)=∫Af ⁣dμ=∫1A f ⁣dμ.\nu(A) = \int_A f \dd\mu = \int \ind_A\, f \dd\mu.

This recipe builds much of applied probability: start from Lebesgue measure, choose a ff with integral 11 and obtain a pdf. The recipe works with any starting measure, which will matter.

Proof

It is a measure. ν(∅)=0\nu(\emptyset) = 0 and ν≥0\nu \ge 0. Let A1,A2,…A_1, A_2, \dots be disjoint with union AA. Then 1Af=∑n1Anf\ind_A f = \sum_n \ind_{A_n} f, a series of nonnegative functions, and by monotone convergence applied to partial sums, ∫∑n1Anf ⁣dμ=∑n∫1Anf ⁣dμ\int \sum_n \ind_{A_n} f \dd\mu = \sum_n \int \ind_{A_n} f \dd\mu. That is, ν(A)=∑nν(An)\nu(A) = \sum_n \nu(A_n).

Formula (1). For g=1Bg = \ind_B this is the definition of ν(B)\nu(B). By linearity it holds for nonnegative simple functions. A measurable g≥0g \ge 0 is the increasing limit of simple functions gn↑gg_n \uparrow g, so gnf↑gfg_n f \uparrow g f; monotone convergence on both sides gives (1). The complete step-by-step argument for functions of arbitrary sign is an exercise.

∎

Formula (1) deserves emphasis: integrating gg with respect to ν\nu means integrating gfg f with respect to μ\mu. Every change of measure in this lesson follows from it. The recipe explains familiar facts:

  • With μ=λ\mu = \lambda (Lebesgue measure) and ∫f ⁣dλ=1\int f \dd\lambda = 1, ν\nu is the law with density function ff. Formula (1) is the law of the unconscious statistician for expectation: E[g(X)]=∫g(x)f(x) ⁣dx\E[g(X)] = \int g(x) f(x) \dd x.
  • With μ\mu the counting measure cc on a countable set SS, ∫Af ⁣dc=∑x∈Af(x)\int_A f \dd c = \sum_{x \in A} f(x), and ν(A)=∑x∈Af(x)\nu(A) = \sum_{x \in A} f(x) is a discrete law with mass function ff. Formula (1) is E[g(X)]=∑xg(x)f(x)\E[g(X)] = \sum_x g(x) f(x).

The examples are literally the same theorem with different reference measures. We will exploit this unification shortly. First, an innocent observation with major consequences. If μ(A)=0\mu(A) = 0 then ∫Af ⁣dμ=0\int_A f \dd\mu = 0 (the integral of a nonnegative function over a null set is zero, as shown in the Lebesgue integral lesson). That is:

ν=f⋅μ⟹(μ(A)=0⇒ν(A)=0).\nu = f \cdot \mu \quad\Longrightarrow\quad \big(\mu(A) = 0 \Rightarrow \nu(A) = 0\big).

A measure with density relative to μ\mu cannot charge any set that μ\mu cannot see. This necessary condition has a name.

Absolute continuity and singularity

Remember this reading: ν≪μ\nu \ll \mu means ν\nu does not invent mass where μ\mu measures nothing. Singularity is the opposite extreme, complete non-overlap: all the mass of ν\nu lies where μ\mu has none. The general case lies between them, with part of ν\nu of each kind (the Lebesgue decomposition below).

ν\nuμ\muRelationshipWhy
N(0,1)\Normal(0, 1)N(3,22)\Normal(3, 2^2)ν∼μ\nu \sim \muboth have strictly positive density throughout R\R, so their null sets are Lebesgue null sets
Unif[0,1]\mathrm{Unif}[0, 1]Exp(1)\mathrm{Exp}(1)ν≪μ\nu \ll \mu, not μ≪ν\mu \ll \nuevery μ\mu-null set is Lebesgue-null within (0,∞)(0, \infty), and (0,1](0, 1] fits there (point 00 has no mass under ν\nu); conversely [2,3][2, 3] is ν\nu-null but not μ\mu-null
δ0\delta_0λ\lambdaδ0⊥λ\delta_0 \perp \lambdaλ({0})=0\lambda(\{0\}) = 0 and δ0({0}c)=0\delta_0(\{0\}^c) = 0
Poisson(2)\mathrm{Poisson}(2)Poisson(3)\mathrm{Poisson}(3)ν∼μ\nu \sim \muboth charge every integer ≥0\ge 0 and only those integers
Poisson(2)\mathrm{Poisson}(2)λ\lambdaν⊥λ\nu \perp \lambdaall mass lies on N\N, which is Lebesgue-null
Cantor lawλ\lambdaν⊥λ\nu \perp \lambdait lives on the Cantor set, of length 00
uniform on the unit circleλ2\lambda_2 on R2\R^2ν⊥λ2\nu \perp \lambda_2the circle has area 00

Two cautions. The relation ≪\ll is not symmetric (the second row shows this), and two measures that are “not ≪\ll” need not be singular: Unif[0,2]\mathrm{Unif}[0, 2] and Unif[1,3]\mathrm{Unif}[1, 3] share the segment [1,2][1, 2] and are neither one nor the other. Finally, for probability measures on Rd\R^d, absolute continuity with respect to Lebesgue measure is precisely the property that the event “XX falls in a zero-volume set” has probability zero.

The Radon–Nikodym theorem

We saw that having a density implies ν≪μ\nu \ll \mu. The Radon–Nikodym theorem says this is the only obstruction.

Both assumptions are necessary. Absolute continuity is necessary, as just seen. σ\sigma-finiteness is necessary too, and the counterexample is instructive: let μ\mu be counting measure on [0,1][0, 1] and ν=λ\nu = \lambda Lebesgue measure. Then ν≪μ\nu \ll \mu, because μ(A)=0\mu(A) = 0 only if A=∅A = \emptyset. But if ff existed, 0=λ({x})=f(x) μ({x})=f(x)0 = \lambda(\{x\}) = f(x)\, \mu(\{x\}) = f(x) for every xx, hence f=0f = 0 and λ=0\lambda = 0: a contradiction. The failure is that counting measure is not σ\sigma-finite on an uncountable set (remember this for the figures below).

In practice, uniqueness means densities are not values but equivalence classes: two pdfs that differ on a zero-length set (for example, at one point) are the same density. That is why the value p(x)p(x) is not the probability of anything: it is the rate of mass per unit of μ\mu around xx.

Density as a ratio of measures

The notation  ⁣dν/ ⁣dμ\dd\nu/\dd\mu is not arbitrary: it follows the rules of fractions.

Proof

(1) is an exercise in this lesson. (2) Apply (1) with R=PR = P: 1= ⁣dP/ ⁣dP=( ⁣dP/ ⁣dQ)( ⁣dQ/ ⁣dP)1 = \dd P/\dd P = (\dd P/\dd Q)(\dd Q/\dd P) PP-almost surely. (3) If P≪QP \ll Q: Q({q=0})=∫{q=0}q ⁣dμ=0Q(\{q = 0\}) = \int_{\{q = 0\}} q \dd\mu = 0, hence P({q=0})=∫{q=0}p ⁣dμ=0P(\{q = 0\}) = \int_{\{q = 0\}} p \dd\mu = 0, and since p≥0p \ge 0 this forces p=0p = 0 μ\mu-almost surely on {q=0}\{q = 0\}. Conversely, if Q(A)=0Q(A) = 0 then q=0q = 0 μ\mu-almost surely on AA, and by assumption p=0p = 0 μ\mu-almost surely on AA, giving P(A)=0P(A) = 0. The ratio formula follows from (1): P(A)=∫Ap ⁣dμ=∫Apq q ⁣dμ=∫Apq ⁣dQP(A) = \int_A p \dd\mu = \int_A \frac{p}{q}\, q \dd\mu = \int_A \frac{p}{q} \dd Q (on {q>0}\{q > 0\}, and the remainder has no PP-mass).

∎

The third rule contains this section’s most important practical lesson: the ratio p/qp/q does not depend on the reference measure. Replacing μ\mu with another changes pp and qq, but by the same factor, so the ratio survives. This is what the Radon–Nikodym derivative between laws measures: an intrinsic object, unlike each density separately.

Density: pmf and pdf are the same object

We can now give the definition that replaces the one in elementary courses.

With μ\mu counting measure, pp is the mass function p(x)=P(X=x)p(x) = \Pr(X = x); with μ=λ\mu = \lambda it is the usual pdf. There are not two concepts but one derivative and two reference measures. An important point elementary courses omit: the choice of μ\mu is not neutral, and a poor choice means the density does not exist.

E[X]=∫x p(x) ⁣dμ(x)\E[X] = \int x \, p(x) \dd\mu(x)
The law of the unconscious statistician with density relative to μ=δ0+λ\mu = \delta_0 + \lambda.
1/4

The next figure puts this in your hands. Compare the mixed law P=π δ0+(1−π) GammaP = \pi\,\delta_0 + (1 - \pi)\,\mathrm{Gamma} with three reference measures. For each, calculate ∫Ap ⁣dμ\int_A p \dd\mu over an interval AA that you drag, and read how much mass is lost relative to P(A)P(A).

InteractiveDensity depends on the reference measure
The law P=π δ0+(1−π) GammaP = \pi\,\delta_0 + (1 - \pi)\,\mathrm{Gamma} and its density relative to the chosen reference
p(0) = ∞A
  • continuous part
  • atom at 0
  • interval AA
There is no Lebesgue density: λ({0})=0\lambda(\{0\}) = 0 but P({0})=0.35>0P(\{0\}) = 0.35 > 0, so P≪̸λP \not\ll \lambda. The density captures only the continuous part and loses atom mass 0.350.
Reference measure μ\mu
0.35
2.0
1.00
P(A)P(A), the true mass0.6992
∫Ap  ⁣dμ\int_A p\,\dd\mu with this reference0.3492
Lost mass0.3500 (the atom)
Atom height p(0)p(0)does not exist (∞ required)
Continuous density at y=cy = c (point x=1x = 1)0.239
Choose reference measure μ\mu and drag the endpoints of AA on the axis. With Lebesgue measure the continuous part is represented correctly, but the atom would require infinite height (a ‘delta’, which is not a function): no value of p(0)p(0) works because {0}\{0\} has zero length, and as soon as AA contains 00, the atom's mass π\pi is lost. Counting measure does the opposite: the atom has height π\pi, but a sum of zeros over an uncountable set cannot reproduce continuous mass. Only with δ0+λ\delta_0 + \lambda does ∫Ap  ⁣dμ\int_A p\,\dd\mu equal P(A)P(A) for every AA. Use cc to change the units of the variable: continuous density height changes, atom mass does not.

What you should have seen:

  • With Lebesgue measure, the atom disappears. While AA does not contain 00 this goes unnoticed; once it does, the lost-mass column shows π\pi. This is not a failure of the formula: P≪̸λP \not\ll \lambda, so there is no Radon–Nikodym derivative to find.
  • With counting measure, the continuous part is lost. The lesson is subtler. Counting measure does satisfy P≪μP \ll \mu (its only null set is empty), but it is not σ\sigma-finite, and without σ\sigma-finiteness the theorem does not apply: the “density” p(0)=πp(0) = \pi, p(x)=0p(x) = 0 for x>0x > 0 does not represent PP.
  • With δ0+λ\delta_0 + \lambda everything works for every AA. The right reference measure sees all parts of PP: each atom with its own delta and the continuous part with Lebesgue measure.
  • A Lebesgue density value is not invariant. If Y=cXY = cX on R\R, then PY(B)=PX(B/c)=∫B/cpX(x) ⁣dx=∫B1c pX(y/c) ⁣dyP_Y(B) = P_X(B/c) = \int_{B/c} p_X(x) \dd x = \int_B \frac{1}{c}\, p_X(y/c) \dd y, so pY(y)=pX(y/c)/cp_Y(y) = p_X(y/c)/c: density is divided by cc, probabilities are not. In dimension dd the factor is c−dc^{-d}. This is the fourth opening example: changing pixels from [0,1][0, 1] to [0,255][0, 255] in an image with 784784 pixels subtracts 784ln⁡255≈4344784 \ln 255 \approx 4344 nats from log⁡p(x)\log p(\vb{x}). Comparing likelihoods of models using different scales is meaningless; we return to this with the change-of-variables formula for densities.

Why it is true: von Neumann’s proof

The rest of the lesson uses Radon–Nikodym as a black box; this section opens it. The idea is one of the most beautiful in elementary functional analysis: a measure ν≪μ\nu \ll \mu defines a bounded linear functional on L2L^2, and bounded linear functionals on a Hilbert space are inner products (Riesz). We prove it for finite measures; the σ\sigma-finite case is reduced to it at the end.

Proof

Let μ\mu and ν\nu be finite measures with ν≪μ\nu \ll \mu. Let λ′=μ+ν\lambda' = \mu + \nu, which is finite and satisfies μ,ν≤λ′\mu, \nu \le \lambda'.

Step 1: a bounded functional on L2(λ′)L^2(\lambda'). For g∈L2(λ′)g \in L^2(\lambda'), by Cauchy–Schwarz (in space LpL^p with p=2p = 2),

∣∫g ⁣dν∣≤∫∣g∣ ⁣dλ′≤λ′(Ω)1/2 ∥g∥L2(λ′).\Big|\int g \dd\nu\Big| \le \int \abs{g} \dd\lambda' \le \lambda'(\Omega)^{1/2}\, \norm{g}_{L^2(\lambda')}.

Thus Φ(g)=∫g ⁣dν\Phi(g) = \int g \dd\nu is a bounded linear functional on Hilbert space L2(λ′)L^2(\lambda') (well-defined on equivalence classes because a λ′\lambda'-null set is ν\nu-null). By the Riesz representation theorem, which in a Hilbert space is the orthogonal projection onto the orthogonal complement of the kernel of Φ\Phi with inner product ⟨g,h⟩=∫gh ⁣dλ′\inner{g}{h} = \int g h \dd\lambda' (inner product), there exists h∈L2(λ′)h \in L^2(\lambda') with

∫g ⁣dν=∫g h ⁣dλ′para todo g∈L2(λ′).(2)\int g \dd\nu = \int g\, h \dd\lambda' \qquad \text{para todo } g \in L^2(\lambda'). \tag{2}

Step 2: 0≤h≤10 \le h \le 1. With g=1Ag = \ind_A, (2) says ν(A)=∫Ah ⁣dλ′\nu(A) = \int_A h \dd\lambda', and 0≤ν(A)≤λ′(A)0 \le \nu(A) \le \lambda'(A). If A={h<0}A = \{h < 0\}, ∫Ah ⁣dλ′≥0\int_A h \dd\lambda' \ge 0 forces λ′(A)=0\lambda'(A) = 0. If A={h>1}A = \{h > 1\}, ∫A(h−1) ⁣dλ′≤0\int_A (h - 1) \dd\lambda' \le 0 and h−1>0h - 1 > 0 on AA force λ′(A)=0\lambda'(A) = 0. Modifying hh on a λ′\lambda'-null set gives 0≤h≤10 \le h \le 1 everywhere.

Step 3: rewrite. Since  ⁣dλ′= ⁣dμ+ ⁣dν\dd\lambda' = \dd\mu + \dd\nu, (2) for bounded measurable gg reads ∫g ⁣dν=∫gh ⁣dμ+∫gh ⁣dν\int g \dd\nu = \int g h \dd\mu + \int g h \dd\nu, that is,

∫g (1−h) ⁣dν=∫g h ⁣dμ.(3)\int g\,(1 - h) \dd\nu = \int g\, h \dd\mu. \tag{3}

Step 4: the set N={h=1}N = \{h = 1\} is null. With g=1Ng = \ind_N in (3): 0=∫Nh ⁣dμ=μ(N)0 = \int_N h \dd\mu = \mu(N). Thus μ(N)=0\mu(N) = 0 and, by assumption ν≪μ\nu \ll \mu, ν(N)=0\nu(N) = 0.

Step 5: the monotone limit. Take bounded g=(1+h+⋯+hn) 1Ag = (1 + h + \dots + h^n)\,\ind_A in (3). Since (1−h)(1+h+⋯+hn)=1−hn+1(1 - h)(1 + h + \dots + h^n) = 1 - h^{n+1},

∫A(1−hn+1) ⁣dν=∫A(h+h2+⋯+hn+1) ⁣dμ.\int_A (1 - h^{n+1}) \dd\nu = \int_A (h + h^2 + \dots + h^{n+1}) \dd\mu.

Now n→∞n \to \infty. Outside NN, h<1h < 1, so 1−hn+1↑11 - h^{n+1} \uparrow 1 and h+⋯+hn+1↑h/(1−h)h + \dots + h^{n+1} \uparrow h/(1 - h); on NN, null for both measures, nothing changes. By monotone convergence on both sides, ν(A∖N)=∫A∖Nh1−h ⁣dμ\nu(A \setminus N) = \int_{A \setminus N} \frac{h}{1 - h} \dd\mu. Since ν(N)=0\nu(N) = 0, defining f=h/(1−h)f = h/(1 - h) outside NN and f=0f = 0 on NN gives ν(A)=∫Af ⁣dμ\nu(A) = \int_A f \dd\mu for every AA. ■\blacksquare

Uniqueness. If ff and f′f' satisfy the theorem and ν\nu is finite, both are μ\mu-integrable. With A={f>f′}A = \{f > f'\}, ∫A(f−f′) ⁣dμ=ν(A)−ν(A)=0\int_A (f - f') \dd\mu = \nu(A) - \nu(A) = 0 with positive integrand on AA, so μ(A)=0\mu(A) = 0; similarly for {f′>f}\{f' > f\}.

The σ\sigma-finite case. Intersect a partition of Ω\Omega into sets of finite μ\mu-measure with another of finite ν\nu-measure, obtaining a countable partition (Ωn)(\Omega_n) where both measures are finite. Apply the finite case on each Ωn\Omega_n and glue the results: f=∑nfn1Ωnf = \sum_n f_n \ind_{\Omega_n}.

∎

Two observations. First, of all the steps, only the fourth uses ν≪μ\nu \ll \mu, and the rest hold for any pair of finite measures. Second, without the assumption, step four gives a result of its own, the next piece.

The Lebesgue decomposition

If ν\nu is not absolutely continuous with respect to μ\mu, the previous proof gets stuck at step 4: μ(N)=0\mu(N) = 0 remains true (it did not use the assumption), but ν(N)\nu(N) need not be 00. The mass ν\nu places on NN is precisely the mass μ\mu cannot measure.

Proof

Existence (finite measures; the σ\sigma-finite case is glued as before). Repeat steps 1–3 of von Neumann’s proof, which do not use ν≪μ\nu \ll \mu, and define N={h=1}N = \{h = 1\}. Step 4 gives μ(N)=0\mu(N) = 0. Let νs(A)=ν(A∩N)\nu_s(A) = \nu(A \cap N) and νa(A)=ν(A∖N)\nu_a(A) = \nu(A \setminus N). Then νs⊥μ\nu_s \perp \mu (it lives on NN, which is μ\mu-null, and vanishes on NcN^c). And step 5, applied to sets A⊂NcA \subset N^c, where ν\nu has no problem, gives νa(A)=∫Af ⁣dμ\nu_a(A) = \int_A f \dd\mu with f=h/(1−h)f = h/(1-h): in particular νa≪μ\nu_a \ll \mu.

Uniqueness. If ν=νa+νs=νa′+νs′\nu = \nu_a + \nu_s = \nu_a' + \nu_s', let N,N′N, N' be μ\mu-null sets carrying νs,νs′\nu_s, \nu_s', and M=N∪N′M = N \cup N', also μ\mu-null. On MM, νa\nu_a and νa′\nu_a' equal 00 (they are ≪μ\ll \mu). On McM^c, νs\nu_s and νs′\nu_s' equal 00. For every AA, then, νa(A)=νa(A∖M)=ν(A∖M)=νa′(A∖M)=νa′(A)\nu_a(A) = \nu_a(A \setminus M) = \nu(A \setminus M) = \nu_a'(A \setminus M) = \nu_a'(A), and similarly νs(A)=νs(A∩M)=ν(A∩M)=νs′(A)\nu_s(A) = \nu_s(A \cap M) = \nu(A \cap M) = \nu_s'(A). No subtraction of measures is needed, so the argument works unchanged in the σ\sigma-finite case. ■\blacksquare

∎

The three faces of a law on R\R

For a law PP on R\R relative to Lebesgue measure, the singular part PsP_s can be split again. The atoms of PP are points with P({x})>0P(\{x\}) > 0, and there are at most countably many: for every nn there are fewer than nn atoms of mass >1/n> 1/n (otherwise total mass would exceed 11). The part Pd=∑xP({x}) δxP_d = \sum_x P(\{x\})\,\delta_x is singular with respect to λ\lambda (it lives on a countable, hence Lebesgue-null, set), and the remainder of PsP_s is a singular measure without atoms. Thus every law on R\R can be written uniquely as

P=Pd⏟discreta+Pac⏟con densidad+Psc⏟singular continua.P = \underbrace{P_d}_{\text{discreta}} + \underbrace{P_{ac}}_{\text{con densidad}} + \underbrace{P_{sc}}_{\text{singular continua}}.

This is the decomposition announced in the lesson on distribution functions. The first piece appears in the steps of the distribution function; the second has a pdf; and the third is Cantor’s devil’s staircase: continuous, increasing and without a density. In practice only the first two appear in real data: the third is a textbook curiosity on R\R (although, as the last section shows, its high-dimensional counterpart is far from exotic).

A visual way to see the decomposition is to inspect the distribution function with a magnifying glass. For x0∈Rx_0 \in \R and small h>0h > 0,

R(h)=P((x0−h,x0+h])2h=F(x0+h)−F(x0−h)2hR(h) = \frac{P\big((x_0 - h, x_0 + h]\big)}{2h} = \frac{F(x_0 + h) - F(x_0 - h)}{2h}

is mass per unit length in a window around x0x_0. The Lebesgue differentiation theorem (not proved here; see section 31 of Billingsley, one of the lesson references) says R(h)→ ⁣dPac/ ⁣dλ (x0)R(h) \to \dd P_{ac}/\dd\lambda\,(x_0) for λ\lambda-almost every x0x_0. The Radon–Nikodym derivative is the limit of these ratios, while the other two parts behave as follows:

  • At an atom, R(h)≈P({x0})/(2h)→∞R(h) \approx P(\{x_0\})/(2h) \to \infty.
  • For the singular continuous part, the ratio does not converge to anything useful: at almost every point (for λ\lambda) it eventually equals 00, while at support points it oscillates or explodes. F′F' exists and equals 00 almost everywhere, and ∫F′=0≠1\int F' = 0 \ne 1.
InteractiveLebesgue decomposition under a magnifying glass
Distribution function FF as three stacked layers
log⁡10R(h)\log_{10} R(h) as the window shrinks (jj increases, hh decreases)
R = 10⁻²R = 1R = 10²R = 10⁴0481216 (j)
  • atoms
  • density part
  • Cantor part
  • R(h)R(h) total
At an atom, R(h)≈m/(2h)R(h) \approx m/(2h) with m=0.150m = 0.150: it grows without bound, since ν({x0})>0\nu(\{x_0\}) > 0 but λ({x0})=0\lambda(\{x_0\}) = 0.
0.25
0.45
0.30
Where to look
0.20
3 (h = 0.13)
Masses: atoms / density / Cantor0.25 / 0.45 / 0.30
R(h)R(h) total1.418
from atoms0.600
from the density part0.418
from the Cantor part0.400
Limiting density of the a.c. part at x0x_00.432
Left: the distribution function of ν=md (atoms)+ma Beta(2,2)+mc (Cantor)\nu = m_d\,(\text{atoms}) + m_a\,\mathrm{Beta}(2,2) + m_c\,(\text{Cantor}) as three stacked layers, with window (x0−h,x0+h](x_0 - h, x_0 + h] in gray. Right: log⁡10R(h)\log_{10} R(h) for h=2−jh = 2^{-j} and each of the three parts. Choose Atom: RR grows like 1/h1/h and the line rises with slope log⁡102\log_{10} 2 per unit of jj. Choose Density: only the absolutely continuous part survives and RR stabilizes at its density. Choose Cantor: the singular part does not stabilize either; without atoms, it grows without bound like hlog⁡2/log⁡3−1h^{\log 2/\log 3 - 1}, more slowly than at an atom and with small oscillations. Set two of the three masses to zero and see what remains.

Change of measure and likelihood ratio

Formula (1) in the first section, with μ=Q\mu = Q and ν=P\nu = P, is the lesson’s practical result.

The proof is (1), with g=fg = f, for f≥0f \ge 0; extending to signed ff (separating f=f+−f−f = f^+ - f^- and checking integrals are finite) is an exercise. EQ[w]=1\E_Q[w] = 1 is (4) with f=1f = 1, and P({w=0})=∫{w=0}w ⁣dQ=0P(\{w = 0\}) = \int_{\{w = 0\}} w \dd Q = 0 gives w>0w > 0 PP-almost surely.

Read (4) carefully: it is a machine. To calculate an expectation under PP, sample from another law QQ and weight by ww. The general name for ww is likelihood ratio when PP and QQ are data laws of two models, by the third calculus rule: w=p/qw = p/q. It appears in hypothesis tests (Neyman–Pearson lemma), in KL(P ∥ Q)=EP[log⁡w]\mathrm{KL}(P \,\|\, Q) = \E_P[\log w] divergence in the information theory module, in derivatives pricing (moving from the real-world measure to the risk-neutral measure is a change to an equivalent measure), and in off-policy reinforcement learning, where the ratio π(a∣s)/b(a∣s)\pi(a \mid s)/b(a \mid s) between target and behavior policies corrects the data.

The Gaussian example

For P=N(a,I)P = \Normal(\vb{a}, \mat{I}) and Q=N(b,I)Q = \Normal(\vb{b}, \mat{I}) on Rd\R^d, the ratio has a closed form, and its second moment explains what happens in high dimension.

w(x)=exp⁡ ⁣(12∥x−b∥2−12∥x−a∥2)w(\vb{x}) = \exp\!\big(\tfrac{1}{2}\norm{\vb{x} - \vb{b}}^2 - \tfrac{1}{2}\norm{\vb{x} - \vb{a}}^2\big)
This is the ratio w=p/qw = p/q of the two normal densities. Their normalizing constants agree (same covariance) and cancel.
1/5

The result EQ[w2]=e∥a−b∥2\E_Q[w^2] = e^{\norm{\vb{a} - \vb{b}}^2} grows exponentially in the square of the distance between the means, and for two Gaussians with dd coordinates separated by δ\delta each, that square is d δ2d\,\delta^2. This is why importance sampling breaks down in high dimension even when PP and QQ are almost identical coordinate by coordinate. The implementation cell measures it.

Estimator variance and effective sample size

Let QQ be the proposal, X1,…,Xn∼iidQX_1, \dots, X_n \iid Q and the importance-sampling estimator

θ^n=1n∑i=1nf(Xi) w(Xi).\hat\theta_n = \frac{1}{n}\sum_{i=1}^n f(X_i)\, w(X_i).

By (4) it is unbiased for EP[f]\E_P[f] (even when EP[f]\E_P[f] does not exist as a finite number, within the f≥0f \ge 0 cases). Its variance is

Var(θ^n)=1n(EQ[f2w2]−(EPf)2)=1n(EP[f2w]−(EPf)2),\mathrm{Var}(\hat\theta_n) = \frac{1}{n}\Big(\E_Q[f^2 w^2] - (\E_P f)^2\Big) = \frac{1}{n}\Big(\E_P[f^2 w] - (\E_P f)^2\Big),

which can be infinite even when P≪QP \ll Q. This occurs when the tails of QQ are lighter than those of PP: with P=N(0,1)P = \Normal(0, 1) and Q=N(0,σQ2)Q = \Normal(0, \sigma_Q^2) one calculates EQ[w2]=σQ2/2σQ2−1\E_Q[w^2] = \sigma_Q^2/\sqrt{2\sigma_Q^2 - 1} if σQ2>12\sigma_Q^2 > \tfrac{1}{2}, and ∞\infty otherwise. A proposal only somewhat narrower than the target already breaks the estimator.

To assess the damage without knowing EP[f]\E_P[f], use the effective sample size (ESS)

ESS=(∑iwi)2∑iwi2≈nEQ[w2],\mathrm{ESS} = \frac{\big(\sum_i w_i\big)^2}{\sum_i w_i^2} \approx \frac{n}{\E_Q[w^2]},

the number of iid samples from PP equivalent to the nn weighted samples (a first-order approximation). It ranges from 11 (one weight dominates) to nn (all equal). When PP is known only up to a constant, normalize by the sum of weights to obtain the self-normalized estimator ∑iwif(Xi)/∑iwi\sum_i w_i f(X_i)/\sum_i w_i, which is consistent though biased; see the library section.

InteractiveReweight Q samples to estimate under P
Target pp (blue), proposal qq (red), and nn samples from qq with area proportional to w=p/qw = p/q
−4−2024680.10.20.3
Cumulative estimates as nn grows (same samples)
  • IS: 1n∑fw\frac{1}{n}\sum f w
  • self-normalized
  • EP[f]\E_P[f] (truth)
  • pp: target
  • qq: proposal and samples
QQ covers PP and EQ[w2]\E_Q[w^2] is finite: weights are spread (ESS = 322 of 501) and the estimator converges to EP[f]\E_P[f].
Family of QQ
1.00
2.00
501
Function ff
EP[f]\E_P[f] exact1.2000
Estimate with n=501n = 5011.0562
Mean weight (should be 1)1.035
Effective sample size ESS\mathrm{ESS}322 (64.4 %)
EQ[w2]\E_Q[w^2]1.68
The target PP (blue) is a mixture of two bell curves, and samples (red circles, with radius proportional to w\sqrt{w} and hence area proportional to weight ww) come from a proposal QQ that you can move and widen. Below are cumulative estimates as nn grows. Try three cases. (1) A wide centered Gaussian: the estimate converges and weights are spread. (2) A narrow Gaussian (σQ2≤1/2\sigma_Q^2 \le 1/2, that is, σQ≤0.71\sigma_Q \le 0.71, half the variance of the wide bell in PP): EQ[w2]=∞\E_Q[w^2] = \infty and the estimates jump. (3) The uniform proposal: adjust its interval so it does not cover the right-hand mode of PP. The estimator converges to a different value without warning; the only clue is that the mean of the weights, which should equal 11, stays at P(SQ)<1P(S_Q) < 1.

When P≪̸QP \not\ll Q: failure without warning

What does formula EQ[f p/q]\E_Q[f\,p/q] calculate when PP is not absolutely continuous with respect to QQ? The Lebesgue decomposition answers precisely.

Proof

This is formula (1) with μ=Q\mu = Q and ν=Pa\nu = P_a: EQ[f wa]=∫f ⁣dPa\E_Q[f\,w_a] = \int f \dd P_a. And Pa(A)=P(A∖N)P_a(A) = P(A \setminus N) (the singular part lives on NN), so ∫f ⁣dPa=∫f 1Nc ⁣dP\int f \dd P_a = \int f\,\ind_{N^c} \dd P. With f=1f = 1, EQ[wa]=P(Nc)=1−P(N)\E_Q[w_a] = P(N^c) = 1 - P(N).

∎

This is exactly what the figure with the uniform proposal shows: the estimator converges to the expectation of ff restricted to where QQ can see, and the weight mean converges to the mass of PP covered by QQ. No confidence interval based on sample variance detects this, because the estimator is stable with finite variance. The only defense is diagnostic EQ[w]=1\E_Q[w] = 1: if the mean weight is not 11, something is wrong. The same happens with discrete variables, and underlies the coverage requirements on the behavior policy in off-policy reinforcement learning: b(a∣s)>0b(a \mid s) > 0 whenever π(a∣s)>0\pi(a \mid s) > 0, precisely π≪b\pi \ll b.

Disjoint supports: the density that does not exist

We arrive at the fourth opening situation. A generator G:Rk→RdG : \R^k \to \R^d with k<dk < d takes a law on Rk\R^k to a law P=G#PZP = G_\# P_Z on Rd\R^d (the pushforward law). For PP to have a density with respect to λd\lambda_d, the image of GG would need nonzero measure; it has measure zero.

Proof

It suffices to show G([−n,n]k)G([-n, n]^k) is null for every nn. Divide the cube into mkm^k cubes of side 2n/m2n/m. If LL is the Lipschitz constant, each subcube’s image fits in a ball of radius Lk 2n/mL\sqrt{k}\,2n/m and volume cd (2nLk/m)dc_d\,(2nL\sqrt{k}/m)^d. Summing gives λd(G([−n,n]k))≤mkcd (2nLk)d m−d→0\lambda_d(G([-n, n]^k)) \le m^k c_d\,(2nL\sqrt{k})^d\, m^{-d} \to 0 as m→∞m \to \infty because k<dk < d. The countable union of nn gives all of G(Rk)G(\R^k), and P(G(Rk))=PZ(Rk)=1P(G(\R^k)) = P_Z(\R^k) = 1 with λd(G(Rk))=0\lambda_d(G(\R^k)) = 0. ■\blacksquare

∎

Generators with ReLU activations are Lipschitz (piecewise linear), and smooth ones of class C1C^1 are locally Lipschitz, so the conclusion applies to GANs, autoencoders and any model decoding a code of dimension lower than the data: the manifold hypothesis in measure-theoretic form. The simplest cases in the exercise at the end are (U,U)(U, U) (the square’s diagonal), (U,U2)(U, U^2) (a parabola), and the uniform distribution on a circle: all are laws on R2\R^2 without a density. The law of (U,V)(U, V) with independent U,VU, V, filling the square, does have one (the constant 11 on [0,1]2[0, 1]^2).

The serious issue arises when comparing two such laws. If PP and QQ live on manifolds of dimension lower than dd, their supports are often disjoint or intersect on a set null for both. In either case P⊥QP \perp Q and there is no likelihood ratio. Two consequences, each one line away:

  • KL(P ∥ Q)=∞\mathrm{KL}(P \,\|\, Q) = \infty, because by definition KL(P ∥ Q)=EP[log⁡ ⁣dP/ ⁣dQ]\mathrm{KL}(P \,\|\, Q) = \E_P[\log \dd P/\dd Q] if P≪QP \ll Q and +∞+\infty otherwise. Bringing the laws closer does not help: however small the movement of QQ, as long as P⊥QP \perp Q the divergence equals ∞\infty.
  • Jensen–Shannon divergence is constant. Let M=(P+Q)/2M = (P + Q)/2. If P⊥QP \perp Q, on the support AA of PP we have  ⁣dP/ ⁣dM=2\dd P/\dd M = 2, so KL(P ∥ M)=log⁡2\mathrm{KL}(P \,\|\, M) = \log 2, and symmetrically KL(Q ∥ M)=log⁡2\mathrm{KL}(Q \,\|\, M) = \log 2. Thus JS(P,Q)=12KL(P ∥ M)+12KL(Q ∥ M)=log⁡2\mathrm{JS}(P, Q) = \tfrac{1}{2}\mathrm{KL}(P \,\|\, M) + \tfrac{1}{2}\mathrm{KL}(Q \,\|\, M) = \log 2 for any mutually singular pair of laws, whether QQ is next to PP or far away. A perfect discriminator separates the laws and its gradient to the generator vanishes: the Arjovsky–Bottou argument for unstable GAN training, giving its name to the manifold support problem.
InteractiveTwo laws on manifolds in R3\R^3
  • law PP and its support
  • law QQ and its support
PP and QQ live on curves in R3\R^3: zero volume, no Lebesgue density. The curves do not intersect, and two curves in R3\R^3 share no mass: P⊥QP \perp Q, the ratio does not exist and KL(P ∥ Q)=∞\mathrm{KL}(P \,\|\, Q) = \infty however small the movement.
Noise dimension kk
1.60
1.00
25°
0.00
Support / ambient dimension1 / 3
Support volume in R3\R^30 (no Lebesgue density)
Minimum distance between supports≈ 0.21
Relationship between supportsdisjoint supports
Ratio  ⁣dP/ ⁣dQ\dd P / \dd Qdoes not exist (P ⊥ Q)
KL(P ∥ Q)\mathrm{KL}(P \,\|\, Q)∞
PP lives on a trefoil knot (dimension 1) or a wavy surface (dimension 2); QQ is a shifted and rotated copy. While Q≠PQ \ne P, their supports are disjoint or intersect on a set null for both, and neither Lebesgue densities nor the ratio  ⁣dP/ ⁣dQ\dd P/\dd Q exist: KL\mathrm{KL} is ∞\infty however close they are. Notice that the minimum distance between supports does vary continuously. With k=2k = 2 the surfaces intersect along a curve, yet P⊥QP \perp Q because a curve has zero area. Increase σ\sigma: Gaussian noise turns both curves into clouds with densities and the ratio exists and is finite for any σ>0\sigma > 0, but takes moderate values only when σ\sigma is comparable to the distance between supports.

What is done in practice

There are three approaches, all appearing later in the course.

  1. Add noise. If Pσ=P∗N(0,σ2I)P_\sigma = P * \Normal(\vb{0}, \sigma^2 \mat{I}), its density is pσ(x)=EY∼P[ϕσ(x−Y)]>0p_\sigma(\vb{x}) = \E_{\vb{Y} \sim P}[\phi_\sigma(\vb{x} - \vb{Y})] > 0 throughout Rd\R^d even when PP lives on a curve. Then Pσ∼QσP_\sigma \sim Q_\sigma and KL(Pσ ∥ Qσ)<∞\mathrm{KL}(P_\sigma \,\|\, Q_\sigma) < \infty (in fact ≤W22(P,Q)/(2σ2)\le W_2^2(P, Q)/(2\sigma^2)). The price is an enormous divergence when σ\sigma is small relative to the distance between supports, as the figure shows. Diffusion models take this idea to the limit: they add noise at many scales so there is always a ratio to learn.
  2. Change distance. Wasserstein distance does not require a ratio: if QQ is a translation of PP by a vector t\vb{t}, W1(P,Q)≤∥t∥W_1(P, Q) \le \norm{\vb{t}} varies continuously with t\vb{t}, while KL\mathrm{KL} jumps from 00 to ∞\infty.
  3. Work in latent space. If the manifold has a known parameterization GG, calculate density in the space of z\vb{z} (dimension kk) and correct with the area factor det⁡(JG⊤JG)\sqrt{\det(\mat{J}_G\T\mat{J}_G)} of the Jacobian of GG. The result is a density relative to the manifold’s surface measure, another reference measure, not to λd\lambda_d. This is the topic of normalizing flows (injective ones here).

Implementation from scratch

We now build and measure what we just proved. The first cell implements a law with atoms and a continuous part, using a single formula for probabilities and expectations (integration with respect to δ0+λ\delta_0 + \lambda), and compares it with a direct simulation of ReLU⁡(Z)\relu(Z).

[ ]A mixed law: atoms plus densityBrowser
import numpy as np

class LeyMixta:
    """P = Σ p_i δ_{x_i} + c(x) dx: átomos más una parte continua dada por una subdensidad c."""
    def __init__(self, atomos, c, lo, hi, n=400):
        self.atomos = dict(atomos)                               # {posición: masa}
        self.c = c                                               # subdensidad de la parte continua
        self.lo, self.hi = lo, hi                                # ventana que contiene toda la parte continua
        self.nodos, self.pesos = np.polynomial.legendre.leggauss(n)   # cuadratura de Gauss-Legendre

    def integral(self, g, a, b):
        """∫_a^b g(x) c(x) dx, recortada a la ventana [lo, hi]."""
        a, b = max(a, self.lo), min(b, self.hi)
        if b <= a:
            return 0.0
        x = 0.5 * (b - a) * self.nodos + 0.5 * (b + a)
        return 0.5 * (b - a) * float(np.sum(self.pesos * g(x) * self.c(x)))

    def prob(self, a, b):
        """P((a, b]) = Σ_{a < x_i ≤ b} p_i + ∫_a^b c."""
        return sum(p for x, p in self.atomos.items() if a < x <= b) + self.integral(np.ones_like, a, b)

    def cdf(self, x):
        return self.prob(-np.inf, x)

    def esperanza(self, g):
        """E[g(X)] = Σ p_i g(x_i) + ∫ g c dx: una suma y una integral, una sola fórmula."""
        suma = sum(p * float(g(np.array([x]))[0]) for x, p in self.atomos.items())
        return suma + self.integral(g, self.lo, self.hi)

phi = lambda x: np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
relu_z = LeyMixta({0.0: 0.5}, lambda x: np.where(x > 0, phi(x), 0.0), lo=0.0, hi=12.0)

print("masa total             :", relu_z.prob(-np.inf, np.inf))
print("P(X = 0)               :", relu_z.prob(-1e-9, 0.0))
print("P(X <= 1)  (esperado Φ(1) = 0.841345):", round(relu_z.cdf(1.0), 6))
E1 = relu_z.esperanza(lambda x: x)
E2 = relu_z.esperanza(lambda x: x**2)
print("E[X]   =", round(E1, 6), "  (1/sqrt(2π) =", round(1 / np.sqrt(2 * np.pi), 6), ")")
print("E[X^2] =", round(E2, 6), "  Var[X] =", round(E2 - E1**2, 6))

rng = np.random.default_rng(0)
x = np.maximum(0.0, rng.standard_normal(400_000))                # simulación directa de ReLU(Z)
print("Monte Carlo:  P(X=0) =", round(float(np.mean(x == 0)), 4), "  E[X] =", round(float(x.mean()), 4), "  E[X^2] =", round(float(np.mean(x**2)), 4))

The expectation is 0.398942=1/2π0.398942 = 1/\sqrt{2\pi} and E[X2]=0.5\E[X^2] = 0.5, so variance is 0.3408450.340845, and direct simulation agrees with quadrature within Monte Carlo error (of order 10−310^{-3}). The class has no special case for discrete or continuous: it is formula ∫g ⁣dμ\int g \dd\mu with μ=δ0+λ\mu = \delta_0 + \lambda.

The second cell calculates Radon–Nikodym derivatives between laws of the same type and verifies change of measure (4), first in the discrete case with counting measure, then with Gaussians, and finally where PP is not ≪Q\ll Q:

[ ]dP/dQ and change of measure, including when it failsBrowser
import numpy as np
from math import lgamma, log

# --- Caso discreto: P = Poisson(2), Q = Poisson(3), μ = medida de conteo en N ---
def pmf_poisson(lam, k):
    return np.exp(-lam + k * np.log(lam) - np.array([lgamma(j + 1) for j in k]))

k = np.arange(0, 80)
pP, pQ = pmf_poisson(2.0, k), pmf_poisson(3.0, k)
w = pP / pQ                                               # dP/dQ (k) = cociente de pmf: derivada de Radon-Nikodym
print("dP/dQ en k = 4          :", round(float(w[4]), 6), " (e·(2/3)^4 =", round(float(np.e * (2 / 3) ** 4), 6), ")")
print("E_Q[w]  (debe ser 1)    :", round(float(np.sum(pQ * w)), 10))
print("E_P[k^2] directa        :", round(float(np.sum(pP * k**2)), 6), "  (λ + λ² = 6)")
print("E_Q[k^2 w] (cambio de Q):", round(float(np.sum(pQ * k**2 * w)), 6))

# --- Caso gaussiano: P = N(1, 1), Q = N(0, 2²), μ = Lebesgue. La razón de densidades es dP/dQ ---
norm = lambda x, m, s: np.exp(-0.5 * ((x - m) / s) ** 2) / (s * np.sqrt(2 * np.pi))
rng = np.random.default_rng(1)
n = 400_000
x = rng.normal(0.0, 2.0, n)                              # muestras de Q
w = norm(x, 1.0, 1.0) / norm(x, 0.0, 2.0)                # pesos w = p/q
print("\nE_P[X^2] verdadera = 2     ; E_Q[X^2 w] ≈", round(float(np.mean(x**2 * w)), 4))
print("media de los pesos (≈ 1)   :", round(float(w.mean()), 4))

# --- El mismo cálculo cuando P NO es absolutamente continua respecto de Q ---
# Q = uniforme en [−1, 1]; P = N(0, 1) tiene masa fuera de [−1, 1] (P(|X| > 1) ≈ 0.317)
x = rng.uniform(-1.0, 1.0, n)
w = norm(x, 0.0, 1.0) / 0.5                              # q(x) = 1/2 dentro del soporte de Q
print("\nQ = U[−1, 1]:   E_Q[X^2 w] ≈", round(float(np.mean(x**2 * w)), 4), " (E_P[X^2] = 1)")
print("media de los pesos         :", round(float(w.mean()), 4), " (P(|X| ≤ 1) = 0.6827)")

For the first two laws, change of measure works exactly: the derivative at k=4k = 4 is e (2/3)4=0.5369e\,(2/3)^4 = 0.5369, EQ[w]=1\E_Q[w] = 1 and both expectations of k2k^2 equal 6=λ+λ26 = \lambda + \lambda^2 exactly. With Gaussians, the estimate using 4⋅1054 \cdot 10^5 samples from QQ is within 10−210^{-2} of value 22. With the uniform proposal the result is what the proposition predicted: the estimate is 0.19870.1987 instead of 11 and mean weight is 0.6827=P(∣X∣≤1)0.6827 = P(\abs{X} \le 1) instead of 11. 0.19870.1987 is EP[X2 1∣X∣≤1]\E_P[X^2\,\ind_{\abs{X} \le 1}], not EP[X2]\E_P[X^2]. Nothing crashes and no warning appears: the estimator converges perfectly to the wrong value.

The third cell packages the estimator with diagnostics and tests it against three proposals for the same target P=0.7 N(0,1)+0.3 N(4,0.52)P = 0.7\,\Normal(0, 1) + 0.3\,\Normal(4, 0.5^2), whose EP[X2]\E_P[X^2] is 5.5755.575. It then measures how effective sample size collapses as dimension increases.

[ ]Importance estimator with diagnostics and the curse of dimensionalityBrowser
import numpy as np

norm_logpdf = lambda x, m, s: -0.5 * ((x - m) / s) ** 2 - np.log(s * np.sqrt(2 * np.pi))

def estimar_is(f, x, logw):
    """Estima E_P[f] con x ~ Q y logw = log(dP/dQ)(x). Devuelve estimación, media de pesos y muestra efectiva."""
    w = np.exp(logw)
    return float(np.mean(f(x) * w)), float(np.mean(w)), float(w.sum() ** 2 / np.sum(w**2))

f = lambda x: x**2
rng = np.random.default_rng(2)
n = 100_000

# P = mezcla 0.7 N(0, 1) + 0.3 N(4, 0.5²); verdad: E_P[X²] = 0.7·1 + 0.3·(16 + 0.25) = 5.575
logp = lambda x: np.log(0.7 * np.exp(norm_logpdf(x, 0, 1)) + 0.3 * np.exp(norm_logpdf(x, 4, 0.5)))
print("verdad: 5.575\n")
for nombre, m, s in [("Q = N(1, 2²)   (cubre a P)    ", 1.0, 2.0), ("Q = N(0, 1)     (no cubre el modo)", 0.0, 1.0), ("Q = N(1, 0.5²) (colas ligeras)  ", 1.0, 0.5)]:
    est = []
    for rep in range(5):
        x = rng.normal(m, s, n)
        est.append(estimar_is(f, x, logp(x) - norm_logpdf(x, m, s)))
    ests, mw, ess = zip(*est)
    print(f"{nombre}  estimaciones: {np.round(ests, 3)}   media de w: {np.mean(mw):.3f}   ESS/n: {np.mean(ess) / n:.4f}")

# La dimensión mata a los pesos: P = N(0, I), Q = N(δ·1, I), E_Q[w²] = exp(d δ²)
print("\n d   ESS/n medido   exp(−d δ²)")
delta = 0.5
for d in [1, 2, 4, 8, 16, 32]:
    x = rng.standard_normal((n, d)) + delta
    logw = -0.5 * np.sum(x**2, axis=1) + 0.5 * np.sum((x - delta) ** 2, axis=1)
    w = np.exp(logw - logw.max())                         # ESS no cambia si se reescala w
    print(f"{d:2d}   {w.sum() ** 2 / np.sum(w**2) / n:11.4f}   {np.exp(-d * delta**2):10.4f}")

The three cases illustrate three regimes. With Q=N(1,22)Q = \Normal(1, 2^2) the five estimates cluster around 5.5755.575 and effective sample size is on the order of 60 %60\,\% of nn. With Q=N(0,1)Q = \Normal(0, 1), which covers the first mode but barely sees the one at x=4x = 4 (44 standard deviations away), estimates fluctuate between 4.74.7 and 12.612.6 and only one sample in a thousand counts: the estimator is unbiased and, at n=105n = 10^5, useless. With Q=N(1,0.52)Q = \Normal(1, 0.5^2) there is a third, most dangerous behavior: tails are lighter than those of PP, variance is infinite and estimates stabilize near 0.60.6, while mean weight 0.640.64 instead of 11 reveals that the estimator remains far from 5.5755.575 despite nn. The second block measures dimension: through d=8d = 8 the measured column follows e−dδ2e^{-d\delta^2}, then stays above it. Estimated ESS becomes optimistic because the huge weights that would dominate EQ[w2]\E_Q[w^2] are so rare they do not appear in 10510^5 samples: at d=32d = 32 the cell reports one useful sample per 330330, while the true value e−8e^{-8} is one per 30003000. The key result is that with δ=0.5\delta = 0.5, only half a standard deviation of difference per coordinate, at d=32d = 32 effective sample size has already fallen below 0.1 %0.1\,\%, and the diagnostic itself underestimates the damage.

Using libraries

scipy.stats provides laws with logpdf, and scipy.special.logsumexp normalizes weights on a logarithmic scale without overflow. In practice always work with log weights: ww can equal e−300e^{-300} or e300e^{300} in high dimension and overflow is silent. The cell does three things: self-normalized importance sampling (useful when pp is known only up to a constant), a Gaussian with singular covariance (which scipy accepts with allow_singular=True while silently changing the reference measure), and exploding likelihood when data are flattened onto a line.

[ ]scipy: logarithmic weights and singular covariance matricesBrowser
import numpy as np
from scipy import stats
from scipy.special import logsumexp

rng = np.random.default_rng(3)

# 1) IS autonormalizado con logs: sirve cuando p solo se conoce salvo una constante
logp_sin_norm = lambda x: np.logaddexp(np.log(0.7) - 0.5 * x**2, np.log(0.3) - 0.5 * ((x - 4) / 0.5) ** 2 - np.log(0.5))   # p(x) · √(2π)
q = stats.norm(1.0, 2.0)
x = q.rvs(size=200_000, random_state=rng)
logw = logp_sin_norm(x) - q.logpdf(x)                    # log-pesos sin normalizar
w_n = np.exp(logw - logsumexp(logw))                     # Σ w_n = 1 sin desbordar
print("IS autonormalizado de E[X²]:", round(float(np.sum(w_n * x**2)), 3), " (verdad 5.575)")

# 2) scipy elige en silencio la medida de referencia: una gaussiana con covarianza singular
cov = np.array([[1.0, 1.0], [1.0, 1.0]])                 # toda la masa en la recta y = x
ley = stats.multivariate_normal(mean=[0, 0], cov=cov, allow_singular=True)
print("\ndensidad sobre la recta (1, 1):", round(float(ley.pdf([1, 1])), 4), "  fuera de ella (1, 1.5):", float(ley.pdf([1, 1.5])))
print("   (es la densidad respecto de la longitud en la recta, no respecto de Lebesgue en R²)")

# 3) la log-verosimilitud de un ajuste gaussiano se dispara cuando los datos se aplastan sobre una recta
t = rng.standard_normal(5000)
print("\n  ε        log-verosimilitud media del ajuste gaussiano")
for eps in [1.0, 0.1, 1e-2, 1e-4, 1e-8]:
    X = np.column_stack([t, t + eps * rng.standard_normal(t.size)])   # casi sobre la recta y = x
    try:
        ll = stats.multivariate_normal(X.mean(axis=0), np.cov(X.T)).logpdf(X).mean()
        print(f"{eps:8.0e}   {ll:8.2f}")
    except np.linalg.LinAlgError:
        print(f"{eps:8.0e}   scipy se niega: la covarianza ya es numéricamente singular")

Self-normalization gives 5.5995.599 with 2⋅1052 \cdot 10^5 samples and without knowing the constant of pp. The singular Gaussian’s density is 0.17110.1711 on the line and 00 outside: it is a density relative to length on the line, a different reference measure, and comparing it with a pdf on R2\R^2 would be absurd. The third table shows the fourth common mistake: when data flatten onto the line y=xy = x (thickness ε\varepsilon), the fitted Gaussian’s mean log likelihood grows without bound, as −log⁡ε-\log\varepsilon (from −0.55-0.55 with ε=0.1\varepsilon = 0.1 to 6.376.37 with ε=10−4\varepsilon = 10^{-4}), and scipy eventually refuses to construct the law. Such a model would have enormous likelihood without being better: it has only discovered that the data are nearly singular.

Common mistakes

Exercises

QuizWith a density in the plane?
Which of these laws on R2\R^2 are absolutely continuous with respect to Lebesgue measure λ2\lambda_2? (U,V∼iidUnif[0,1]U, V \iid \mathrm{Unif}[0, 1].)
QuizWhich relationships hold?
For measures on R\R, which statements are true? (λ\lambda is Lebesgue measure.)

More than one answer may be correct.

QuizRelative to which measure?
A variable XX equals 00 with probability 0.30.3 and, with probability 0.70.7, follows Exp(1)\mathrm{Exp}(1). Relative to which of these σ\sigma-finite measures does XX have a well-defined density unique almost surely?
QuizWhen is weight variance infinite?
Estimate EP[1]=1\E_P[1] = 1 with P=N(0,1)P = \Normal(0, 1) and proposal Q=N(0,σQ2)Q = \Normal(0, \sigma_Q^2): θ^n=1n∑iw(Xi)\hat\theta_n = \frac{1}{n}\sum_i w(X_i). For which values of σQ2\sigma_Q^2 does θ^n\hat\theta_n have finite variance? (Hint: EQ[w2]=∫p2/q\E_Q[w^2] = \int p^2/q.)

More than one answer may be correct.

NumericExpectation of a Gaussian ReLU
Let Z∼N(0,1)Z \sim \Normal(0, 1) and X=max⁡(0,Z)X = \max(0, Z). Given P(X=0)=12\Pr(X = 0) = \tfrac{1}{2}, calculate E[X]\E[X] using the density of XX relative to δ0+λ\delta_0 + \lambda.
NumericA ratio of mass functions
Let P=Poisson(2)P = \mathrm{Poisson}(2) and Q=Poisson(3)Q = \mathrm{Poisson}(3). Using counting measure as reference, calculate  ⁣dP ⁣dQ(4)\dfrac{\dd P}{\dd Q}(4).
NumericHow many effective samples remain?
You want to estimate an expectation under P=N(0,1)P = \Normal(0, 1) using n=10 000n = 10\,000 samples from Q=N(2,1)Q = \Normal(2, 1). Using approximation ESS≈n/EQ[w2]\mathrm{ESS} \approx n/\E_Q[w^2] and the Gaussian derivation, what is the effective sample size?
NumericWeight variance with a wide proposal
With P=N(0,1)P = \Normal(0, 1) and Q=N(0,2)Q = \Normal(0, 2) (variance σQ2=2\sigma_Q^2 = 2), calculate the variance of weights VarQ(w)=EQ[w2]−1\mathrm{Var}_Q(w) = \E_Q[w^2] - 1.
NumericChanging from [0, 1] to [0, 255]
A model assigns an image of 28×28=78428 \times 28 = 784 pixels with values in [0,1][0, 1] a log density of −1200-1200 nats. If pixels are rescaled to [0,255][0, 255] (multiplying by 255255), what is the log density of the same image under the equivalent model, in nats?
ProofThe chain rule for derivatives
Prove: Let P≪Q≪RP \ll Q \ll R be σ\sigma-finite measures, f= ⁣dP/ ⁣dQf = \dd P/\dd Q and g= ⁣dQ/ ⁣dRg = \dd Q/\dd R. Then P≪RP \ll R and  ⁣dP/ ⁣dR=f g\dd P/\dd R = f\,g RR-almost surely.
0
Use formula (1): if  ⁣dν=g ⁣dμ\dd\nu = g \dd\mu, then ∫φ ⁣dν=∫φ g ⁣dμ\int \varphi \dd\nu = \int \varphi\,g \dd\mu for every measurable φ≥0\varphi \ge 0. Also use uniqueness of the Radon–Nikodym derivative.

Step 1 of 4. How do you see that P≪RP \ll R?

ProofChange of measure, starting with indicators
Prove: Let QQ be a measure, w≥0w \ge 0 measurable and P(A)=∫Aw ⁣dQP(A) = \int_A w \dd Q. Then ∫g ⁣dP=∫g w ⁣dQ\int g \dd P = \int g\,w \dd Q for every measurable g≥0g \ge 0. If gg is PP-integrable, g wg\,w is QQ-integrable and the equality also holds.
0
Recall the integral's construction: indicators, simple functions, monotone limit, and g=g+−g−g = g^+ - g^-.

Step 1 of 4. Start with g=1Bg = \ind_B. What is true?

CodeAn importance estimator that warns
Implement importance_estimate(f, x, p_pdf, q_pdf). x are n samples from QQ (a NumPy array), p_pdf and q_pdf evaluate the densities (or mass functions) of PP and QQ relative to the same measure, vectorized, and f is the function whose expectation under PP is estimated. Return a dictionary with estimate (the mean of f(xi) wif(x_i)\,w_i with wi=p/qw_i = p/q), mean_weight (mean weight, which should equal 11), ess ((∑wi)2/∑wi2(\sum w_i)^2/\sum w_i^2), and warning (a boolean). Warn if mean weight differs from 11 by more than 44 standard errors, ∣wˉ−1∣>4 sw/n\abs{\bar w - 1} > 4\,s_w/\sqrt{n} with sws_w the sample standard deviation of weights (with ddof=1\mathtt{ddof}=1, and avoiding division by zero when sw=0s_w = 0), or if ESS<0.01 n\mathrm{ESS} < 0.01\,n.
import numpy as np

def importance_estimate(f, x, p_pdf, q_pdf):
  # pesos w = p(x)/q(x); estimación, media de pesos, ESS y aviso de soporte
  pass
Shift+Enter to run

Summary

Key idea
A density is a Radon–Nikodym derivative: p= ⁣dP/ ⁣dμp = \dd P/\dd\mu, the mass of PP per unit of reference measure μ\mu. It exists when P≪μP \ll \mu and μ\mu is σ\sigma-finite (von Neumann’s proof constructs it using Riesz in L2L^2). It is an equivalence class, not a value, and changes with μ\mu: pmf and pdf are the same object with counting and Lebesgue measure, while mixed laws have densities relative to Lebesgue plus deltas. What is not absolutely continuous separates cleanly (Lebesgue decomposition). Change of measure EP[f]=EQ[f  ⁣dP/ ⁣dQ]\E_P[f] = \E_Q[f\,\dd P/\dd Q] converts samples from QQ into estimates under PP, with possibly infinite variance and silent failure if P≪̸QP \not\ll Q, signaled only by a mean weight other than 11. Generative models supported on low-dimensional manifolds have neither densities nor a ratio: KL=∞\mathrm{KL} = \infty and JS=log⁡2\mathrm{JS} = \log 2 regardless of their proximity, motivating the addition of noise.