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 without asking what it means. Four real situations make the question pressing:
- A ReLU activation. If and , half the mass falls exactly at and the rest follows a bell curve. 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 but can only sample from another law . You reweight each sample by . When is that ratio legitimate? What is the ratio when has atoms or is discrete?
- An image generator. A network maps noise to an image in . The generated-image law lives on a set of dimension at most inside a space of dimension almost . What is its density relative to Lebesgue measure in that space? None, which is why and likelihood behave so poorly with GANs.
- A change of units. A model assigns to an image of pixels with values in . With pixels in it gives . 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 . When 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:
- Measures with densities. Build new measures from a function and see a necessary condition: absolute continuity.
- Radon–Nikodym. That condition is also sufficient. A complete proof for finite measures.
- Density as a derivative. Pmfs and pdfs are the same object, and mixed laws finally find their place.
- Lebesgue decomposition. The part of a measure without a density is isolated precisely.
- Change of measure. Reweight to move from to , with its cost, variance, and its silent failure.
- 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 and a function , you can redistribute by weighting it with :
This recipe builds much of applied probability: start from Lebesgue measure, choose a with integral and obtain a pdf. The recipe works with any starting measure, which will matter.
Proof
It is a measure. and . Let be disjoint with union . Then , a series of nonnegative functions, and by monotone convergence applied to partial sums, . That is, .
Formula (1). For this is the definition of . By linearity it holds for nonnegative simple functions. A measurable is the increasing limit of simple functions , so ; 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 with respect to means integrating with respect to . Every change of measure in this lesson follows from it. The recipe explains familiar facts:
- With (Lebesgue measure) and , is the law with density function . Formula (1) is the law of the unconscious statistician for expectation: .
- With the counting measure on a countable set , , and is a discrete law with mass function . Formula (1) is .
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 then (the integral of a nonnegative function over a null set is zero, as shown in the Lebesgue integral lesson). That is:
A measure with density relative to cannot charge any set that cannot see. This necessary condition has a name.
Absolute continuity and singularity
Remember this reading: means does not invent mass where measures nothing. Singularity is the opposite extreme, complete non-overlap: all the mass of lies where has none. The general case lies between them, with part of of each kind (the Lebesgue decomposition below).
| Relationship | Why | ||
|---|---|---|---|
| both have strictly positive density throughout , so their null sets are Lebesgue null sets | |||
| , not | every -null set is Lebesgue-null within , and fits there (point has no mass under ); conversely is -null but not -null | ||
| and | |||
| both charge every integer and only those integers | |||
| all mass lies on , which is Lebesgue-null | |||
| Cantor law | it lives on the Cantor set, of length | ||
| uniform on the unit circle | on | the circle has area |
Two cautions. The relation is not symmetric (the second row shows this), and two measures that are “not ” need not be singular: and share the segment and are neither one nor the other. Finally, for probability measures on , absolute continuity with respect to Lebesgue measure is precisely the property that the event “ falls in a zero-volume set” has probability zero.
The Radon–Nikodym theorem
We saw that having a density implies . The Radon–Nikodym theorem says this is the only obstruction.
Both assumptions are necessary. Absolute continuity is necessary, as just seen. -finiteness is necessary too, and the counterexample is instructive: let be counting measure on and Lebesgue measure. Then , because only if . But if existed, for every , hence and : a contradiction. The failure is that counting measure is not -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 is not the probability of anything: it is the rate of mass per unit of around .
Density as a ratio of measures
The notation is not arbitrary: it follows the rules of fractions.
Proof
(1) is an exercise in this lesson. (2) Apply (1) with : -almost surely. (3) If : , hence , and since this forces -almost surely on . Conversely, if then -almost surely on , and by assumption -almost surely on , giving . The ratio formula follows from (1): (on , and the remainder has no -mass).
∎The third rule contains this section’s most important practical lesson: the ratio does not depend on the reference measure. Replacing with another changes and , 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 counting measure, is the mass function ; with 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 is not neutral, and a poor choice means the density does not exist.
The next figure puts this in your hands. Compare the mixed law with three reference measures. For each, calculate over an interval that you drag, and read how much mass is lost relative to .
What you should have seen:
- With Lebesgue measure, the atom disappears. While does not contain this goes unnoticed; once it does, the lost-mass column shows . This is not a failure of the formula: , 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 (its only null set is empty), but it is not -finite, and without -finiteness the theorem does not apply: the “density” , for does not represent .
- With everything works for every . The right reference measure sees all parts of : each atom with its own delta and the continuous part with Lebesgue measure.
- A Lebesgue density value is not invariant. If on , then , so : density is divided by , probabilities are not. In dimension the factor is . This is the fourth opening example: changing pixels from to in an image with pixels subtracts nats from . 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 defines a bounded linear functional on , and bounded linear functionals on a Hilbert space are inner products (Riesz). We prove it for finite measures; the -finite case is reduced to it at the end.
Proof
Let and be finite measures with . Let , which is finite and satisfies .
Step 1: a bounded functional on . For , by Cauchy–Schwarz (in space with ),
Thus is a bounded linear functional on Hilbert space (well-defined on equivalence classes because a -null set is -null). By the Riesz representation theorem, which in a Hilbert space is the orthogonal projection onto the orthogonal complement of the kernel of with inner product (inner product), there exists with
Step 2: . With , (2) says , and . If , forces . If , and on force . Modifying on a -null set gives everywhere.
Step 3: rewrite. Since , (2) for bounded measurable reads , that is,
Step 4: the set is null. With in (3): . Thus and, by assumption , .
Step 5: the monotone limit. Take bounded in (3). Since ,
Now . Outside , , so and ; on , null for both measures, nothing changes. By monotone convergence on both sides, . Since , defining outside and on gives for every .
Uniqueness. If and satisfy the theorem and is finite, both are -integrable. With , with positive integrand on , so ; similarly for .
The -finite case. Intersect a partition of into sets of finite -measure with another of finite -measure, obtaining a countable partition where both measures are finite. Apply the finite case on each and glue the results: .
∎Two observations. First, of all the steps, only the fourth uses , 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 is not absolutely continuous with respect to , the previous proof gets stuck at step 4: remains true (it did not use the assumption), but need not be . The mass places on is precisely the mass cannot measure.
Proof
Existence (finite measures; the -finite case is glued as before). Repeat steps 1–3 of von Neumann’s proof, which do not use , and define . Step 4 gives . Let and . Then (it lives on , which is -null, and vanishes on ). And step 5, applied to sets , where has no problem, gives with : in particular .
Uniqueness. If , let be -null sets carrying , and , also -null. On , and equal (they are ). On , and equal . For every , then, , and similarly . No subtraction of measures is needed, so the argument works unchanged in the -finite case.
∎The three faces of a law on
For a law on relative to Lebesgue measure, the singular part can be split again. The atoms of are points with , and there are at most countably many: for every there are fewer than atoms of mass (otherwise total mass would exceed ). The part is singular with respect to (it lives on a countable, hence Lebesgue-null, set), and the remainder of is a singular measure without atoms. Thus every law on can be written uniquely as
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 (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 and small ,
is mass per unit length in a window around . The Lebesgue differentiation theorem (not proved here; see section 31 of Billingsley, one of the lesson references) says for -almost every . The Radon–Nikodym derivative is the limit of these ratios, while the other two parts behave as follows:
- At an atom, .
- For the singular continuous part, the ratio does not converge to anything useful: at almost every point (for ) it eventually equals , while at support points it oscillates or explodes. exists and equals almost everywhere, and .
Change of measure and likelihood ratio
Formula (1) in the first section, with and , is the lesson’s practical result.
The proof is (1), with , for ; extending to signed (separating and checking integrals are finite) is an exercise. is (4) with , and gives -almost surely.
Read (4) carefully: it is a machine. To calculate an expectation under , sample from another law and weight by . The general name for is likelihood ratio when and are data laws of two models, by the third calculus rule: . It appears in hypothesis tests (Neyman–Pearson lemma), in 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 between target and behavior policies corrects the data.
The Gaussian example
For and on , the ratio has a closed form, and its second moment explains what happens in high dimension.
The result grows exponentially in the square of the distance between the means, and for two Gaussians with coordinates separated by each, that square is . This is why importance sampling breaks down in high dimension even when and are almost identical coordinate by coordinate. The implementation cell measures it.
Estimator variance and effective sample size
Let be the proposal, and the importance-sampling estimator
By (4) it is unbiased for (even when does not exist as a finite number, within the cases). Its variance is
which can be infinite even when . This occurs when the tails of are lighter than those of : with and one calculates if , and otherwise. A proposal only somewhat narrower than the target already breaks the estimator.
To assess the damage without knowing , use the effective sample size (ESS)
the number of iid samples from equivalent to the weighted samples (a first-order approximation). It ranges from (one weight dominates) to (all equal). When is known only up to a constant, normalize by the sum of weights to obtain the self-normalized estimator , which is consistent though biased; see the library section.
When : failure without warning
What does formula calculate when is not absolutely continuous with respect to ? The Lebesgue decomposition answers precisely.
Proof
This is formula (1) with and : . And (the singular part lives on ), so . With , .
∎This is exactly what the figure with the uniform proposal shows: the estimator converges to the expectation of restricted to where can see, and the weight mean converges to the mass of covered by . No confidence interval based on sample variance detects this, because the estimator is stable with finite variance. The only defense is diagnostic : if the mean weight is not , something is wrong. The same happens with discrete variables, and underlies the coverage requirements on the behavior policy in off-policy reinforcement learning: whenever , precisely .
Disjoint supports: the density that does not exist
We arrive at the fourth opening situation. A generator with takes a law on to a law on (the pushforward law). For to have a density with respect to , the image of would need nonzero measure; it has measure zero.
Proof
It suffices to show is null for every . Divide the cube into cubes of side . If is the Lipschitz constant, each subcube’s image fits in a ball of radius and volume . Summing gives as because . The countable union of gives all of , and with .
∎Generators with ReLU activations are Lipschitz (piecewise linear), and smooth ones of class 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 (the square’s diagonal), (a parabola), and the uniform distribution on a circle: all are laws on without a density. The law of with independent , filling the square, does have one (the constant on ).
The serious issue arises when comparing two such laws. If and live on manifolds of dimension lower than , their supports are often disjoint or intersect on a set null for both. In either case and there is no likelihood ratio. Two consequences, each one line away:
- , because by definition if and otherwise. Bringing the laws closer does not help: however small the movement of , as long as the divergence equals .
- Jensen–Shannon divergence is constant. Let . If , on the support of we have , so , and symmetrically . Thus for any mutually singular pair of laws, whether is next to 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.
What is done in practice
There are three approaches, all appearing later in the course.
- Add noise. If , its density is throughout even when lives on a curve. Then and (in fact ). The price is an enormous divergence when 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.
- Change distance. Wasserstein distance does not require a ratio: if is a translation of by a vector , varies continuously with , while jumps from to .
- Work in latent space. If the manifold has a known parameterization , calculate density in the space of (dimension ) and correct with the area factor of the Jacobian of . The result is a density relative to the manifold’s surface measure, another reference measure, not to . 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 ), and compares it with a direct simulation of .
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 and , so variance is , and direct simulation agrees with quadrature within Monte Carlo error (of order ). The class has no special case for discrete or continuous: it is formula with .
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 is not :
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 is , and both expectations of equal exactly. With Gaussians, the estimate using samples from is within of value . With the uniform proposal the result is what the proposition predicted: the estimate is instead of and mean weight is instead of . is , not . 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 , whose is . It then measures how effective sample size collapses as dimension increases.
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 the five estimates cluster around and effective sample size is on the order of of . With , which covers the first mode but barely sees the one at ( standard deviations away), estimates fluctuate between and and only one sample in a thousand counts: the estimator is unbiased and, at , useless. With there is a third, most dangerous behavior: tails are lighter than those of , variance is infinite and estimates stabilize near , while mean weight instead of reveals that the estimator remains far from despite . The second block measures dimension: through the measured column follows , then stays above it. Estimated ESS becomes optimistic because the huge weights that would dominate are so rare they do not appear in samples: at the cell reports one useful sample per , while the true value is one per . The key result is that with , only half a standard deviation of difference per coordinate, at effective sample size has already fallen below , 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: can equal or in high dimension and overflow is silent. The cell does three things: self-normalized importance sampling (useful when 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.
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 with samples and without knowing the constant of . The singular Gaussian’s density is on the line and outside: it is a density relative to length on the line, a different reference measure, and comparing it with a pdf on would be absurd. The third table shows the fourth common mistake: when data flatten onto the line (thickness ), the fitted Gaussian’s mean log likelihood grows without bound, as (from with to with ), 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
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. How do you see that ?
Step 1 of 4. Start with . What is true?
importance_estimate(f, x, p_pdf, q_pdf). x are n samples from (a NumPy array), p_pdf and q_pdf evaluate the densities (or mass functions) of and relative to the same measure, vectorized, and f is the function whose expectation under is estimated. Return a dictionary with estimate (the mean of with ), mean_weight (mean weight, which should equal ), ess (), and warning (a boolean). Warn if mean weight differs from by more than standard errors, with the sample standard deviation of weights (with , and avoiding division by zero when ), or if .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