diff --git a/lectures/_static/quant-econ.bib b/lectures/_static/quant-econ.bib index 5f54c1755..2beb587fd 100644 --- a/lectures/_static/quant-econ.bib +++ b/lectures/_static/quant-econ.bib @@ -6207,6 +6207,37 @@ @article{Giannitsarou2005 pages = {276--287} } +@article{EvansHonkapohjaWilliams2010, + author = {Evans, George W. and Honkapohja, Seppo and Williams, Noah}, + title = {Generalized Stochastic Gradient Learning}, + journal = {International Economic Review}, + year = {2010}, + volume = {51}, + number = {1}, + pages = {237--262}, + doi = {10.1111/j.1468-2354.2009.00578.x} +} + +@article{Amari1998, + author = {Amari, Shun-ichi}, + title = {Natural Gradient Works Efficiently in Learning}, + journal = {Neural Computation}, + year = {1998}, + volume = {10}, + number = {2}, + pages = {251--276} +} + +@article{HeymannVandenEijnden2008, + author = {Heymann, Matthias and Vanden-Eijnden, Eric}, + title = {The Geometric Minimum Action Method: A Least Action Principle on the Space of Curves}, + journal = {Communications on Pure and Applied Mathematics}, + year = {2008}, + volume = {61}, + number = {8}, + pages = {1052--1117} +} + @article{MalmendierNagel2016, author = {Malmendier, Ulrike and Nagel, Stefan}, title = {Learning from Inflation Experiences}, @@ -6824,6 +6855,153 @@ @article{Nielsen2013 doi = {10.1109/LSP.2013.2243726} } +@misc{NielsenMLSS2015, + author = {Nielsen, Frank}, + title = {Computational Information Geometry for Machine Learning}, + howpublished = {Lecture slides, Machine Learning Summer School, Sydney}, + year = {2015} +} + +@article{Fisher1922, + author = {Fisher, Ronald A.}, + title = {On the Mathematical Foundations of Theoretical Statistics}, + journal = {Philosophical Transactions of the Royal Society of London. Series A}, + year = {1922}, + volume = {222}, + pages = {309--368}, + doi = {10.1098/rsta.1922.0009} +} + +@article{Darmois1935, + author = {Darmois, Georges}, + title = {Sur les lois de probabilit{\'e} {\`a} estimation exhaustive}, + journal = {Comptes Rendus de l'Acad{\'e}mie des Sciences}, + year = {1935}, + volume = {200}, + pages = {1265--1266} +} + +@article{Koopman1936, + author = {Koopman, Bernard O.}, + title = {On Distributions Admitting a Sufficient Statistic}, + journal = {Transactions of the American Mathematical Society}, + year = {1936}, + volume = {39}, + number = {3}, + pages = {399--409}, + doi = {10.1090/S0002-9947-1936-1501854-3} +} + +@article{Pitman1936, + author = {Pitman, Edwin J. G.}, + title = {Sufficient Statistics and Intrinsic Accuracy}, + journal = {Mathematical Proceedings of the Cambridge Philosophical Society}, + year = {1936}, + volume = {32}, + pages = {567--579} +} + +@article{Rao1945, + author = {Rao, C. Radhakrishna}, + title = {Information and the Accuracy Attainable in the Estimation of Statistical Parameters}, + journal = {Bulletin of the Calcutta Mathematical Society}, + year = {1945}, + volume = {37}, + pages = {81--91} +} + +@article{CostaSantosStrapasson2015, + author = {Costa, Sueli I. R. and Santos, Sandra A. and Strapasson, Jo{\~a}o E.}, + title = {Fisher Information Distance: A Geometrical Reading}, + journal = {Discrete Applied Mathematics}, + year = {2015}, + volume = {197}, + pages = {59--69} +} + +@article{KhanZhang2022, + author = {Khan, Gabriel and Zhang, Jun}, + title = {When Optimal Transport Meets Information Geometry}, + journal = {Information Geometry}, + year = {2022}, + volume = {5}, + pages = {47--78}, + doi = {10.1007/s41884-022-00066-w} +} + +@article{AmariKarakidaOizumi2018, + author = {Amari, Shun-ichi and Karakida, Ryo and Oizumi, Masafumi}, + title = {Information Geometry Connecting {W}asserstein Distance and {K}ullback--{L}eibler Divergence via the Entropy-Relaxed Transportation Problem}, + journal = {Information Geometry}, + year = {2018}, + volume = {1}, + number = {1}, + pages = {13--37} +} + +@article{McCann1997, + author = {McCann, Robert J.}, + title = {A Convexity Principle for Interacting Gases}, + journal = {Advances in Mathematics}, + year = {1997}, + volume = {128}, + number = {1}, + pages = {153--179} +} + +@article{Takatsu2011, + author = {Takatsu, Asuka}, + title = {{W}asserstein Geometry of {G}aussian Measures}, + journal = {Osaka Journal of Mathematics}, + year = {2011}, + volume = {48}, + number = {4}, + pages = {1005--1026} +} + +@article{PeyreCuturi2019, + author = {Peyr{\'e}, Gabriel and Cuturi, Marco}, + title = {Computational Optimal Transport: With Applications to Data Science}, + journal = {Foundations and Trends in Machine Learning}, + year = {2019}, + volume = {11}, + number = {5--6}, + pages = {355--607} +} + +@article{Gelbrich1990, + author = {Gelbrich, Matthias}, + title = {On a Formula for the {$L^2$} {W}asserstein Metric between Measures on {E}uclidean and {H}ilbert Spaces}, + journal = {Mathematische Nachrichten}, + year = {1990}, + volume = {147}, + number = {1}, + pages = {185--203}, + doi = {10.1002/mana.19901470121} +} + +@article{MatejkaMcKay2015, + author = {Mat{\v{e}}jka, Filip and McKay, Alisdair}, + title = {Rational Inattention to Discrete Choices: A New Foundation for the Multinomial Logit Model}, + journal = {American Economic Review}, + year = {2015}, + volume = {105}, + number = {1}, + pages = {272--298}, + doi = {10.1257/aer.20130047} +} + +@article{DupuyGalichon2014, + author = {Dupuy, Arnaud and Galichon, Alfred}, + title = {Personality Traits and the Marriage Market}, + journal = {Journal of Political Economy}, + year = {2014}, + volume = {122}, + number = {6}, + pages = {1271--1319}, + doi = {10.1086/677191} +} + @article{AndersonDePalmaThisse1988, author = {Anderson, Simon P. and de Palma, Andr{\'e} and Thisse, Jacques-Fran{\c{c}}ois}, title = {A Representative Consumer Theory of the Logit Model}, diff --git a/lectures/_toc.yml b/lectures/_toc.yml index 30c85b37d..0b6a46cfa 100644 --- a/lectures/_toc.yml +++ b/lectures/_toc.yml @@ -34,11 +34,6 @@ parts: numbered: true chapters: - file: divergence_measures - - file: exponential_families - - file: information_projections - - file: approximation_errors - - file: specification_tests - - file: turbulence_inference - file: likelihood_ratio_process - file: likelihood_ratio_process_2 - file: likelihood_var @@ -57,6 +52,14 @@ parts: - file: pricing_information - file: market_diffusion - file: gallant_tauchen +- caption: Information Geometry + numbered: true + chapters: + - file: exponential_families + - file: information_projections + - file: approximation_errors + - file: specification_tests + - file: turbulence_inference - caption: Linear Programming numbered: true chapters: diff --git a/lectures/approximation_errors.md b/lectures/approximation_errors.md index 7de1da178..551a4af12 100644 --- a/lectures/approximation_errors.md +++ b/lectures/approximation_errors.md @@ -28,9 +28,9 @@ kernelspec: ## Overview -When an econometrician estimates a model that does not contain the process that generated the data, the maximum likelihood estimator converges, under regularity conditions, to the member of the model that is closest to the true process in the sense of Kullback–Leibler (KL) divergence. +When an econometrician estimates a family of models that does not contain the process that generated the data, the maximum likelihood estimator converges, under regularity conditions, to the model in the family that is closest to the true process in the sense of Kullback–Leibler (KL) divergence. -In {doc}`information_projections` we called that member the **m-projection** of the true distribution onto the model. +In {doc}`information_projections` we called that model the **m-projection** of the true distribution onto the family. We organize this lecture around one consequence of that fact: by choosing the model, the data, and any filter that transforms the data, an econometrician chooses which projection an estimator computes. @@ -62,7 +62,7 @@ We use the following imports. import numpy as np import matplotlib.pyplot as plt from scipy import integrate -from scipy.linalg import toeplitz, cho_factor, cho_solve +from scipy.linalg import toeplitz, cho_factor, cho_solve, sqrtm from scipy.optimize import minimize ``` @@ -1046,6 +1046,50 @@ Sims's filter $1 - \kappa(L)\kappa(L^{-1})$ is zero at $\pm\pi/2$, at $\pi$, and It removes the deterministic seasonal, whose spectral measure puts all its mass at $\pm\pi/2$, and the equality applies to what remains, as {ref}`ae_ex_invariance` shows. +The invariance belongs to the KL divergence, which compares two processes frequency by frequency through the ratio $f / g$. + +A distance that measures how far probability mass must move does not have it. + +The squared 2-Wasserstein distance of {doc}`exponential_families` between $N(0, \Sigma_1)$ and $N(0, \Sigma_2)$ is $\operatorname{tr}\left(\Sigma_1 + \Sigma_2 - 2 (\Sigma_1^{1/2} \Sigma_2 \Sigma_1^{1/2})^{1/2}\right)$ {cite}`Gelbrich1990`. + +The covariance matrices of $T$ consecutive observations of two stationary processes are nearly diagonalized by the same Fourier basis when $T$ is large, so for two Gaussian processes with mean zero this distance, divided by $T$, converges to + +$$ +\frac{1}{2\pi} \int_{-\pi}^{\pi} \left( \sqrt{f(\omega)} - \sqrt{g(\omega)} \right)^2 d\omega . +$$ (ae_w2_rate) + +Filtering both processes by $c(L)$ multiplies the integrand by $\lvert c(e^{-i\omega}) \rvert^2$, so the filter changes the distance even when it leaves the divergence rate unchanged. + +We check {eq}`ae_w2_rate` for a first-order autoregression with $\rho = 0.8$ and white noise with variance $2$, and filter both by $1 - 0.9 L$. + +```{code-cell} ipython3 +def w2_squared_gaussian(S1, S2): + """Squared 2-Wasserstein distance between N(0, S1) and N(0, S2).""" + root = sqrtm(S1) + return np.trace(S1 + S2 - 2 * np.real(sqrtm(root @ S2 @ root))) + + +def w2_rate(f, g): + """(1/2π) ∫ (√f - √g)² dω on the grid.""" + return np.mean((np.sqrt(f) - np.sqrt(g))**2) + + +f_ar, g_wn = ar_spectrum(0.8), ar_spectrum(0.0, 2.0) +for T_w in (100, 400): + S_f, S_g = toeplitz(autocov(f_ar, T_w - 1)), toeplitz(autocov(g_wn, T_w - 1)) + print(f"T = {T_w}: W2² / T = {w2_squared_gaussian(S_f, S_g) / T_w:.4f}") + +gain_sq = np.abs(1 - 0.9 * z)**2 +print(f"formula (ae_w2_rate): {w2_rate(f_ar, g_wn):.4f}") +print(f"filtered by 1 - 0.9L: W2 rate {w2_rate(gain_sq * f_ar, gain_sq * g_wn):.4f}, " + f"KL rate {kl_rate(f_ar, g_wn):.4f} before and " + f"{kl_rate(gain_sq * f_ar, gain_sq * g_wn):.4f} after") +``` + +The filter leaves the KL divergence rate at its value and changes the Wasserstein rate. + +{doc}`exponential_families` describes the same contrast for transformations of a single random variable. + A filter cannot delete a band of frequencies from the likelihood. A filter whose frequency response is zero on a band makes the filtered processes linearly deterministic, and formula {eq}`ae_kl_rate`, which assumes spectral densities bounded away from zero, no longer applies. diff --git a/lectures/exponential_families.md b/lectures/exponential_families.md index eb3561578..2afff1c68 100644 --- a/lectures/exponential_families.md +++ b/lectures/exponential_families.md @@ -28,24 +28,57 @@ kernelspec: ## Overview -This lecture and its sequel {doc}`information_projections` describe some elements of **information geometry**, a body of work that studies families of probability distributions with tools from convex analysis and differential geometry. +This lecture and its sequel {doc}`information_projections` describe elements of **information geometry**, a field that uses tools from convex analysis and differential geometry to study parameterized families of probability distributions. -We use information geometry to describe the **exponential family** of probability distributions. +A key concept in information geometry is an **exponential family** of probability distributions. -The exponential family includes the Bernoulli, Poisson, normal, gamma, and Beta distributions. +To understand what an exponential family is, we must understand the definition of a **sufficient statistic** for the parameter of a family of probability distributions. -A convex function, the **log-partition function**, generates +A sufficient statistic carries all the information about the parameter that a sample contains. -* two systems of coordinates for the members of a family, called **natural parameters** and **expectation parameters**; +```{note} +{cite:t}`Darmois1935`, {cite:t}`Koopman1936`, and {cite:t}`Pitman1936` described smoothness conditions under which a family of densities whose set of possible outcomes does not depend on its parameter is an exponential family if samples of every size have a sufficient statistic of the same finite dimension. +``` + +The exponential family includes the Bernoulli, exponential, Poisson, normal, gamma, and Beta families, among others. + +Geometry studies **invariants**, properties that do not change when we change coordinates. + +To characterize such **invariants**, we ask which objects change and which do not when we relabel the parameters of a family or transform the data. + +KL divergence does not change when appropriate transformations are applied to either the parameters or the data. + +However, the Euclidean distance between parameter vectors *does* change when we relabel parameters. + +Differential entropy *does* change when we transform the data. + +A key tool used to define an exponential family is a convex function called the **log-partition function**. + +The log-partition function generates + +* two systems of coordinates for the models in a family, called **natural parameters** and **expectation parameters**; * the means and covariances of the family's sufficient statistics; * the Fisher information matrix; -* the entropy of each member, through a Legendre transform, when the family's base measure is constant; and -* the Kullback–Leibler (KL) divergence between any two members, through a **Bregman divergence**. +* the entropy of each model, through a Legendre transform, when the family's base measure is constant; and +* the Kullback–Leibler (KL) divergence between any two models, through a **Bregman divergence**. + +```{note} +Here "system of coordinates" is a synonym for "parameterization of a family." +``` -Members of the exponential family answer a question posed by {cite:t}`Jaynes1957`: which probability distribution expresses the least information, as measured by Shannon's entropy, among all distributions that have given means of some statistics? +Each model in an exponential family answers a question posed by {cite:t}`Jaynes1957`: what probability distribution expresses the least information, as measured by Shannon's entropy, among all distributions that have given means of some statistics? A special case characterizes the normal distribution: among all densities on the real line with a given mean and variance, the normal density has the largest entropy. +The **Fisher information matrix** assigns lengths to paths of models and defines a distance between models, the **Fisher–Rao distance**. + +The Fisher–Rao distance does not change when we relabel parameters or transform the data. + +For the normal family, it is a distance of hyperbolic geometry. + +The **Wasserstein distance** of optimal transport measures instead how far probability mass must move to turn one model into another; it does not change when we relabel parameters, but it does change when we transform the data. + +```{note} Economists already use several of these tools under other names. The log-partition function and its **Legendre transform** are related in the same way as a profit function and a production function. @@ -57,15 +90,18 @@ The **inclusive value** of the multinomial logit model of discrete choice is a l Up to a constant, it is the expected utility of the best alternative. Its Legendre transform is minus an entropy. +``` The sequel {doc}`information_projections` uses these tools to study projections of probability distributions onto families of distributions, with applications to maximum likelihood, robust control, the updating of input–output tables, and optimal transport. -The lecture builds on {doc}`divergence_measures`, which describes entropy, cross-entropy, and KL divergence; we use its notation. +The lecture builds on {doc}`divergence_measures`, which describes entropy, cross-entropy, and KL divergence; we import some of its notation. {doc}`mle` and {doc}`multivariate_normal` provide additional background. {cite:t}`amari_nagaoka2000`, {cite:t}`Nielsen2020`, and chapters 2, 8, 11, and 12 of {cite:t}`CoverThomas2006` treat the material of this lecture and its sequel. +Our order of topics follows the lecture slides of {cite:t}`NielsenMLSS2015`. + We use the following imports. ```{code-cell} ipython3 @@ -75,16 +111,133 @@ from scipy import integrate from scipy.optimize import brentq from scipy.special import logsumexp, digamma, polygamma, gammaln from scipy.stats import norm, poisson, laplace, logistic, uniform, chi2 +from scipy.stats import lognorm, cauchy from scipy.stats import gamma as gamma_dist ``` -## Coordinates matter +## Models and families + +### Models, families, and parameters + +A **model** is a probability distribution for a random variable $X$ that takes values in a set $\mathcal X$. + +We describe a model by a density or by a probability mass function. + +A **parametric family** is a set of models + +$$ +\mathcal P = \{ p(\cdot\,; \theta) : \theta \in \Theta \} , +$$ + +where the **parameter space** $\Theta$ is a subset of $\mathbb R^D$. + +The map $\theta \mapsto p(\cdot\,; \theta)$ is a **parameterization** of $\mathcal P$; it assigns coordinates $\theta$ to the models in $\mathcal P$. + +Statisticians often call a whole family a "statistical model." + +We do not. + +In this lecture, a model is a single distribution $p(\cdot\,; \theta)$ at a single parameter vector $\theta$, and a family is a set of models indexed by parameter vectors that range over $\Theta$. + +Here are six families. + +* The **Bernoulli family**: $\mathcal X = \{0, 1\}$, $p(x; \pi) = \pi^x (1 - \pi)^{1 - x}$, and $\Theta = (0, 1)$. +* The **Poisson family**: $\mathcal X = \{0, 1, 2, \ldots\}$, $p(x; \lambda) = \lambda^x e^{-\lambda} / x!$, and $\Theta = (0, \infty)$. +* The **normal family**: $\mathcal X = \mathbb R$, $p(x; \mu, \sigma) = (2 \pi \sigma^2)^{-1/2} \exp\left(-(x - \mu)^2 / (2 \sigma^2)\right)$, and $\Theta$ is the half-plane $\mathbb R \times (0, \infty)$. +* The **uniform family**: $\mathcal X = (0, \infty)$, $p(x; \theta) = 1/\theta$ for $0 < x < \theta$ and $p(x; \theta) = 0$ for $x \geq \theta$, and $\Theta = (0, \infty)$. +* The **Cauchy location family**: $\mathcal X = \mathbb R$, $p(x; \mu) = 1 / \left(\pi (1 + (x - \mu)^2)\right)$, and $\Theta = \mathbb R$. +* A **normal mixture family**: $\mathcal X = \mathbb R$, $p(x; w, \mu_1, \mu_2) = w \, \varphi(x - \mu_1) + (1 - w) \, \varphi(x - \mu_2)$, where $\varphi$ is the $N(0, 1)$ density, and $\Theta = [0, 1] \times \mathbb R^2$. + +In the Bernoulli family $\pi$ is a probability; in the normal and Cauchy families it is $3.14159\ldots$. + +A parameterization is **identifiable** if different parameter vectors give different models. + +The parameterizations of the first five families are identifiable. + +The mixture parameterization is not: $(w, \mu_1, \mu_2)$ and $(1 - w, \mu_2, \mu_1)$ give the same model, every $w$ gives the same model when $\mu_1 = \mu_2$, and every $\mu_1$ gives the same model when $w = 0$. + +We assume that a parameterization is identifiable and smooth, and that the $D$ functions $\partial p(\cdot\,; \theta) / \partial \theta_i$ are linearly independent. + +Then $\mathcal P$ is a $D$-dimensional surface, or **manifold**, in the set of all probability distributions on $\mathcal X$, and $\theta$ is a coordinate system on $\mathcal P$. + +Harold Hotelling in 1930 and {cite:t}`Rao1945` studied a parametric family as such a space. + +A family has many coordinate systems. + +We can describe the normal family by $(\mu, \sigma)$, by $(\mu, \sigma^2)$, or by the pair of means $(E X, E X^2) = (\mu, \mu^2 + \sigma^2)$. + +### Score and Fisher information + +The **score** of a model is the gradient $\nabla_\theta \log p(X; \theta)$ of its log density with respect to the parameter vector. + +When we can differentiate under the integral sign, the score has mean zero: + +$$ +E_\theta \left[ \nabla_\theta \log p(X; \theta) \right] = \int \nabla_\theta \, p(x; \theta) \, dx = \nabla_\theta \int p(x; \theta) \, dx = 0 . +$$ + +The covariance matrix of the score is the **Fisher information matrix** + +$$ +I(\theta) = E_\theta \left[ \nabla_\theta \log p(X; \theta) \, \nabla_\theta \log p(X; \theta)^\top \right] . +$$ (ef_fisher) + +An IID sample of size $n$ has Fisher information $n I(\theta)$. + +The Cramér–Rao inequality says that the covariance matrix of an unbiased estimator of $\theta$ from such a sample exceeds $I(\theta)^{-1} / n$ by a positive semidefinite matrix. + +For the normal family in coordinates $(\mu, \sigma)$, + +$$ +I(\mu, \sigma) = \frac{1}{\sigma^2} \begin{bmatrix} 1 & 0 \\ 0 & 2 \end{bmatrix} . +$$ (ef_fisher_normal) + +### Sufficient statistics + +Let $\mathbf X = (X_1, \ldots, X_n)$ be an IID sample from a model $p(\cdot\,; \theta)$ in a family $\mathcal P$. + +A **statistic** is a function $s(\mathbf X)$ of the sample that does not involve $\theta$. + +A statistic $s$ is **sufficient** for $\theta$ in the family $\mathcal P$ if the conditional distribution of $\mathbf X$ given $s(\mathbf X)$ is the same for every $\theta \in \Theta$. + +Once we know $s(\mathbf X)$, the rest of the sample tells us nothing more about $\theta$. + +{cite:t}`Fisher1922` introduced sufficiency. + +The Fisher–Neyman **factorization theorem** says that $s$ is sufficient if and only if the joint density factors as + +$$ +\prod_{i=1}^n p(x_i; \theta) = g\left(s(\mathbf x); \theta\right) a(\mathbf x) +$$ (ef_factorization) + +for some functions $g$ and $a$, where $a$ does not depend on $\theta$. + +By {eq}`ef_factorization`, two samples with the same value of $s$ have proportional likelihood functions. + +They deliver the same maximum likelihood estimate and, under any prior, the same posterior distribution. + +Sufficiency is a property of a statistic relative to a family. + +We give examples of sufficient statistics after we define an exponential family. + +(ef_invariants)= +## Invariants + +Felix Klein's Erlangen program of 1872 defined a geometry by a group of transformations and studied the properties of figures that the transformations leave unchanged. + +Information geometry studies properties of models and families that survive three kinds of transformation. -We usually describe a normal distribution by its mean $\mu$ and standard deviation $\sigma$. +1. A **reparameterization** replaces $\theta$ by $\xi = \phi(\theta)$, where $\phi$ is smooth and one-to-one with a smooth inverse. Each model stays the same; only its coordinates change. +2. An **invertible transformation of the data** replaces $X$ by $Y = f(X)$, where $f$ is smooth and one-to-one. Each model for $X$ becomes a model for $Y$, and the family keeps its parameter space. +3. A **statistic** replaces the data by a function of the data. More generally, a **garbling** of the kind studied in {doc}`blackwell_kihlstrom` replaces the data by a random variable whose conditional distribution given the data does not depend on $\theta$. Statistics and garblings can discard information. -The pair $(\mu, \sigma)$ is a point in a half-plane, but the ordinary distance between two such points says little about how hard it is to tell the two distributions apart from data. +### Distances between parameter vectors -Consider four normal distributions: +We usually describe a normal model by its mean $\mu$ and standard deviation $\sigma$. + +The pair $(\mu, \sigma)$ is a point in a half-plane, but the ordinary distance between two such points says little about how hard it is to tell the two models apart from data. + +Consider four normal models: * $A = N(0, 0.2^2)$ and $B = N(1, 0.2^2)$, and * $C = N(0, 2^2)$ and $D = N(1, 2^2)$. @@ -93,7 +246,9 @@ In the $(\mu, \sigma)$ half-plane, $A$ is as far from $B$ as $C$ is from $D$. But $A$ and $B$ barely overlap, while $C$ and $D$ overlap heavily. -The KL divergence between two normal distributions with a common standard deviation $\sigma$ is $(\mu_1 - \mu_2)^2 / (2 \sigma^2)$, which is $12.5$ for $A$ and $B$ and $0.125$ for $C$ and $D$. +We read $D_{KL}(p \| q) = \int p(x) \log (p(x) / q(x)) \, dx$ as "the KL divergence of $p$ from $q$." + +The KL divergence between two normal models with a common standard deviation $\sigma$ is $(\mu_1 - \mu_2)^2 / (2 \sigma^2)$, which is $12.5$ for $A$ and $B$ and $0.125$ for $C$ and $D$. ```{code-cell} ipython3 --- @@ -118,374 +273,389 @@ A geometry of probability distributions should measure distances by how distingu For the exponential family, one convex function generates such a geometry. -## Maximum entropy +### What changes and what does not -### A die +In the table below, $J = \partial \theta / \partial \xi$ is the Jacobian matrix of the inverse of a reparameterization $\phi$, and $f'$ is the derivative of a transformation $f$ of scalar data. -Edwin Jaynes proposed the maximum entropy principle {cite}`Jaynes1957` and illustrated it in his 1962 Brandeis lectures with the following problem, now known as the Brandeis dice problem {cite}`Jaynes1963`. +| object | reparameterization $\theta \to \xi = \phi(\theta)$ | transformation of the data $x \to y = f(x)$ | +|---|---|---| +| KL divergence between two models | unchanged | unchanged | +| Fisher information matrix | becomes $J^\top I(\theta) J$ | unchanged | +| Euclidean distance between parameter vectors | changes | unchanged | +| Wasserstein distance between two models | unchanged | changes | +| density of a model at a point | unchanged | divided by $\lvert f'(x) \rvert$ | +| differential entropy of a model | unchanged | changes by $E \log \lvert f'(X) \rvert$ | +| maximum likelihood estimate | becomes $\phi(\hat \theta)$ | unchanged | +| unbiasedness of an estimator | can be lost | unchanged | +| a flat prior density | generally not flat in $\xi$ | unchanged | +| the Jeffreys prior | unchanged | unchanged | -A die has faces $x \in \{1, 2, \ldots, 6\}$. +Under $y = f(x)$, each density acquires the factor $1 / \lvert f'(x) \rvert$, which does not depend on $\theta$. -We are told only that the average number of spots is $4.5$, rather than the $3.5$ of a fair die. +Likelihood ratios and scores do not change, so neither do KL divergences, Fisher information matrices, and maximum likelihood estimates. -Which probability distribution $p = (p_1, \ldots, p_6)$ should we assign to the faces? +Differential entropy changes because it is an expectation of the log density itself: measuring income in cents instead of dollars adds $\log 100$ to it. -Many distributions have mean $4.5$. +Under a reparameterization, the chain rule multiplies the score by $J^\top$, so the Fisher information matrix becomes $J^\top I(\theta) J$. -Jaynes proposed choosing the one that is "maximally noncommittal with regard to missing information" {cite}`Jaynes1957`, which he took to mean the one that maximizes Shannon's entropy +The quadratic form $d\theta^\top I(\theta) \, d\theta$ does not change, because $d\theta = J \, d\xi$. -$$ -H(p) = - \sum_{x} p(x) \log p(x) -$$ +{ref}`ef_fisher_rao` uses this quadratic form to define a distance between models that does not depend on coordinates. -subject to $\sum_x p(x) = 1$ and $\sum_x x \, p(x) = 4.5$. +The maximum likelihood estimate changes its coordinates from $\hat \theta$ to $\phi(\hat \theta)$ and names the same model. -### The solution is an exponential family +Unbiasedness can be lost because $E \phi(\hat \theta) \neq \phi(E \hat \theta)$ when $\phi$ is nonlinear; {ref}`ef_estimation` gives an example. -Let's solve a more general version of this problem. +A flat prior on $\sigma$ is not flat on $\sigma^2$. -Let $t(x) = (t_1(x), \ldots, t_d(x))$ be a vector of functions of the outcome $x$, which takes values in a finite set. +The prior of {cite:t}`jeffreys1946invariant` has density proportional to $\sqrt{\det I(\theta)}$. -We seek the distribution $p$ that maximizes $H(p)$ subject to the moment conditions +In coordinates $\xi$, its density is proportional to $\sqrt{\det (J^\top I J)} = \lvert \det J \rvert \sqrt{\det I}$, as the change-of-variables formula requires, so the Jeffreys prior assigns the same probability to each set of models in every coordinate system. -$$ -\sum_x p(x) \, t(x) = c -$$ (ef_moments) +{ref}`ef_ex_jeffreys` works out the Bernoulli case. -for a given vector $c$, and $\sum_x p(x) = 1$. +We compute several of these objects for two normal models, $N(1, 1.5^2)$ and $N(-0.5, 1)$. -Attach a vector of Lagrange multipliers $\theta$ to {eq}`ef_moments`. +We use four coordinate systems: $(\mu, \sigma)$, $(\mu, \sigma^2)$, the pair of means $(\mu, \mu^2 + \sigma^2)$, and $(\mu / \sigma^2, -1 / (2 \sigma^2))$, which we meet again as natural parameters. -The first-order condition for $p(x)$ is $-\log p(x) - 1 + \theta \cdot t(x) - \nu = 0$, where $\nu$ is the multiplier on $\sum_x p(x) = 1$. +The transformation $y = e^x$ turns each normal model into a lognormal model. -The solution has the form +The function `fisher_matrix` computes {eq}`ef_fisher` by numerical integration, with the score computed by finite differences. -$$ -p(x; \theta) = \exp\left( \theta \cdot t(x) - F(\theta) \right), -\qquad -F(\theta) = \log \sum_x \exp\left( \theta \cdot t(x) \right) , -$$ (ef_maxent_solution) +```{code-cell} ipython3 +def fisher_matrix(logpdf, v, a, b, h=1e-5): + """Fisher information matrix (ef_fisher) at parameter vector v, by quadrature.""" + v = np.asarray(v, dtype=float) + e = np.eye(v.size) * h -where $\theta$ satisfies {eq}`ef_moments`. + def score(z): + return np.array([(logpdf(z, v + e[i]) - logpdf(z, v - e[i])) / (2 * h) + for i in range(v.size)]) -The function $F$ makes the probabilities sum to one. + return np.array([[integrate.quad( + lambda z: score(z)[i] * score(z)[j] * np.exp(logpdf(z, v)), + a, b, limit=200)[0] for j in range(v.size)] for i in range(v.size)]) -Such a $\theta$ exists if and only if $c$ lies in the relative interior of the convex hull of the points $t(x)$, that is, in its interior as a subset of the smallest affine subspace that contains it; for the die below, if and only if $1 < c < 6$. -When $c$ lies on the relative boundary, as for a die whose mean is $6$, a maximizing distribution still exists. +def kl_quad(logpdf, v1, v2, a, b): + """KL divergence of model v1 from model v2, by quadrature.""" + f = lambda z: np.exp(logpdf(z, v1)) * (logpdf(z, v1) - logpdf(z, v2)) + return integrate.quad(f, a, b, limit=200)[0] -It puts zero probability on some outcomes, and it lies outside the family, as a limit of members whose $\theta$ diverges. -A family of distributions of the form {eq}`ef_maxent_solution` is called an **exponential family**. +def x_normal(x, v): # log density of X, coordinates (μ, σ) + return norm.logpdf(x, v[0], v[1]) -The Lagrange multipliers $\theta$ are its **natural parameters**, and $t$ is its **sufficient statistic**. -To confirm that {eq}`ef_maxent_solution` is a maximum, let $p$ be any distribution that satisfies {eq}`ef_moments`, and let $p^*$ be the member of the exponential family that satisfies it. +def y_lognormal(y, v): # log density of Y = exp(X), coordinates (μ, σ) + return lognorm.logpdf(y, s=v[1], scale=np.exp(v[0])) -Because $\log p^*(x) = \theta \cdot t(x) - F(\theta)$ is an affine function of $t(x)$, and $p$ and $p^*$ assign the same mean $c$ to $t$, -$$ -\sum_x p(x) \log p^*(x) = \theta \cdot c - F(\theta) = \sum_x p^*(x) \log p^*(x) = - H(p^*) . -$$ +def x_natural(x, v): # log density of X, coordinates (μ/σ², -1/(2σ²)) + return norm.logpdf(x, -v[0] / (2 * v[1]), np.sqrt(-1 / (2 * v[1]))) -We read $D_{KL}(p \| q) = \sum_x p(x) \log (p(x) / q(x))$ as "the KL divergence of $p$ from $q$." -Therefore +(μ1, σ1), (μ2, σ2) = (1.0, 1.5), (-0.5, 1.0) +coordinates = { + "(μ, σ)": lambda μ, σ: np.array([μ, σ]), + "(μ, σ²)": lambda μ, σ: np.array([μ, σ**2]), + "(μ, μ² + σ²)": lambda μ, σ: np.array([μ, μ**2 + σ**2]), + "(μ/σ², -1/(2σ²))": lambda μ, σ: np.array([μ / σ**2, -1 / (2 * σ**2)]), +} +print("Euclidean distance between the two parameter vectors") +for name, c in coordinates.items(): + print(f" {name:18} {np.linalg.norm(c(μ1, σ1) - c(μ2, σ2)):.4f}") + +print("\nKL divergence") +print(f" from X: " + f"{kl_quad(x_normal, (μ1, σ1), (μ2, σ2), -np.inf, np.inf):.6f}") +print(f" from Y = exp(X): " + f"{kl_quad(y_lognormal, (μ1, σ1), (μ2, σ2), 0, np.inf):.6f}") + +H_x = norm(μ1, σ1).entropy() +H_y = lognorm(s=σ1, scale=np.exp(μ1)).entropy() +print("\ndifferential entropy of the first model") +print(f" of X: {H_x:.4f}, of Y: {H_y:.4f}, difference: {H_y - H_x:.4f}") + +θ1 = coordinates["(μ/σ², -1/(2σ²))"](μ1, σ1) +cases = (("from X, coordinates (μ, σ)", x_normal, (μ1, σ1), -np.inf), + ("from Y, coordinates (μ, σ)", y_lognormal, (μ1, σ1), 0), + ("from X, coordinates (μ/σ², -1/(2σ²))", x_natural, θ1, -np.inf)) +print("\nFisher information matrix of the first model") +for label, logpdf, v, a in cases: + I_v = np.round(fisher_matrix(logpdf, v, a, np.inf), 4) + 0.0 + print(f" {label}:\n{I_v}") +``` -$$ -H(p^*) - H(p) = \sum_x p(x) \log p(x) - \sum_x p(x) \log p^*(x) = D_{KL}(p \| p^*) \geq 0 , -$$ (ef_entropy_gap) +The four Euclidean distances differ. -with equality only if $p = p^*$. +The KL divergence computed from $X$ equals the KL divergence computed from $Y$. -Among all distributions that satisfy the moment conditions, the member of the exponential family has the largest entropy, and the entropy shortfall of any other distribution equals its KL divergence from that member. +The differential entropy of $Y$ exceeds that of $X$ by $E \log \lvert f'(X) \rvert = E X = 1$. -The sequel {doc}`information_projections` shows that {eq}`ef_entropy_gap` is an instance of a Pythagorean theorem. +The Fisher information matrices computed from $X$ and from $Y$ in coordinates $(\mu, \sigma)$ agree with {eq}`ef_fisher_normal`. -For Jaynes's die, $t(x) = x$ and $\theta$ is a scalar. +In the coordinates $(\mu / \sigma^2, -1 / (2 \sigma^2))$, the Fisher information matrix is a different matrix, $J^\top I J$. -The function `tilt` below computes the **exponential tilt** of a **base distribution** $q$: the distribution proportional to $q(x) \exp(\theta \, t(x))$ for a statistic $t$. +(ef_wasserstein_section)= +### Moving mass and comparing heights -For the maximum entropy problem, $q$ is uniform, and the result is {eq}`ef_maxent_solution`. +Optimal transport measures the distance between two models in another way. -The second function finds the $\theta$ that delivers a given mean. +The **2-Wasserstein distance** between distributions $p$ and $q$ on the real line is -```{code-cell} ipython3 -def tilt(q, t, θ): - """The distribution proportional to q(x) exp(θ t(x)).""" - log_w = np.log(q) + θ * t - return np.exp(log_w - logsumexp(log_w)) +$$ +W_2(p, q) = \left( \min E\left[ (X - Y)^2 \right] \right)^{1/2} , +$$ (ef_wasserstein) +where the minimum is over joint distributions of $(X, Y)$ whose marginal distributions are $p$ and $q$. -def match_mean(q, t, c): - """Find θ such that the tilted distribution has mean c.""" - θ = brentq(lambda θ: tilt(q, t, θ) @ t - c, -50, 50) - return θ, tilt(q, t, θ) +{doc}`opt_transport` solves discrete versions of this problem. +On the real line, the minimum is attained by pairing quantiles: $X = F_p^{-1}(U)$ and $Y = F_q^{-1}(U)$, where $F_p$ and $F_q$ are the two cumulative distribution functions and $U$ is uniform on $(0, 1)$. -def entropy(p): - return -p @ np.log(p) +For two normal models, this pairing is $Y = \mu_2 + (\sigma_2 / \sigma_1)(X - \mu_1)$, and +$$ +W_2\left(N(\mu_1, \sigma_1^2), N(\mu_2, \sigma_2^2)\right) = \sqrt{(\mu_1 - \mu_2)^2 + (\sigma_1 - \sigma_2)^2} , +$$ -def kl(p, q): - return p @ np.log(p / q) +the Euclidean distance between the parameter vectors $(\mu_1, \sigma_1)$ and $(\mu_2, \sigma_2)$. +So $W_2(A, B) = W_2(C, D) = 1$: optimal transport moves the mass of $A$ to $B$, and the mass of $C$ to $D$, by one unit, although $A$ and $B$ are much easier to tell apart than $C$ and $D$. -faces = np.arange(1, 7) -uniform_die = np.full(6, 1 / 6) -θ_die, p_die = match_mean(uniform_die, faces, 4.5) -print(f"θ = {θ_die:.4f}") -print("maximum entropy distribution:", np.round(p_die, 4)) -print(f"entropy = {entropy(p_die):.4f}, compared with log 6 = {np.log(6):.4f}") -``` +The two kinds of distance answer different questions. -The probabilities rise geometrically, by the factor $e^{\theta}$ from one face to the next. +KL divergence and Fisher information compare the heights of two densities outcome by outcome and use no distance between outcomes; the Wasserstein distance measures how far probability mass must move along the real line. -Let's check {eq}`ef_entropy_gap` by drawing other distributions with mean $4.5$. +{cite:t}`KhanZhang2022` call the first comparison vertical and the second horizontal. -We construct them by moving away from $p^*$ in directions that preserve both the total probability and the mean. +The Wasserstein distance is a distance between models, so relabeling parameters does not change it; of the parameterizations in this lecture, it equals the Euclidean distance between parameter vectors only in $(\mu, \sigma)$. -```{code-cell} ipython3 -rng = np.random.default_rng(0) +Because it measures displacements in the units of the data, transforming the data changes it. -# directions orthogonal to (1, ..., 1) and to (1, 2, ..., 6) -constraints = np.vstack([np.ones(6), faces]) -null_space = np.linalg.svd(constraints)[2][2:].T +It is also finite for models that put their probability on different sets: the Wasserstein distance between $A$ and a point mass at zero is $0.2$, while the KL divergence between them is infinite in either order. -print(" H(p*) - H(p) KL(p || p*)") -for _ in range(5): - while True: - p = p_die + null_space @ rng.normal(scale=0.05, size=4) - if np.all(p > 0): - break - print(f"{entropy(p_die) - entropy(p):12.6f} {kl(p, p_die):14.6f}") -``` +The function below computes {eq}`ef_wasserstein` for two distributions that are increasing functions of one standard normal random variable $Z$, so that pairing the values of $Z$ pairs quantiles. -The figure shows the maximum entropy distributions for several means. +We compute it for the four normal models and for the lognormal models that the transformation $y = e^x$ produces. ```{code-cell} ipython3 ---- -mystnb: - figure: - caption: Maximum entropy die distributions by mean - name: fig-ef-die ---- -fig, ax = plt.subplots() -for c in (2.5, 3.5, 4.5, 5.5): - θ, p = match_mean(uniform_die, faces, c) - ax.plot(faces, p, "o-", label=rf"mean {c}, $\theta$ = {θ:.2f}") -ax.set_xlabel("face") -ax.set_ylabel("probability") -ax.legend() -plt.show() +def w2_increasing(g1, g2): + """W2 between the distributions of g1(Z) and g2(Z), where Z is standard + normal and g1 and g2 are increasing; |Z| > 12 has negligible probability.""" + integrand = lambda z: (g1(z) - g2(z))**2 * norm.pdf(z) + return np.sqrt(integrate.quad(integrand, -12, 12, limit=200)[0]) + + +four_normals = {"A, B": ((0.0, 0.2), (1.0, 0.2)), "C, D": ((0.0, 2.0), (1.0, 2.0))} +for name, ((μa, σa), (μb, σb)) in four_normals.items(): + w_x = w2_increasing(lambda z: μa + σa * z, lambda z: μb + σb * z) + w_y = w2_increasing(lambda z: np.exp(μa + σa * z), + lambda z: np.exp(μb + σb * z)) + kl_x = kl_quad(x_normal, (μa, σa), (μb, σb), -np.inf, np.inf) + kl_y = kl_quad(y_lognormal, (μa, σa), (μb, σb), 0, np.inf) + print(f"{name}: W2 from X {w_x:.4f}, from Y = exp(X) {w_y:.4f}; " + f"KL from X {kl_x:.4f}, from Y {kl_y:.4f}") ``` -### The normal distribution +After the transformation, the Wasserstein distance is $1.79$ between $A$ and $B$ and $93.8$ between $C$ and $D$, because exponentiation stretches the upper tail, where $C$ and $D$ put much more probability than $A$ and $B$. -Now let the outcome $x$ be a real number, and constrain its mean and its second moment: +The KL divergences do not change. -$$ -E[X] = \mu, \qquad E[X^2] = \mu^2 + \sigma^2 . -$$ +{ref}`ef_fisher_rao` compares the shortest paths that the two kinds of distance select. -For a density $p$ on the real line, the **differential entropy** is $H(p) = -\int p(x) \log p(x) \, dx$. +### Statistics and sufficiency -The argument that led to {eq}`ef_maxent_solution` now says that the density with the largest entropy has the form +A statistic or a garbling can only lose information. + +Let $X$ be the data, a single observation or a whole sample, and let $p^s(\cdot\,; \theta)$ be the distribution of a statistic $s(X)$ when $X$ has distribution $p(\cdot\,; \theta)$. + +For any two parameter vectors $\theta_1$ and $\theta_2$, $$ -p(x; \theta) = \exp\left( \theta_1 x + \theta_2 x^2 - F(\theta) \right) , -$$ +D_{KL}\left(p^s(\cdot\,; \theta_1) \| p^s(\cdot\,; \theta_2)\right) \leq D_{KL}\left(p(\cdot\,; \theta_1) \| p(\cdot\,; \theta_2)\right) , +$$ (ef_dpi) -which is integrable only if $\theta_2 < 0$. +and the Fisher information matrix of $s(X)$ falls short of the Fisher information matrix of $X$ by a positive semidefinite matrix. -Completing the square shows that this is the normal density with $\theta_1 = \mu / \sigma^2$ and $\theta_2 = -1/(2\sigma^2)$. +Inequality {eq}`ef_dpi` is the data processing inequality of {doc}`blackwell_kihlstrom`. -The argument that delivered {eq}`ef_entropy_gap` goes through with sums replaced by integrals, so that every density $p$ with mean $\mu$ and variance $\sigma^2$ satisfies +{cite:t}`kullback1951information` showed that equality holds in {eq}`ef_dpi` for every pair of parameter vectors if and only if $s$ is sufficient. + +When the parameter space is connected, the Fisher information matrix of $s(X)$ equals that of $X$ for every $\theta$ if and only if $s$ is sufficient. + +{cite:t}`chentsov1981` characterized the Fisher information by this invariance. + +On the set of probability distributions over a finite set, the Fisher information metric is, up to a constant factor, the only Riemannian metric that does not change under the transformations that sufficient statistics induce. + +{doc}`blackwell_kihlstrom` states Chentsov's theorem. + +## The exponential family + +### Definition + +A family of models is an **exponential family** if its densities (or probability mass functions) can be written as $$ -H(\varphi) - H(p) = D_{KL}(p \| \varphi) \geq 0 , -$$ (ef_normal_gap) +p(x; \theta) = h(x) \exp\left( \theta \cdot t(x) - F(\theta) \right), +\qquad +F(\theta) = \log \int h(x) \exp\left( \theta \cdot t(x) \right) dx , +$$ (ef_family) -where $\varphi$ is the $N(\mu, \sigma^2)$ density. +with the integral replaced by a sum when $x$ is discrete, and where -*Among all densities on the real line with a given mean and variance, the normal density has the largest entropy.* +* $t(x) \in \mathbb{R}^d$ is the **sufficient statistic**, +* $\theta \in \mathbb{R}^d$ is the **natural parameter**, +* $h(x) \geq 0$ is the **base measure**, and +* $F(\theta)$ is the **log-partition function**, also called the cumulant function. -Its entropy is $H(\varphi) = \frac{1}{2} \log(2 \pi e \sigma^2)$. +The name comes from statistical mechanics, where $e^{F(\theta)}$ is the partition function of a Boltzmann–Gibbs distribution. -Unlike the entropy of a discrete distribution, differential entropy can be negative, and it changes when we change the units in which $x$ is measured; the gap {eq}`ef_normal_gap` is a KL divergence and does neither. +The natural parameters range over the set $\Theta$ of $\theta$ for which the integral defining $F$ is finite. -We check {eq}`ef_normal_gap` for several densities with mean zero and variance one. +In the maximum entropy problems of {ref}`ef_maxent`, $h$ is constant; the function `tilt` defined there uses a base distribution $q$ as $h$. -We compute the entropies with SciPy's formulas and the KL divergences by numerical integration. +A nonconstant $h$ arises when we maximize entropy relative to a base distribution that is not uniform, a problem that {doc}`information_projections` takes up. -```{code-cell} ipython3 -φ = norm(0, 1) -alternatives = { - "uniform": uniform(-np.sqrt(3), 2 * np.sqrt(3)), - "Laplace": laplace(0, 1 / np.sqrt(2)), - "logistic": logistic(0, np.sqrt(3) / np.pi), -} +We assume that the representation is **minimal**: no nontrivial linear combination $a \cdot t(x)$ is constant on the set where $h(x) > 0$. -print(f"entropy of N(0, 1): {φ.entropy():.4f}\n") -print(f"{'distribution':12} {'variance':>8} {'entropy':>8} " - f"{'H(φ) - H(p)':>12} {'KL(p || φ)':>11}") -for name, dist in alternatives.items(): - a, b = dist.support() - a, b = max(a, -30), min(b, 30) - kl_p_φ = integrate.quad( - lambda x: dist.pdf(x) * (dist.logpdf(x) - φ.logpdf(x)), a, b, - limit=200)[0] - print(f"{name:12} {dist.var():8.4f} {dist.entropy():8.4f} " - f"{φ.entropy() - dist.entropy():12.4f} {kl_p_φ:11.4f}") -``` +Then different $\theta$'s give different models. -We can also watch the normal distribution emerge from a discrete maximum entropy problem. +We also assume that $\Theta$ is an open set, as it is for every family in this lecture. -Put the outcome on a fine grid of points and impose the two moment conditions. +A minimal representation is unique up to an affine change of coordinates. -The function below finds the natural parameters by Newton's method, using two facts that we prove below: the gradient of $F$ is the vector of means of $t$, and the Hessian of $F$ is the covariance matrix of $t$. +If $A$ is an invertible $d \times d$ matrix, the sufficient statistic $A t(x)$ and the natural parameter $A^{-\top} \theta$ describe the same models, because $(A^{-\top} \theta) \cdot (A t(x)) = \theta \cdot t(x)$. -```{code-cell} ipython3 -def maxent(q, T, c, tol=1e-12, max_iter=100): - """ - Maximize entropy relative to q subject to E[T] = c. +If $b \in \mathbb{R}^d$, the natural parameter $\theta + b$ and the base measure $h(x) e^{-b \cdot t(x)}$ also describe the same models. - T is an m × d array whose rows are t(x). Returns θ and the - distribution proportional to q(x) exp(θ · t(x)). The iterations - converge only if c is in the interior of the convex hull of the - rows of T. - """ - def tilted(θ): - log_w = np.log(q) + T @ θ - return np.exp(log_w - logsumexp(log_w)) +Here are some familiar families written this way. - θ = np.zeros(T.shape[1]) - for _ in range(max_iter): - p = tilted(θ) - mean = p @ T - cov = (T - mean).T @ ((T - mean) * p[:, None]) - step = np.linalg.solve(cov, c - mean) - θ = θ + step - if np.max(np.abs(step)) < tol: - break - else: - raise RuntimeError("no convergence: is c inside the hull of t(x)?") - return θ, tilted(θ) - - -μ_grid, σ_grid = 1.0, 1.2 -grid = np.linspace(-6, 6, 241) -spacing = grid[1] - grid[0] -T_grid = np.column_stack([grid, grid**2]) -θ_grid, p_grid = maxent(np.full(grid.size, 1 / grid.size), T_grid, - c=np.array([μ_grid, μ_grid**2 + σ_grid**2])) -print(f"θ = {np.round(θ_grid, 4)}") -print(f"(μ/σ², -1/(2σ²)) = " - f"{np.round([μ_grid / σ_grid**2, -1 / (2 * σ_grid**2)], 4)}") -``` +| family | $t(x)$ | $\theta$ | $F(\theta)$ | +|---|---|---|---| +| Bernoulli($\pi$) | $x$ | $\log \frac{\pi}{1 - \pi}$ | $\log(1 + e^{\theta})$ | +| Poisson($\lambda$) | $x$ | $\log \lambda$ | $e^{\theta}$ | +| exponential($\lambda$) | $x$ | $-\lambda$ | $-\log(-\theta)$ | +| $N(\mu, \sigma^2)$ | $(x, x^2)$ | $\left(\frac{\mu}{\sigma^2}, -\frac{1}{2\sigma^2}\right)$ | $-\frac{\theta_1^2}{4 \theta_2} + \frac{1}{2}\log\left(-\frac{\pi}{\theta_2}\right)$ | +| Beta($a$, $b$) | $(\log x, \log(1 - x))$ | $(a - 1, b - 1)$ | $\log B(\theta_1 + 1, \theta_2 + 1)$ | +| categorical($\pi$) | $(1_{x = 1}, \ldots, 1_{x = K - 1})$ | $\left(\log \frac{\pi_k}{\pi_K}\right)_{k < K}$ | $\log\left(1 + \sum_{k < K} e^{\theta_k}\right)$ | -```{code-cell} ipython3 ---- -mystnb: - figure: - caption: Grid maximum entropy matches the normal - name: fig-ef-grid-normal ---- -fig, ax = plt.subplots() -ax.plot(grid, p_grid / spacing, lw=4, alpha=0.4, - label="maximum entropy on a grid") -ax.plot(grid, norm.pdf(grid, μ_grid, σ_grid), "k--", lw=1, - label=f"N({μ_grid:g}, {σ_grid:g}²)") -ax.set_xlabel("$x$") -ax.legend(loc="upper right") -plt.show() -``` +In every row $h(x) = 1$, except the Poisson row, where $h(x) = 1/x!$. -### Other moment conditions +In the Bernoulli and categorical rows $\pi$ is a probability or a vector of probabilities; in the normal row it is $3.14159\ldots$. -Different moment conditions produce different families. +In the Beta row, $B$ is the beta function. -| outcomes | constrained means | maximum entropy distribution | -|---|---|---| -| $\{1, \ldots, m\}$ | none | uniform | -| $\{0, 1, 2, \ldots\}$ | $E[X]$ | geometric | -| $[a, b]$ | none | uniform | -| $[0, \infty)$ | $E[X]$ | exponential | -| $(0, \infty)$ | $E[X]$, $E[\log X]$ | gamma | -| $(0, \infty)$ | $E[\log X]$, $E[(\log X)^2]$ | lognormal | -| $(0, 1)$ | $E[\log X]$, $E[\log(1 - X)]$ | Beta | -| $\mathbb{R}$ | $E[\lvert X \rvert]$ | Laplace | -| $\mathbb{R}$ | $E[X]$, $E[X^2]$ | normal | -| $\mathbb{R}^m$ | $E[X]$, $E[X X^\top]$ | multivariate normal | +The categorical family on $\{1, \ldots, K\}$ uses only $K - 1$ indicators, because all $K$ indicators sum to one; with all $K$, the representation would not be minimal. -The last row implies that, among all densities on $\mathbb{R}^m$ with a given mean vector and covariance matrix $\Sigma$, the multivariate normal density has the largest entropy, $\frac{1}{2} \log \det(2 \pi e \Sigma)$. +The multivariate normal family $N(\mu, \Sigma)$ is an exponential family with $t(x) = (x, x x^\top)$ and natural parameters $(\Sigma^{-1}\mu, -\frac{1}{2}\Sigma^{-1})$, where the pairing is $\theta \cdot t(x) = \theta_1 \cdot x + x^\top \Theta_2 x$ with $\Theta_2$ a symmetric matrix. -The lognormal row is the normal row applied to $\log X$: a density on $(0, \infty)$ proportional to $\exp(\theta_1 \log x + \theta_2 (\log x)^2)$ is a lognormal density. +Because $x_i x_j = x_j x_i$, a minimal representation keeps only the entries of $x x^\top$ on and above the diagonal. -{ref}`ef_ex_gamma` asks you to work out the gamma case. +A family of the form {eq}`ef_family` contains every normalized geometric mixture of two of its models: the distribution proportional to $p(x; \theta_0)^{1 - a} p(x; \theta_1)^a$ has natural parameter $(1 - a)\theta_0 + a \theta_1$, for every $a \in [0, 1]$ and for any other $a$ for which that parameter lies in $\Theta$. -## The exponential family +The sequel {doc}`information_projections` builds a geometry on this fact. -### Definition +### Sufficient statistics of fixed dimension -A family of densities (or probability mass functions) is an **exponential family** if it can be written as +For a model in an exponential family, the joint density of an IID sample of size $n$ is $$ -p(x; \theta) = h(x) \exp\left( \theta \cdot t(x) - F(\theta) \right), +\prod_{i=1}^n p(x_i; \theta) = \exp\left( n \left[ \theta \cdot \bar t - F(\theta) \right] \right) \prod_{i=1}^n h(x_i), \qquad -F(\theta) = \log \int h(x) \exp\left( \theta \cdot t(x) \right) dx , -$$ (ef_family) +\bar t = \frac{1}{n} \sum_{i=1}^n t(x_i) . +$$ -with the integral replaced by a sum when $x$ is discrete, and where +By the factorization theorem {eq}`ef_factorization`, the average $\bar t$ is sufficient for $\theta$. -* $t(x) \in \mathbb{R}^d$ is the **sufficient statistic**, -* $\theta \in \mathbb{R}^d$ is the **natural parameter**, -* $h(x) \geq 0$ is the **base measure**, and -* $F(\theta)$ is the **log-partition function**, also called the cumulant function. +Its dimension is $d$, whatever the sample size $n$. -The natural parameters range over the set $\Theta$ of $\theta$ for which the integral defining $F$ is finite. +For the normal family, $\bar t$ is the pair of sample moments $\left(\frac{1}{n} \sum_i x_i, \frac{1}{n} \sum_i x_i^2\right)$. -In the maximum entropy problem above, $h$ is constant; in the function `tilt`, the base distribution $q$ is the base measure $h$. +For the Bernoulli family, $\bar t$ is the fraction of successes. -A nonconstant $h$ arises when we maximize entropy relative to a base distribution that is not uniform, a problem that {doc}`information_projections` takes up. +For the Poisson family, $\bar t$ is the sample mean. -We assume that the representation is **minimal**: no nontrivial linear combination $a \cdot t(x)$ is constant on the set where $h(x) > 0$. +{cite:t}`Darmois1935`, {cite:t}`Koopman1936`, and {cite:t}`Pitman1936` proved a converse. -Then different $\theta$'s give different distributions. +Suppose that the models in a family have densities on the real line, that the set of outcomes $x$ with $p(x; \theta) > 0$ does not depend on $\theta$, and that for every sample size $n$ an IID sample has a sufficient statistic whose dimension does not grow with $n$. -We also assume that $\Theta$ is an open set, as it is for every family in this lecture. +Then, under smoothness conditions, the family is an exponential family.[^pkd] -Here are some familiar families written this way. +[^pkd]: The smoothness conditions rule out statistics that pack many numbers into one, such as a statistic that interleaves the decimal digits of $x_1, \ldots, x_n$. For a single observation, $x$ itself is a sufficient statistic of finite dimension; the theorem concerns how the dimension of a sufficient statistic behaves as $n$ grows. -| family | $t(x)$ | $\theta$ | $F(\theta)$ | -|---|---|---|---| -| Bernoulli($\pi$) | $x$ | $\log \frac{\pi}{1 - \pi}$ | $\log(1 + e^{\theta})$ | -| Poisson($\lambda$) | $x$ | $\log \lambda$ | $e^{\theta}$ | -| exponential($\lambda$) | $x$ | $-\lambda$ | $-\log(-\theta)$ | -| $N(\mu, \sigma^2)$ | $(x, x^2)$ | $\left(\frac{\mu}{\sigma^2}, -\frac{1}{2\sigma^2}\right)$ | $-\frac{\theta_1^2}{4 \theta_2} + \frac{1}{2}\log\left(-\frac{\pi}{\theta_2}\right)$ | -| Beta($a$, $b$) | $(\log x, \log(1 - x))$ | $(a - 1, b - 1)$ | $\log B(\theta_1 + 1, \theta_2 + 1)$ | -| categorical($\pi$) | $(1_{x = 1}, \ldots, 1_{x = K - 1})$ | $\left(\log \frac{\pi_k}{\pi_K}\right)_{k < K}$ | $\log\left(1 + \sum_{k < K} e^{\theta_k}\right)$ | +Two families show why the conditions matter. -In every row $h(x) = 1$, except the Poisson row, where $h(x) = 1/x!$. +The uniform family on $(0, \theta)$ has the one-dimensional sufficient statistic $\max_i x_i$ for every $n$, and it is not an exponential family: its set of possible outcomes $(0, \theta)$ depends on $\theta$. -In the Bernoulli and categorical rows $\pi$ is a probability or a vector of probabilities; in the normal row it is $3.14159\ldots$. +The Cauchy location family satisfies the condition on outcomes, and no statistic of fixed dimension is sufficient for it: its smallest sufficient statistic is the set of order statistics, whose dimension grows with $n$. -In the Beta row, $B$ is the beta function. +We draw a sample $\mathbf x$ of size $n = 8$ from $N(1, 1.5^2)$ and multiply it by an orthogonal matrix $Q$ that maps the vector $\mathbf 1 = (1, \ldots, 1)$ into itself. -The categorical family on $\{1, \ldots, K\}$ uses only $K - 1$ indicators, because all $K$ indicators sum to one; with all $K$, the representation would not be minimal. +The rotated sample $Q \mathbf x$ has the same sum, $\mathbf 1^\top Q \mathbf x = \mathbf 1^\top \mathbf x$, and the same sum of squares, $\mathbf x^\top Q^\top Q \mathbf x = \mathbf x^\top \mathbf x$, so it has the same sufficient statistic for the normal family. -The multivariate normal $N(\mu, \Sigma)$ is an exponential family with $t(x) = (x, x x^\top)$ and natural parameters $(\Sigma^{-1}\mu, -\frac{1}{2}\Sigma^{-1})$, where the pairing is $\theta \cdot t(x) = \theta_1 \cdot x + x^\top \Theta_2 x$ with $\Theta_2$ a symmetric matrix. +```{code-cell} ipython3 +rng_rotate = np.random.default_rng(1) +n = 8 +x_sample = rng_rotate.normal(1.0, 1.5, n) -Because $x_i x_j = x_j x_i$, a minimal representation keeps only the entries of $x x^\top$ on and above the diagonal. +# Q is orthogonal and maps (1, ..., 1) into itself +ones = np.ones(n) +basis = np.linalg.svd(ones[None, :])[2][1:].T # orthonormal basis of 1's complement +rotation = np.linalg.qr(rng_rotate.normal(size=(n - 1, n - 1)))[0] +Q = np.outer(ones, ones) / n + basis @ rotation @ basis.T +x_rotated = Q @ x_sample -A family of the form {eq}`ef_family` contains every normalized geometric mixture of two of its members: the distribution proportional to $p(x; \theta_0)^{1 - a} p(x; \theta_1)^a$ has natural parameter $(1 - a)\theta_0 + a \theta_1$, for every $a \in [0, 1]$ and for any other $a$ for which that parameter lies in $\Theta$. +print("sample: ", np.round(x_sample, 3)) +print("rotated sample:", np.round(x_rotated, 3)) +print(f"sums: {x_sample.sum():.6f} {x_rotated.sum():.6f}") +print(f"sums of squares: {x_sample @ x_sample:.6f} {x_rotated @ x_rotated:.6f}") -The sequel {doc}`information_projections` builds a geometry on this fact. +μ_vals, σ_vals = np.meshgrid(np.linspace(-2, 4, 61), np.linspace(0.3, 4, 38)) -The log-partition function determines everything else. + +def log_likelihood(dist, sample, μ, σ): + return sum(dist(μ, σ).logpdf(xi) for xi in sample) + + +for name, dist in (("normal", norm), ("Cauchy", cauchy)): + gap = np.max(np.abs(log_likelihood(dist, x_sample, μ_vals, σ_vals) + - log_likelihood(dist, x_rotated, μ_vals, σ_vals))) + print(f"{name:6} family: largest gap between the two log likelihood " + f"functions = {gap:.2e}") +``` + +The figure shows the two log likelihood functions of the location parameter $\mu$, with the scale parameter fixed at $1.5$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Log likelihoods before and after rotation + name: fig-ef-rotated-sample +--- +μ_line = np.linspace(-2, 4, 400) +fig, axes = plt.subplots(1, 2, figsize=(10, 3.5)) +for ax, (name, dist) in zip(axes, (("normal", norm), ("Cauchy", cauchy))): + for sample, label, ls in ((x_sample, "sample", "-"), + (x_rotated, "rotated sample", "--")): + ax.plot(μ_line, log_likelihood(dist, sample, μ_line, 1.5), ls, lw=2, + label=label) + ax.set_title(f"{name} family") + ax.set_xlabel(r"$\mu$") + ax.legend() +axes[0].set_ylabel("log likelihood") +plt.tight_layout() +plt.show() +``` + +The normal family cannot distinguish the two samples; the Cauchy family can. ### The log-partition function generates moments +The log-partition function determines everything else. + Differentiate $F(\theta) = \log \int h(x) \exp(\theta \cdot t(x)) \, dx$: $$ @@ -564,11 +734,13 @@ This map is one-to-one because $F$ is strictly convex. For the families in this lecture, its range is the interior of the convex hull of the values that $t(X)$ can take: a Bernoulli mean lies strictly between $0$ and $1$, a Poisson mean is positive, and so on. -We can label each member of the family either by its natural parameter $\theta$ or by its **expectation parameter** $\eta$. +We can label each model in the family either by its natural parameter $\theta$ or by its **expectation parameter** $\eta$. For the normal family, $\eta = (\mu, \mu^2 + \sigma^2)$; for the Poisson family, $\eta = \lambda$; for the Bernoulli family, $\eta = \pi$. -The maximum entropy problem fixes the expectation parameters $\eta = c$; its solution delivers the natural parameters $\theta$. +An exponential family carries three coordinate systems: conventional parameters, such as $(\mu, \sigma)$ for the normal family; natural parameters $\theta$; and expectation parameters $\eta$. + +The maximum entropy problems of {ref}`ef_maxent` fix the expectation parameters $\eta = c$; their solutions deliver the natural parameters $\theta$. ### Legendre duality @@ -601,6 +773,7 @@ $$ F(\theta) = \max_\eta \left\{ \theta \cdot \eta - F^*(\eta) \right\} . $$ +```{note} Economists use the same duality between a profit function and a production function. In {doc}`houthakker_aggregation`, the industry profit function is $\Pi(p) = \max_X \{ f(X) - p \cdot X \}$, where $X$ is a vector of inputs, $p$ is the vector of their prices, and $f$ is the aggregate production function (which that lecture calls $F$). @@ -615,6 +788,7 @@ The dictionary is * conjugate $F^*$ $\leftrightarrow$ minus the production function $-f$. Hotelling's lemma, $\partial \Pi / \partial p_i = -X_i$, is the counterpart of $\nabla F(\theta) = \eta$, and recovering the production function from the profit function is the counterpart of recovering $F^*$ from $F$. +``` ### The conjugate is negative entropy @@ -640,62 +814,369 @@ In general, $H(p(\cdot; \theta)) = -F^*(\eta) - E_\theta \log h(X)$. For the Bernoulli family, $h = 1$, $F(\theta) = \log(1 + e^\theta)$, and $F^*(\eta) = \eta \log \eta + (1 - \eta) \log (1 - \eta)$. -In the left panel of the figure below, the tangent line to $F$ with slope $\eta$ meets the vertical axis at $-F^*(\eta)$. +In the left panel of the figure below, the tangent line to $F$ with slope $\eta$ meets the vertical axis at $-F^*(\eta)$. + +In the right panel, the tangent line to $F^*$ at $\eta$ has slope $\theta$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Bernoulli log-partition function and its conjugate + name: fig-ef-legendre +--- +def F_bern(θ): + return np.log1p(np.exp(θ)) + + +def F_star_bern(η): + return η * np.log(η) + (1 - η) * np.log(1 - η) + + +θ0 = 2.0 +η0 = 1 / (1 + np.exp(-θ0)) + +θ_vals = np.linspace(-4, 4, 200) +η_vals = np.linspace(0.001, 0.999, 200) + +fig, axes = plt.subplots(1, 2, figsize=(10, 4)) +ax = axes[0] +ax.plot(θ_vals, F_bern(θ_vals), lw=2, label=r"$F(\theta)$") +ax.plot(θ_vals, -F_star_bern(η0) + η0 * θ_vals, "--", + label=rf"tangent line with slope $\eta$ = {η0:.2f}") +ax.plot([0], [-F_star_bern(η0)], "ko") +ax.annotate(r"$-F^*(\eta)$", (0, -F_star_bern(η0)), + xytext=(8, -14), textcoords="offset points") +ax.plot([θ0], [F_bern(θ0)], "o", color="C1") +ax.axvline(0, color="0.7", lw=0.8) +ax.set_xlabel(r"$\theta$") +ax.legend() + +ax = axes[1] +ax.plot(η_vals, F_star_bern(η_vals), lw=2, label=r"$F^*(\eta) = -H$") +ax.plot(η_vals, F_star_bern(η0) + θ0 * (η_vals - η0), "--", + label=rf"tangent line with slope $\theta$ = {θ0:.2f}") +ax.plot([η0], [F_star_bern(η0)], "o", color="C1") +ax.set_xlabel(r"$\eta$") +ax.legend() +plt.tight_layout() +plt.show() +``` + +(ef_maxent)= +## Maximum entropy + +### A die + +Edwin Jaynes proposed the maximum entropy principle {cite}`Jaynes1957` and illustrated it in his 1962 Brandeis lectures with the following problem, now known as the Brandeis dice problem {cite}`Jaynes1963`. + +A die has faces $x \in \{1, 2, \ldots, 6\}$. + +We are told only that the average number of spots is $4.5$, rather than the $3.5$ of a fair die. + +Which probability distribution $p = (p_1, \ldots, p_6)$ should we assign to the faces? + +Many distributions have mean $4.5$. + +Jaynes proposed choosing the one that is "maximally noncommittal with regard to missing information" {cite}`Jaynes1957`, which he took to mean the one that maximizes Shannon's entropy + +$$ +H(p) = - \sum_{x} p(x) \log p(x) +$$ + +subject to $\sum_x p(x) = 1$ and $\sum_x x \, p(x) = 4.5$. + +### The solution is a model in an exponential family + +Let's solve a more general version of this problem. + +Let $t(x) = (t_1(x), \ldots, t_d(x))$ be a vector of functions of the outcome $x$, which takes values in a finite set. + +We seek the distribution $p$ that maximizes $H(p)$ subject to the moment conditions + +$$ +\sum_x p(x) \, t(x) = c +$$ (ef_moments) + +for a given vector $c$, and $\sum_x p(x) = 1$. + +Attach a vector of Lagrange multipliers $\theta$ to {eq}`ef_moments`. + +The first-order condition for $p(x)$ is $-\log p(x) - 1 + \theta \cdot t(x) - \nu = 0$, where $\nu$ is the multiplier on $\sum_x p(x) = 1$. + +The solution has the form + +$$ +p(x; \theta) = \exp\left( \theta \cdot t(x) - F(\theta) \right), +\qquad +F(\theta) = \log \sum_x \exp\left( \theta \cdot t(x) \right) , +$$ (ef_maxent_solution) + +where $\theta$ satisfies {eq}`ef_moments`. + +The function $F$ makes the probabilities sum to one. + +Such a $\theta$ exists if and only if $c$ lies in the relative interior of the convex hull of the points $t(x)$, that is, in its interior as a subset of the smallest affine subspace that contains it; for the die below, if and only if $1 < c < 6$. + +When $c$ lies on the relative boundary, as for a die whose mean is $6$, a maximizing distribution still exists. + +It puts zero probability on some outcomes, and it lies outside the family, as a limit of models whose $\theta$ diverges. + +The models {eq}`ef_maxent_solution` form an exponential family with sufficient statistic $t$ and constant base measure. + +The Lagrange multipliers $\theta$ are natural parameters, and the constrained means $c$ are expectation parameters $\eta$. + +To confirm that {eq}`ef_maxent_solution` is a maximum, let $p$ be any distribution that satisfies {eq}`ef_moments`, and let $p^*$ be the model in the exponential family that satisfies it. + +Because $\log p^*(x) = \theta \cdot t(x) - F(\theta)$ is an affine function of $t(x)$, and $p$ and $p^*$ assign the same mean $c$ to $t$, + +$$ +\sum_x p(x) \log p^*(x) = \theta \cdot c - F(\theta) = \sum_x p^*(x) \log p^*(x) = - H(p^*) . +$$ + +Therefore + +$$ +H(p^*) - H(p) = \sum_x p(x) \log p(x) - \sum_x p(x) \log p^*(x) = D_{KL}(p \| p^*) \geq 0 , +$$ (ef_entropy_gap) + +with equality only if $p = p^*$. + +Among all distributions that satisfy the moment conditions, the model in the exponential family has the largest entropy, and the entropy shortfall of any other distribution equals its KL divergence from that model. + +The sequel {doc}`information_projections` shows that {eq}`ef_entropy_gap` is an instance of a Pythagorean theorem. + +For Jaynes's die, $t(x) = x$ and $\theta$ is a scalar. + +The function `tilt` below computes the **exponential tilt** of a **base distribution** $q$: the distribution proportional to $q(x) \exp(\theta \, t(x))$ for a statistic $t$. + +For the maximum entropy problem, $q$ is uniform, and the result is {eq}`ef_maxent_solution`. + +The second function finds the $\theta$ that delivers a given mean. + +```{code-cell} ipython3 +def tilt(q, t, θ): + """The distribution proportional to q(x) exp(θ t(x)).""" + log_w = np.log(q) + θ * t + return np.exp(log_w - logsumexp(log_w)) + + +def match_mean(q, t, c): + """Find θ such that the tilted distribution has mean c.""" + θ = brentq(lambda θ: tilt(q, t, θ) @ t - c, -50, 50) + return θ, tilt(q, t, θ) + + +def entropy(p): + return -p @ np.log(p) + + +def kl(p, q): + return p @ np.log(p / q) + + +faces = np.arange(1, 7) +uniform_die = np.full(6, 1 / 6) +θ_die, p_die = match_mean(uniform_die, faces, 4.5) +print(f"θ = {θ_die:.4f}") +print("maximum entropy distribution:", np.round(p_die, 4)) +print(f"entropy = {entropy(p_die):.4f}, compared with log 6 = {np.log(6):.4f}") +``` + +The probabilities rise geometrically, by the factor $e^{\theta}$ from one face to the next. + +Let's check {eq}`ef_entropy_gap` by drawing other distributions with mean $4.5$. + +We construct them by moving away from $p^*$ in directions that preserve both the total probability and the mean. + +```{code-cell} ipython3 +rng = np.random.default_rng(0) + +# directions orthogonal to (1, ..., 1) and to (1, 2, ..., 6) +constraints = np.vstack([np.ones(6), faces]) +null_space = np.linalg.svd(constraints)[2][2:].T + +print(" H(p*) - H(p) KL(p || p*)") +for _ in range(5): + while True: + p = p_die + null_space @ rng.normal(scale=0.05, size=4) + if np.all(p > 0): + break + print(f"{entropy(p_die) - entropy(p):12.6f} {kl(p, p_die):14.6f}") +``` + +The figure shows the maximum entropy distributions for several means. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Maximum entropy die distributions by mean + name: fig-ef-die +--- +fig, ax = plt.subplots() +for c in (2.5, 3.5, 4.5, 5.5): + θ, p = match_mean(uniform_die, faces, c) + ax.plot(faces, p, "o-", label=rf"mean {c}, $\theta$ = {θ:.2f}") +ax.set_xlabel("face") +ax.set_ylabel("probability") +ax.legend() +plt.show() +``` + +### Shadow prices + +*The Lagrange multipliers of the maximum entropy problem are the shadow prices of the moment constraints.* + +By {eq}`ef_negentropy`, the maximized entropy is $H(p^*) = -F^*(c)$, so by the envelope theorem $\partial H(p^*) / \partial c = -\nabla F^*(c) = -\theta$. + +The multiplier $\theta_j$ is the rate at which entropy falls as the constrained mean $c_j$ rises. + +For Jaynes's die, $\theta > 0$ at $c = 4.5$, because pushing the mean further from $3.5$ requires a less uniform distribution. + +### The normal distribution + +Now let the outcome $x$ be a real number, and constrain its mean and its second moment: + +$$ +E[X] = \mu, \qquad E[X^2] = \mu^2 + \sigma^2 . +$$ + +For a density $p$ on the real line, the **differential entropy** is $H(p) = -\int p(x) \log p(x) \, dx$. + +The argument that led to {eq}`ef_maxent_solution` now says that the density with the largest entropy has the form + +$$ +p(x; \theta) = \exp\left( \theta_1 x + \theta_2 x^2 - F(\theta) \right) , +$$ + +which is integrable only if $\theta_2 < 0$. + +Completing the square shows that this is the normal density with $\theta_1 = \mu / \sigma^2$ and $\theta_2 = -1/(2\sigma^2)$. + +The argument that delivered {eq}`ef_entropy_gap` goes through with sums replaced by integrals, so that every density $p$ with mean $\mu$ and variance $\sigma^2$ satisfies + +$$ +H(\varphi) - H(p) = D_{KL}(p \| \varphi) \geq 0 , +$$ (ef_normal_gap) + +where $\varphi$ is the $N(\mu, \sigma^2)$ density. + +*Among all densities on the real line with a given mean and variance, the normal density has the largest entropy.* + +Its entropy is $H(\varphi) = \frac{1}{2} \log(2 \pi e \sigma^2)$. + +Unlike the entropy of a discrete distribution, differential entropy can be negative, and it changes when we change the units in which $x$ is measured, as the table in {ref}`ef_invariants` records; the gap {eq}`ef_normal_gap` is a KL divergence and does neither. + +We check {eq}`ef_normal_gap` for several densities with mean zero and variance one. + +We compute the entropies with SciPy's formulas and the KL divergences by numerical integration. + +```{code-cell} ipython3 +φ = norm(0, 1) +alternatives = { + "uniform": uniform(-np.sqrt(3), 2 * np.sqrt(3)), + "Laplace": laplace(0, 1 / np.sqrt(2)), + "logistic": logistic(0, np.sqrt(3) / np.pi), +} + +print(f"entropy of N(0, 1): {φ.entropy():.4f}\n") +print(f"{'distribution':12} {'variance':>8} {'entropy':>8} " + f"{'H(φ) - H(p)':>12} {'KL(p || φ)':>11}") +for name, dist in alternatives.items(): + a, b = dist.support() + a, b = max(a, -30), min(b, 30) + kl_p_φ = integrate.quad( + lambda x: dist.pdf(x) * (dist.logpdf(x) - φ.logpdf(x)), a, b, + limit=200)[0] + print(f"{name:12} {dist.var():8.4f} {dist.entropy():8.4f} " + f"{φ.entropy() - dist.entropy():12.4f} {kl_p_φ:11.4f}") +``` + +We can also watch the normal distribution emerge from a discrete maximum entropy problem. + +Put the outcome on a fine grid of points and impose the two moment conditions. + +The function below finds the natural parameters by Newton's method, using {eq}`ef_gradient` and {eq}`ef_hessian`: the gradient of $F$ is the vector of means of $t$, and the Hessian of $F$ is the covariance matrix of $t$. + +```{code-cell} ipython3 +def maxent(q, T, c, tol=1e-12, max_iter=100): + """ + Maximize entropy relative to q subject to E[T] = c. + + T is an m × d array whose rows are t(x). Returns θ and the + distribution proportional to q(x) exp(θ · t(x)). The iterations + converge only if c is in the interior of the convex hull of the + rows of T. + """ + def tilted(θ): + log_w = np.log(q) + T @ θ + return np.exp(log_w - logsumexp(log_w)) + + θ = np.zeros(T.shape[1]) + for _ in range(max_iter): + p = tilted(θ) + mean = p @ T + cov = (T - mean).T @ ((T - mean) * p[:, None]) + step = np.linalg.solve(cov, c - mean) + θ = θ + step + if np.max(np.abs(step)) < tol: + break + else: + raise RuntimeError("no convergence: is c inside the hull of t(x)?") + return θ, tilted(θ) + -In the right panel, the tangent line to $F^*$ at $\eta$ has slope $\theta$. +μ_grid, σ_grid = 1.0, 1.2 +grid = np.linspace(-6, 6, 241) +spacing = grid[1] - grid[0] +T_grid = np.column_stack([grid, grid**2]) +θ_grid, p_grid = maxent(np.full(grid.size, 1 / grid.size), T_grid, + c=np.array([μ_grid, μ_grid**2 + σ_grid**2])) +print(f"θ = {np.round(θ_grid, 4)}") +print(f"(μ/σ², -1/(2σ²)) = " + f"{np.round([μ_grid / σ_grid**2, -1 / (2 * σ_grid**2)], 4)}") +``` ```{code-cell} ipython3 --- mystnb: figure: - caption: Bernoulli log-partition function and its conjugate - name: fig-ef-legendre + caption: Grid maximum entropy matches the normal + name: fig-ef-grid-normal --- -def F_bern(θ): - return np.log1p(np.exp(θ)) - - -def F_star_bern(η): - return η * np.log(η) + (1 - η) * np.log(1 - η) - - -θ0 = 2.0 -η0 = 1 / (1 + np.exp(-θ0)) - -θ_vals = np.linspace(-4, 4, 200) -η_vals = np.linspace(0.001, 0.999, 200) - -fig, axes = plt.subplots(1, 2, figsize=(10, 4)) -ax = axes[0] -ax.plot(θ_vals, F_bern(θ_vals), lw=2, label=r"$F(\theta)$") -ax.plot(θ_vals, -F_star_bern(η0) + η0 * θ_vals, "--", - label=rf"tangent line with slope $\eta$ = {η0:.2f}") -ax.plot([0], [-F_star_bern(η0)], "ko") -ax.annotate(r"$-F^*(\eta)$", (0, -F_star_bern(η0)), - xytext=(8, -14), textcoords="offset points") -ax.plot([θ0], [F_bern(θ0)], "o", color="C1") -ax.axvline(0, color="0.7", lw=0.8) -ax.set_xlabel(r"$\theta$") -ax.legend() - -ax = axes[1] -ax.plot(η_vals, F_star_bern(η_vals), lw=2, label=r"$F^*(\eta) = -H$") -ax.plot(η_vals, F_star_bern(η0) + θ0 * (η_vals - η0), "--", - label=rf"tangent line with slope $\theta$ = {θ0:.2f}") -ax.plot([η0], [F_star_bern(η0)], "o", color="C1") -ax.set_xlabel(r"$\eta$") -ax.legend() -plt.tight_layout() +fig, ax = plt.subplots() +ax.plot(grid, p_grid / spacing, lw=4, alpha=0.4, + label="maximum entropy on a grid") +ax.plot(grid, norm.pdf(grid, μ_grid, σ_grid), "k--", lw=1, + label=f"N({μ_grid:g}, {σ_grid:g}²)") +ax.set_xlabel("$x$") +ax.legend(loc="upper right") plt.show() ``` -*The Lagrange multipliers of the maximum entropy problem are the shadow prices of the moment constraints.* +### Other moment conditions -By {eq}`ef_negentropy`, the maximized entropy is $H(p^*) = -F^*(c)$, so by the envelope theorem $\partial H(p^*) / \partial c = -\nabla F^*(c) = -\theta$. +Different moment conditions produce different families. -The multiplier $\theta_j$ is the rate at which entropy falls as the constrained mean $c_j$ rises. +| outcomes | constrained means | maximum entropy distribution | +|---|---|---| +| $\{1, \ldots, m\}$ | none | uniform | +| $\{0, 1, 2, \ldots\}$ | $E[X]$ | geometric | +| $[a, b]$ | none | uniform | +| $[0, \infty)$ | $E[X]$ | exponential | +| $(0, \infty)$ | $E[X]$, $E[\log X]$ | gamma | +| $(0, \infty)$ | $E[\log X]$, $E[(\log X)^2]$ | lognormal | +| $(0, 1)$ | $E[\log X]$, $E[\log(1 - X)]$ | Beta | +| $\mathbb{R}$ | $E[\lvert X \rvert]$ | Laplace | +| $\mathbb{R}$ | $E[X]$, $E[X^2]$ | normal | +| $\mathbb{R}^m$ | $E[X]$, $E[X X^\top]$ | multivariate normal | -For Jaynes's die, $\theta > 0$ at $c = 4.5$, because pushing the mean further from $3.5$ requires a less uniform distribution. +The last row implies that, among all densities on $\mathbb{R}^m$ with a given mean vector and covariance matrix $\Sigma$, the multivariate normal density has the largest entropy, $\frac{1}{2} \log \det(2 \pi e \Sigma)$. + +The lognormal row is the normal row applied to $\log X$: a density on $(0, \infty)$ proportional to $\exp(\theta_1 \log x + \theta_2 (\log x)^2)$ is a lognormal density. + +{ref}`ef_ex_gamma` asks you to work out the gamma case. ### Logit choice probabilities @@ -807,7 +1288,7 @@ When $F(\theta) = \frac{1}{2} \lVert \theta \rVert^2$, it is half the squared Eu ### KL divergence is a Bregman divergence -Take two members of an exponential family, with natural parameters $\theta_1$ and $\theta_2$ and expectation parameters $\eta_1$ and $\eta_2$. +Take two models in an exponential family, with natural parameters $\theta_1$ and $\theta_2$ and expectation parameters $\eta_1$ and $\eta_2$. Since $\log p(x; \theta_1) - \log p(x; \theta_2) = (\theta_1 - \theta_2) \cdot t(x) - F(\theta_1) + F(\theta_2)$, taking expectations under $p(\cdot; \theta_1)$ gives @@ -831,6 +1312,8 @@ in which the arguments appear in the same order as in the KL divergence. KL divergence is a Bregman divergence in either coordinate system, generated by $F$ in natural parameters and by $F^*$ in expectation parameters. +The two formulas compute one invariant number in two coordinate systems. + Let's check {eq}`ef_kl_bregman` and {eq}`ef_kl_dual` for Poisson and normal distributions, computing the KL divergence directly by summation and integration. ```{code-cell} ipython3 @@ -890,11 +1373,11 @@ $$ D_{KL}\left( p_{\theta} \| p_{\theta + \delta} \right) \approx \frac{1}{2} \, \delta^\top \nabla^2 F(\theta) \, \delta . $$ -For the exponential family, $\nabla^2 F(\theta)$ is the **Fisher information matrix** $I(\theta) = \operatorname{Cov}_\theta[\nabla_\theta \log p(X; \theta)]$, because the score $\nabla_\theta \log p(X; \theta) = t(X) - \nabla F(\theta)$ has covariance matrix $\operatorname{Cov}_\theta[t(X)] = \nabla^2 F(\theta)$. +For the exponential family, $\nabla^2 F(\theta)$ is the Fisher information matrix {eq}`ef_fisher`, because the score $\nabla_\theta \log p(X; \theta) = t(X) - \nabla F(\theta)$ has covariance matrix $\operatorname{Cov}_\theta[t(X)] = \nabla^2 F(\theta)$. *The Fisher information matrix measures how fast nearby distributions become distinguishable.* -This explains the four normal distributions with which we began. +This explains the four normal models with which we began. With $\sigma$ fixed, the Fisher information for $\mu$ is $1/\sigma^2$, so a unit change in $\mu$ moves the distribution by $\frac{1}{2} \cdot 1^2 / \sigma^2$, which is $12.5$ when $\sigma = 0.2$ and $0.125$ when $\sigma = 2$. @@ -935,11 +1418,208 @@ plt.show() Near $\lambda_0$ the three curves coincide; farther away they separate. +(ef_fisher_rao)= +### The Fisher–Rao distance + +KL divergence is not symmetric, and it violates the triangle inequality. + +The Fisher information matrix defines a distance. + +Let $\theta(\tau)$, $0 \leq \tau \leq 1$, be a smooth path of models in a family. + +Its **length** is + +$$ +L = \int_0^1 \sqrt{\dot \theta(\tau)^\top I(\theta(\tau)) \, \dot \theta(\tau)} \, d\tau . +$$ (ef_path_length) + +The **Fisher–Rao distance** between two models is the length of the shortest path in the family that joins them {cite}`Rao1945`. + +The length {eq}`ef_path_length` does not depend on coordinates: under a reparameterization, $\dot \theta = J \dot \xi$ and the Fisher information matrix becomes $J^\top I J$, so the integrand does not change. + +Fisher information does not change under invertible transformations of the data or under sufficient statistics, so the Fisher–Rao distance does not change either. + +For nearby models, the Fisher–Rao distance is approximately $\sqrt{\delta^\top I(\theta) \delta} \approx \sqrt{2 D_{KL}(p_\theta \| p_{\theta + \delta})}$. + +For the normal family in coordinates $(\mu, \sigma)$, {eq}`ef_fisher_normal` gives the squared length element + +$$ +ds^2 = \frac{d\mu^2 + 2 \, d\sigma^2}{\sigma^2} . +$$ + +With $u = \mu / \sqrt{2}$, $ds^2 = 2 (du^2 + d\sigma^2) / \sigma^2$, twice the squared length element of the Poincaré half-plane, a model of hyperbolic geometry. + +In coordinates $(u, \sigma)$, the shortest paths are vertical lines and semicircles centered on the axis $\sigma = 0$. + +The Fisher–Rao distance between two normal models is {cite}`CostaSantosStrapasson2015` + +$$ +d_{FR}\left(N(\mu_1, \sigma_1^2), N(\mu_2, \sigma_2^2)\right) += \sqrt{2} \, \operatorname{arccosh}\left( 1 + \frac{(\mu_1 - \mu_2)^2 / 2 + (\sigma_1 - \sigma_2)^2}{2 \sigma_1 \sigma_2} \right) . +$$ (ef_fisher_rao_normal) + +We compute {eq}`ef_fisher_rao_normal` for the four normal models with which we began. + +```{code-cell} ipython3 +def fisher_rao_normal(μ1, σ1, μ2, σ2): + """Fisher–Rao distance (ef_fisher_rao_normal) between two normal models.""" + return np.sqrt(2) * np.arccosh( + 1 + ((μ1 - μ2)**2 / 2 + (σ1 - σ2)**2) / (2 * σ1 * σ2)) + + +def normal_geodesic(μ1, σ1, μ2, σ2, n_points=401): + """ + Points (μ, σ) on the shortest path between two normal models with + μ1 ≠ μ2: a semicircle in the (μ/√2, σ) half-plane. + """ + u1, u2 = μ1 / np.sqrt(2), μ2 / np.sqrt(2) + center = (u1**2 + σ1**2 - u2**2 - σ2**2) / (2 * (u1 - u2)) + radius = np.hypot(u1 - center, σ1) + angles = np.linspace(np.arctan2(σ1, u1 - center), + np.arctan2(σ2, u2 - center), n_points) + return np.sqrt(2) * (center + radius * np.cos(angles)), radius * np.sin(angles) + + +pairs = {"A, B": (0.0, 0.2, 1.0, 0.2), "C, D": (0.0, 2.0, 1.0, 2.0)} +for name, (μa, σa, μb, σb) in pairs.items(): + kl_ab = np.log(σb / σa) + (σa**2 + (μa - μb)**2) / (2 * σb**2) - 0.5 + μ_path, σ_path = normal_geodesic(μa, σa, μb, σb) + print(f"{name}: Fisher–Rao distance {fisher_rao_normal(μa, σa, μb, σb):.4f}, " + f"sqrt(2 KL) = {np.sqrt(2 * kl_ab):.4f}, " + f"midpoint of the shortest path N({μ_path[200]:.2f}, {σ_path[200]:.3f}²)") +``` + +The path from $A$ to $B$ that holds $\sigma = 0.2$ fixed has length $1 / 0.2 = 5$, which equals $\sqrt{2 D_{KL}(A \| B)}$. + +The shortest path has length $3.775$; it widens the distribution on the way, and at its midpoint it reaches $N(0.5, 0.406^2)$. + +For $C$ and $D$, the shortest path barely bends, and the Fisher–Rao distance $0.497$ is close to $\sqrt{2 D_{KL}(C \| D)} = 0.5$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Shortest paths between normal models + name: fig-ef-fisher-rao +--- +fig, axes = plt.subplots(1, 2, figsize=(10, 3.5)) +for ax, (name, (μa, σa, μb, σb)) in zip(axes, pairs.items()): + μ_path, σ_path = normal_geodesic(μa, σa, μb, σb) + ax.plot(μ_path, σ_path, lw=2, label="shortest path") + ax.plot([μa, μb], [σa, σb], "k--", lw=1, label=r"path with $\sigma$ fixed") + ax.plot([μa, μb], [σa, σb], "ko") + for μ, σ, label in ((μa, σa, name[0]), (μb, σb, name[-1])): + ax.annotate(label, (μ, σ), xytext=(4, -14), textcoords="offset points") + ax.set_xlabel(r"$\mu$") + ax.set_ylabel(r"$\sigma$") + ax.set_ylim(0, 1.3 * σ_path.max()) + ax.legend(loc="lower center") +plt.tight_layout() +plt.show() +``` + +We measure the length of the shortest path from $A$ to $B$ in two coordinate systems: in $(\mu, \sigma)$ with {eq}`ef_fisher_normal`, and in natural parameters with the Fisher information matrix $\nabla^2 F(\theta)$. + +```{code-cell} ipython3 +μ_path, σ_path = normal_geodesic(0.0, 0.2, 1.0, 0.2, n_points=2001) + +dμ, dσ = np.diff(μ_path), np.diff(σ_path) +σ_mid = (σ_path[1:] + σ_path[:-1]) / 2 +length_μσ = np.sum(np.sqrt(dμ**2 + 2 * dσ**2) / σ_mid) + +θ_path = np.array([normal_θ(μ, σ) for μ, σ in zip(μ_path, σ_path)]) +dθ = np.diff(θ_path, axis=0) +θ_mid = (θ_path[1:] + θ_path[:-1]) / 2 +length_θ = sum(np.sqrt(d @ hessian(F_normal, m) @ d) for d, m in zip(dθ, θ_mid)) + +print(f"length in (μ, σ): {length_μσ:.4f}") +print(f"length in natural parameters: {length_θ:.4f}") +print(f"formula (ef_fisher_rao_normal): {fisher_rao_normal(0.0, 0.2, 1.0, 0.2):.4f}") +``` + +The two lengths agree with each other and with {eq}`ef_fisher_rao_normal`. + +The Fisher–Rao distance depends on the family through which paths may pass. + +A path between two normal models can leave the normal family and pass through other densities. + +The map $p \mapsto 2 \sqrt{p}$ sends each density to a point on a sphere of radius $2$, because $\int (2 \sqrt{p})^2 \, dx = 4$. + +It also turns the Fisher quadratic form $\int (dp)^2 / p \, dx$ into the squared Euclidean length $\int (d \, 2 \sqrt{p})^2 \, dx$. + +So the shortest path between two densities, when every density is allowed, is an arc of a great circle, and its length is + +$$ +d_{FR}(p, q) = 2 \arccos \int \sqrt{p(x) \, q(x)} \, dx , +$$ (ef_fisher_rao_all) + +where $\int \sqrt{p q} \, dx$ is the Bhattacharyya coefficient of {doc}`divergence_measures`. + +{cite:t}`KhanZhang2022` describe the same construction for distributions on a finite set. + +```{code-cell} ipython3 +for name, (μa, σa, μb, σb) in pairs.items(): + bc = integrate.quad(lambda x: np.sqrt(norm.pdf(x, μa, σa) * norm.pdf(x, μb, σb)), + -np.inf, np.inf)[0] + print(f"{name}: through normal models {fisher_rao_normal(μa, σa, μb, σb):.5f}, " + f"through all densities {2 * np.arccos(bc):.5f}") +``` + +For $A$ and $B$, a path through densities that are not normal is shorter, $3.054$ against $3.775$. + +For $C$ and $D$, the two distances agree to four decimal places. + +The Wasserstein distance {eq}`ef_wasserstein` selects other shortest paths. + +In the coordinates $(\mu, \sigma)$ it is the Euclidean distance, so its shortest path between two normal models is the straight line between their parameter vectors. + +For $A$ and $B$, that is the path with $\sigma$ fixed, the dashed line in the figure of shortest paths. + +Each model on it is the distribution of $(1 - \tau) X + \tau Y$, $0 \leq \tau \leq 1$, where $(X, Y)$ has the joint distribution that attains {eq}`ef_wasserstein`. + +{cite:t}`McCann1997` called this path **displacement interpolation**, and {cite:t}`Takatsu2011` studied it for normal models. + +The figure plots the models at the midpoints of three paths from $A$ to $B$: the Wasserstein path, the Fisher–Rao path within the normal family, and the mixture path $(1 - \tau) A + \tau B$, which {doc}`information_projections` studies. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Midpoints of three interpolating paths + name: fig-ef-midpoints +--- +x_mid = np.linspace(-1, 2, 600) +μ_fr, σ_fr = normal_geodesic(0.0, 0.2, 1.0, 0.2, n_points=401) +midpoints = { + "Wasserstein: N(0.5, 0.2²)": norm.pdf(x_mid, 0.5, 0.2), + f"Fisher–Rao: N({μ_fr[200]:.1f}, {σ_fr[200]:.3f}²)": + norm.pdf(x_mid, μ_fr[200], σ_fr[200]), + "mixture: (A + B) / 2": 0.5 * (norm.pdf(x_mid, 0, 0.2) + norm.pdf(x_mid, 1, 0.2)), +} +fig, ax = plt.subplots() +for μ in (0.0, 1.0): + ax.plot(x_mid, norm.pdf(x_mid, μ, 0.2), color="0.75", lw=1, + label="A and B" if μ == 0 else None) +for label, density in midpoints.items(): + ax.plot(x_mid, density, lw=2, label=label) +ax.set_xlabel("$x$") +ax.set_ylim(0, 2.9) +ax.legend(loc="upper center", ncol=2, fontsize=9, frameon=False) +plt.show() +``` + +The Wasserstein path slides the mass of $A$ toward $B$ and keeps its shape. + +The Fisher–Rao path spreads the mass out and gathers it again. + +The mixture path leaves the mass where it is and changes the heights of the two humps. + +(ef_estimation)= ## Estimation ### Maximum likelihood matches moments -Let $x_1, \ldots, x_n$ be IID draws from a member of the exponential family. +Let $x_1, \ldots, x_n$ be IID draws from a model in an exponential family. The average log likelihood is @@ -959,6 +1639,8 @@ The maximum likelihood estimator of the natural parameter is $\hat \theta = \nab When it does not, as in a Bernoulli sample with no successes, $\hat \theta$ does not exist (see {ref}`ef_ex_bernoulli`). +When both exist, the estimates $\hat \eta$ and $\hat \theta$ are two sets of coordinates of one estimated model. + The maximized average log likelihood is $F^*(\bar t)$ plus the average of $\log h(x_i)$, by {eq}`ef_fenchel`. In expectation parameters, maximum likelihood estimation is trivial; in natural parameters, it requires inverting $\nabla F$. @@ -969,6 +1651,8 @@ For the gamma and Beta families, inverting $\nabla F$ takes a numerical method, The maximum likelihood estimators in the two coordinate systems behave differently in finite samples. +Both estimators name the same estimated model; bias and covariance depend on the coordinate system, as the table in {ref}`ef_invariants` records. + The estimator $\hat \eta = \bar t$ is unbiased because it is a sample average; its covariance matrix is $\operatorname{Cov}_\theta[t(X)]/n = \nabla^2 F(\theta)/n$. The Fisher information matrix for $\eta$ is $\nabla^2 F^*(\eta)$, so the Cramér–Rao lower bound for an unbiased estimator of $\eta$ is $\left[\nabla^2 F^*(\eta)\right]^{-1}/n = \nabla^2 F(\theta)/n$. @@ -1056,6 +1740,14 @@ In natural parameters, the cloud is skewed, its mean is displaced from the true ## Concluding remarks +A family is a set of models, and a parameterization gives the models coordinates. + +KL divergence and the Fisher–Rao distance depend neither on the coordinates nor on invertible transformations of the data. + +Sufficient statistics preserve them. + +If the set of possible outcomes of a smooth family of densities does not depend on its parameter, and if its samples have sufficient statistics of a fixed finite dimension, then the family is an exponential family. + For the exponential family, one convex function $F$ delivers four facts: * its gradient maps natural parameters $\theta$ to expectation parameters $\eta$, and the gradient of its conjugate $F^*$ maps them back; @@ -1063,7 +1755,7 @@ For the exponential family, one convex function $F$ delivers four facts: * its conjugate is the negative of entropy, when the base measure is constant; and * the Bregman divergences of $F$ and $F^*$ are KL divergences. -Members of the exponential family solve maximum entropy problems. +Models in an exponential family solve maximum entropy problems. The normal density maximizes entropy among densities with a given mean and variance. @@ -1071,6 +1763,10 @@ The Lagrange multipliers of a maximum entropy problem are natural parameters and The logit model's inclusive value is a log-partition function, and its conjugate is negative entropy. +For the normal family, the Fisher–Rao distance is a distance of hyperbolic geometry. + +The Wasserstein distance of optimal transport measures how far probability mass moves; it ignores the parameterization but depends on the units of the data. + The sequel {doc}`information_projections` uses these facts to describe the geometry of KL divergence. ## Exercises @@ -1162,6 +1858,77 @@ The two sets of estimates agree. ```{solution-end} ``` +```{exercise} +:label: ef_ex_moments4 + +Adding powers of $x$ to the sufficient statistic produces a richer exponential family, at the cost of a log-partition function with no closed form. + +Consider densities on the real line with + +$$ +E[X] = 0, \qquad E[X^2] = 1, \qquad E[X^3] = 0.5, \qquad E[X^4] = 3.5 . +$$ + +1. Show that the density with the largest entropy has the form $\exp\left(\sum_{k=1}^4 \theta_k x^k - F(\theta)\right)$, and explain why $\theta_4 < 0$. +2. Approximate the solution with the function `maxent` on a grid of points. Check that the natural parameters do not change when you widen and refine the grid. +3. Compare the entropy of the solution with the entropy of $N(0, 1)$, and verify {eq}`ef_normal_gap`. +``` + +```{solution-start} ef_ex_moments4 +:class: dropdown +``` + +Here is one solution. + +For part 1, the argument that led to {eq}`ef_maxent_solution` gives a density proportional to $\exp\left(\sum_{k=1}^4 \theta_k x^k\right)$. + +The density is integrable only if the highest power of $x$ with a nonzero coefficient is even and its coefficient is negative. + +If $\theta_4 = 0$, integrability would require $\theta_3 = 0$, and the density would be normal, with $E[X^3] = 0 \neq 0.5$. + +Therefore $\theta_4 < 0$. + +The integral that defines $F$ has no closed form, so we compute $\theta$ numerically. + +For part 2, we solve the problem on three grids. + +```{code-cell} ipython3 +c4 = np.array([0.0, 1.0, 0.5, 3.5]) +for bound, n_points in ((8, 641), (10, 1601), (12, 2401)): + grid4 = np.linspace(-bound, bound, n_points) + T4 = np.column_stack([grid4**k for k in range(1, 5)]) + θ4, p4 = maxent(np.full(grid4.size, 1 / grid4.size), T4, c4) + print(f"grid [-{bound}, {bound}] with {n_points} points: θ = {np.round(θ4, 5)}") +``` + +The natural parameters agree to five decimal places. + +For part 3, we compute the entropy of the solution on the last grid, its KL divergence from $N(0, 1)$, and the entropy shortfall. + +```{code-cell} ipython3 +spacing4 = grid4[1] - grid4[0] +density4 = p4 / spacing4 +H4 = -p4 @ np.log(density4) +kl4 = p4 @ (np.log(density4) - norm.logpdf(grid4)) +print(f"entropy of the solution: {H4:.5f}") +print(f"entropy of N(0, 1): {norm.entropy():.5f}") +print(f"H(φ) - H(p): {norm.entropy() - H4:.5f}") +print(f"KL(p || φ): {kl4:.5f}") + +fig, ax = plt.subplots() +ax.plot(grid4, density4, lw=2, label="maximum entropy density") +ax.plot(grid4, norm.pdf(grid4), "k--", lw=1, label="N(0, 1)") +ax.set_xlim(-5, 5) +ax.set_xlabel("$x$") +ax.legend(loc="upper left") +plt.show() +``` + +The solution has the same mean and variance as $N(0, 1)$, so {eq}`ef_normal_gap` applies, and the entropy shortfall equals the KL divergence. + +```{solution-end} +``` + ```{exercise} :label: ef_ex_poisson @@ -1277,8 +2044,8 @@ Meanwhile $\hat \eta$ is unbiased and attains the Cramér–Rao bound at both sa Bayes' law takes a simple form in natural parameters. -1. Let $x_1, \ldots, x_n$ be IID Bernoulli($\pi$) draws, and let the prior for $\pi$ be Beta($a$, $b$). Using the Beta row of the table above, write the prior as a member of the Beta family with natural parameters $(a - 1, b - 1)$ and show that the posterior is a member of the same family whose natural parameters are those of the prior plus $\left(\sum_i x_i, \, n - \sum_i x_i\right)$. -2. Explain why, more generally, if the log likelihood is linear in some functions of the parameter and the prior is a member of the exponential family with those functions as its sufficient statistic, the posterior is in the same family and Bayes' law adds to its natural parameters. +1. Let $x_1, \ldots, x_n$ be IID Bernoulli($\pi$) draws, and let the prior for $\pi$ be Beta($a$, $b$). Using the Beta row of the table above, write the prior as a distribution in the Beta family with natural parameters $(a - 1, b - 1)$ and show that the posterior is a distribution in the same family whose natural parameters are those of the prior plus $\left(\sum_i x_i, \, n - \sum_i x_i\right)$. +2. Explain why, more generally, if the log likelihood is linear in some functions of the parameter and the prior is a distribution in an exponential family with those functions as its sufficient statistic, the posterior is in the same family and Bayes' law adds to its natural parameters. 3. Starting from a Beta(1, 1) prior and draws with $\pi = 0.3$, plot the posterior mean of $\pi$, with a band of two posterior standard deviations, as a function of $n$. After $n = 200$ draws, use {eq}`ef_gradient` and {eq}`ef_hessian` to compute the posterior mean and variance of $\log \pi$, and check them by Monte Carlo. The Beta–Bernoulli model appears in {doc}`exchangeable`, {doc}`likelihood_bayes`, and {doc}`merging_of_opinions`. @@ -1345,3 +2112,72 @@ print(f"Var[log π]: formula {polygamma(1, a) - polygamma(1, a + b):.5f}, " ```{solution-end} ``` + +```{exercise} +:label: ef_ex_jeffreys + +The Jeffreys prior of a family has density proportional to $\sqrt{\det I(\theta)}$. + +1. For the Bernoulli family in coordinates $\pi$, show that $I(\pi) = 1 / (\pi (1 - \pi))$ and that the Jeffreys prior is Beta($1/2$, $1/2$). +2. In the natural parameter $\theta = \log(\pi / (1 - \pi))$, show that $I(\theta) = \pi (1 - \pi)$. Show that the Jeffreys prior in $\theta$, with density proportional to $\sqrt{\pi (1 - \pi)}$, is the distribution of $\theta$ when $\pi$ has the Beta($1/2$, $1/2$) distribution. +3. Draw $\pi$ from the uniform distribution on $(0, 1)$ and from Beta($1/2$, $1/2$), transform each draw to $\theta$, and compare histograms of $\theta$ with the densities that the change-of-variables formula implies. Is the uniform prior on $\pi$ flat in $\theta$? +``` + +```{solution-start} ef_ex_jeffreys +:class: dropdown +``` + +Here is one solution. + +For part 1, the score is $x / \pi - (1 - x) / (1 - \pi)$, and its variance is $\pi / \pi^2 + (1 - \pi) / (1 - \pi)^2 = 1 / (\pi (1 - \pi))$. + +The Jeffreys prior has density proportional to $\pi^{-1/2} (1 - \pi)^{-1/2}$, the Beta($1/2$, $1/2$) density. + +For part 2, $F(\theta) = \log(1 + e^\theta)$, so $I(\theta) = F''(\theta) = \pi (1 - \pi)$ by {eq}`ef_hessian`. + +Because $d\pi / d\theta = \pi (1 - \pi)$, the change-of-variables formula turns the Beta($1/2$, $1/2$) density into the density + +$$ +\frac{\pi^{-1/2} (1 - \pi)^{-1/2}}{B(1/2, 1/2)} \, \pi (1 - \pi) = \frac{\sqrt{\pi (1 - \pi)}}{B(1/2, 1/2)} +$$ + +for $\theta$, which is proportional to $\sqrt{I(\theta)}$. + +The same change of variables turns the uniform density for $\pi$ into the logistic density $\pi (1 - \pi) = e^\theta / (1 + e^\theta)^2$ for $\theta$. + +```{code-cell} ipython3 +rng_jeffreys = np.random.default_rng(4) +R_draws = 200_000 +θ_vals = np.linspace(-8, 8, 400) +π_vals = 1 / (1 + np.exp(-θ_vals)) +cases = { + "uniform prior on π": (rng_jeffreys.uniform(size=R_draws), + π_vals * (1 - π_vals)), + "Jeffreys prior, Beta(1/2, 1/2)": (rng_jeffreys.beta(0.5, 0.5, size=R_draws), + np.sqrt(π_vals * (1 - π_vals)) / np.pi), +} + +fig, axes = plt.subplots(1, 2, figsize=(10, 3.5)) +for ax, (name, (π_draws, density)) in zip(axes, cases.items()): + θ_draws = np.log(π_draws / (1 - π_draws)) + counts, edges = np.histogram(θ_draws, bins=80, range=(-8, 8)) + ax.stairs(counts / (R_draws * np.diff(edges)), edges, fill=True, alpha=0.4, + label=r"histogram of $\theta$") + ax.plot(θ_vals, density, "k", lw=1.5, label="change of variables") + ax.set_title(name) + ax.set_xlabel(r"$\theta$") + ax.legend() +plt.tight_layout() +plt.show() +``` + +In the code, `np.pi` is $B(1/2, 1/2) = \Gamma(1/2)^2 = 3.14159\ldots$. + +The uniform prior on $\pi$ is not flat in $\theta$: it puts most of its probability on $\lvert \theta \rvert < 3$. + +A flat prior on $\theta$ is improper; in $\pi$ its density is proportional to $1 / (\pi (1 - \pi))$. + +The Jeffreys prior is the same distribution over models in both coordinate systems. + +```{solution-end} +``` diff --git a/lectures/information_projections.md b/lectures/information_projections.md index 47877e8c2..90d87e94c 100644 --- a/lectures/information_projections.md +++ b/lectures/information_projections.md @@ -41,15 +41,15 @@ A distribution has two kinds of projection onto a set $\mathcal{S}$ of distribut Two kinds of "flat" sets of distributions serve as lines and planes: -* **linear families**, such as the set of distributions that give a statistic a prescribed mean; a linear family contains every mixture $(1 - a) p_0 + a p_1$ of two of its members, for every real $a$ for which the mixture is a probability distribution; and -* **exponential families**, described in {doc}`exponential_families`; an exponential family contains every normalized geometric mixture of two of its members, for every real $a$ for which the geometric mixture can be normalized. +* **linear families**, such as the set of distributions that give a statistic a prescribed mean; a linear family contains every mixture $(1 - a) p_0 + a p_1$ of two of its distributions, for every real $a$ for which the mixture is a probability distribution; and +* **exponential families**, described in {doc}`exponential_families`; an exponential family contains every normalized geometric mixture of two of its models, for every real $a$ for which the geometric mixture can be normalized. The e-projection onto a linear family and the m-projection onto an exponential family are unique, and each satisfies a Pythagorean theorem. The two projections have simple forms: * the e-projection of $q$ onto a linear family defined by moment conditions is an **exponential tilt** of $q$, a distribution proportional to $q(x) e^{\theta \cdot t(x)}$ for a vector $\theta$ that satisfies the moment conditions; and -* the m-projection of $p$ onto an exponential family **matches moments**: it is the member of the family that gives the sufficient statistic the same means as $p$ does. +* the m-projection of $p$ onto an exponential family **matches moments**: it is the model in the family that gives the sufficient statistic the same means as $p$ does. These two facts organize several ideas that economists use: @@ -62,6 +62,8 @@ These two facts organize several ideas that economists use: The worst-case models of robust control and the solutions of the RAS and Sinkhorn problems are exponential tilts of the kind that attains the logit formula {eq}`ef_logit_base` of {doc}`exponential_families`. +The multipliers of the entropy-regularized transport problem converge to the shadow prices of the linear program in {doc}`opt_transport`, and its entropy term charges for the mutual information between origins and destinations. + This lecture builds on {doc}`exponential_families` and on {doc}`divergence_measures`. {cite:t}`Csiszar1975` developed the theory of e-projections, which he called I-projections. @@ -84,7 +86,7 @@ import warnings We write $D(p \| q)$ for the KL divergence $D_{KL}(p \| q)$ and, as in {doc}`exponential_families`, read it as "the divergence of $p$ from $q$." -We write $q_\theta$ for the members of an exponential family, because they usually appear in the second argument of $D$. +We write $q_\theta$ for the models in an exponential family, because they usually appear in the second argument of $D$. Most of our examples use distributions on a finite set. @@ -197,7 +199,7 @@ In the coordinates described after {eq}`ip_three_point`, an m-geodesic is a stra A set of distributions is **m-flat** if, whenever it contains $p_0$ and $p_1$, it contains $p_a$ on the mixture path for every real $a$ for which $p_a$ is a probability distribution, not only for $a \in [0, 1]$; it is **e-flat** if the same holds for exponential paths. -A set that contains the mixture segments with $a \in [0, 1]$, but not necessarily the whole lines through its members, is merely convex in the ordinary sense. +A set that contains the mixture segments with $a \in [0, 1]$, but not necessarily the whole lines through its distributions, is merely convex in the ordinary sense. The e-projection onto a closed convex set is still unique, but the Pythagorean identity {eq}`ip_pythagoras_e` below weakens to the inequality $D(p \| q) \geq D(p \| p^*) + D(p^* \| q)$ {cite}`Csiszar1975`. @@ -241,15 +243,23 @@ def mixture_path(p0, p1, a): def exponential_path(p0, p1, a): log_w = (1 - a)[:, None] * np.log(p0) + a[:, None] * np.log(p1) return np.exp(log_w - logsumexp(log_w, axis=1, keepdims=True)) + + +def fisher_rao_path(p0, p1, a): + """Shortest path for the Fisher–Rao distance: a great circle in √p.""" + φ = np.arccos(np.sum(np.sqrt(p0 * p1))) + z = (np.sin((1 - a)[:, None] * φ) * np.sqrt(p0) + + np.sin(a[:, None] * φ) * np.sqrt(p1)) / np.sin(φ) + return z**2 ``` -The figure draws both paths between two distributions. +The figure draws both paths between two distributions, together with a third path that we describe below. ```{code-cell} ipython3 --- mystnb: figure: - caption: Mixture and exponential paths + caption: Mixture, exponential, and Fisher–Rao paths name: fig-ip-paths --- p0 = np.array([0.80, 0.15, 0.05]) @@ -261,6 +271,8 @@ draw_simplex(ax) ax.plot(*to_triangle(mixture_path(p0, p1, a)).T, lw=2, label="mixture path") ax.plot(*to_triangle(exponential_path(p0, p1, a)).T, lw=2, label="exponential path") +ax.plot(*to_triangle(fisher_rao_path(p0, p1, a)).T, lw=2, ls="--", + label="Fisher–Rao path") ax.plot(*to_triangle(np.vstack([p0, p1])).T, "ko") ax.text(*to_triangle(p0)[0] + [0.02, 0.0], "$p_0$") ax.text(*to_triangle(p1)[0] + [0.02, 0.0], "$p_1$") @@ -274,6 +286,34 @@ The exponential path bends toward the middle outcome. A geometric mean of two probabilities is small whenever either of them is small, which penalizes outcomes $0$ and $2$, each of which is improbable under one of the two distributions. +The third path is the shortest path for the Fisher–Rao distance of {doc}`exponential_families`. + +The map $p \mapsto 2 \sqrt{p}$ sends the simplex to part of a sphere of radius $2$, and, as {eq}`ef_fisher_rao_all` describes, the shortest path is an arc of a great circle, with length $2 \arccos \sum_x \sqrt{p_0(x) p_1(x)}$. + +The function `fisher_length` measures the length of each path with the Fisher information metric, under which a small step $dp$ from $p$ has squared length $\sum_x dp(x)^2 / p(x)$. + +```{code-cell} ipython3 +def fisher_length(path): + """Fisher–Rao length of a path whose rows are distributions.""" + dp = np.diff(path, axis=0) + mid = (path[1:] + path[:-1]) / 2 + return np.sum(np.sqrt(np.sum(dp**2 / mid, axis=1))) + + +a_fine = np.linspace(0, 1, 2001) +for name, path in (("mixture", mixture_path), ("exponential", exponential_path), + ("Fisher–Rao", fisher_rao_path)): + points = path(p0, p1, a_fine) + print(f"{name:12} path: length {fisher_length(points):.4f}, " + f"midpoint {np.round(points[1000], 3)}") +print(f"2 arccos of the Bhattacharyya coefficient: " + f"{2 * np.arccos(np.sum(np.sqrt(p0 * p1))):.4f}") +``` + +The mixture and exponential paths are straight lines in their own coordinates, but neither is the shortest path for the Fisher–Rao distance. + +The midpoint of the Fisher–Rao path puts probability $0.194$ on the middle outcome, between the $0.15$ of the mixture path and the $0.273$ of the exponential path. + ## Two projections and two Pythagorean theorems ### The e-projection onto a linear family @@ -318,7 +358,7 @@ which proves {eq}`ip_pythagoras_e`. Since $D(p \| p^*) > 0$ unless $p = p^*$, the tilt $p^*$ is the unique minimizer. ``` -When every member of $\mathcal{L}$ puts zero probability on some outcomes, as for a die whose mean is $6$, the e-projection still exists and is unique. +When every distribution in $\mathcal{L}$ puts zero probability on some outcomes, as for a die whose mean is $6$, the e-projection still exists and is unique. It lies outside the family of tilts, as a limit of tilts whose $\theta$ diverges. @@ -405,7 +445,7 @@ Conventions differ across the literature. Check which argument of the KL divergence a source minimizes and which orthogonality condition it attaches to which Pythagorean identity. -Let $p$, $q$, and $r$ be members of an exponential family with log-partition function $F$ and Bregman divergence $B_F$, as in {doc}`exponential_families`, with natural parameters $\theta_p$, $\theta_q$, $\theta_r$ and expectation parameters $\eta_p$, $\eta_q$, $\eta_r$. +Let $p$, $q$, and $r$ be models in an exponential family with log-partition function $F$ and Bregman divergence $B_F$, as in {doc}`exponential_families`, with natural parameters $\theta_p$, $\theta_q$, $\theta_r$ and expectation parameters $\eta_p$, $\eta_q$, $\eta_r$. Then @@ -441,7 +481,7 @@ outcomes = np.arange(3.0) q_e = np.array([0.6, 0.3, 0.1]) θ_e, p_star = match_mean(q_e, outcomes, 1.2) -# members of the linear family: p_star plus multiples of (1, -2, 1), +# distributions in the linear family: p_star plus multiples of (1, -2, 1), # small enough to keep every probability positive s_lo, s_hi = -min(p_star[0], p_star[2]), p_star[1] / 2 print("e-projection: D(p || q) and D(p || p*) + D(p* || q)") @@ -478,7 +518,7 @@ mystnb: def family_curve(base, t, θ_grid): - """Members of the exponential family generated by base and t.""" + """Models in the exponential family generated by base and t.""" return np.vstack([tilt(base, t, θ) for θ in θ_grid]) @@ -1099,6 +1139,7 @@ for s in (-3.0, 2.0, 5.0): f"{gen_kl(P_other, P_io) + gen_kl(P_io, Q_io):.6f}") ``` +(ip_entropic_ot)= ### Entropy-regularized optimal transport {doc}`opt_transport` studies the problem of choosing a transport plan $P$ with row totals $p$ and column totals $q$ (the notation of that lecture) to minimize the total cost $\sum_{i, j} C_{ij} P_{ij}$. @@ -1129,7 +1170,10 @@ We use the example of {doc}`opt_transport`, solve the linear program with `linpr ```{code-cell} ipython3 def sinkhorn(C, p, q, ε, tol=1e-10, max_iter=100_000): - """Entropy-regularized optimal transport by rescaling in logs.""" + """Entropy-regularized optimal transport by rescaling in logs. + + Returns the plan and the vectors α = ε log a and β = ε log b. + """ log_K = -C / ε log_a, log_b = np.zeros(len(p)), np.zeros(len(q)) for _ in range(max_iter): @@ -1140,7 +1184,7 @@ def sinkhorn(C, p, q, ε, tol=1e-10, max_iter=100_000): break else: warnings.warn("Sinkhorn's algorithm did not converge") - return P + return P, ε * log_a, ε * log_b p_ot = np.array([50.0, 100.0, 150.0]) @@ -1159,7 +1203,7 @@ P_lp = res_lp.x.reshape((m, n), order="F") print(f"linear program: cost = {res_lp.fun:.3f}") for ε in (10.0, 3.0, 1.0, 0.1): - P_ε = sinkhorn(C_ot, p_ot, q_ot, ε) + P_ε, _, _ = sinkhorn(C_ot, p_ot, q_ot, ε) print(f"ε = {ε:5.1f}: cost = {np.sum(C_ot * P_ε):9.3f}") ``` @@ -1168,7 +1212,7 @@ As $\varepsilon \to 0$, the cost of the regularized solution converges to the mi The regularized plans need not converge to the plan that `linprog` reports. ```{code-cell} ipython3 -P_small = sinkhorn(C_ot, p_ot, q_ot, 0.05) +P_small, _, _ = sinkhorn(C_ot, p_ot, q_ot, 0.05) print("linprog plan:\n", np.round(P_lp, 2)) print("limit of regularized plans:\n", np.round(P_small, 2)) @@ -1203,6 +1247,184 @@ print(f"cost = {np.sum(C_ot * P_maxent):.3f}, " f"entropy = {plan_entropy(P_maxent):.4f}") ``` +### Shadow prices and logit choice + +Write the regularized plan as + +$$ +P_{ij} = \exp\left( \frac{\alpha_i + \beta_j - C_{ij}}{\varepsilon} \right), +\qquad \alpha_i = \varepsilon \log a_i, \quad \beta_j = \varepsilon \log b_j . +$$ (ip_sinkhorn_plan) + +The vectors $\alpha$ and $\beta$ are Lagrange multipliers on the row and column totals: setting the derivative of the Lagrangian with respect to $P_{ij}$ to zero gives $C_{ij} + \varepsilon \log P_{ij} = \alpha_i + \beta_j$, which is {eq}`ip_sinkhorn_plan`. + +In {doc}`opt_transport`, the dual variables $u_i$ and $v_j$ of the linear program are shadow prices of the totals $p_i$ and $q_j$. + +Adding a constant to every $u_i$ and subtracting it from every $v_j$ leaves the dual objective unchanged when total supply equals total demand, so we compare $u - u_1$ and $v + u_1$ with $\alpha - \alpha_1$ and $\beta + \alpha_1$. + +In this example the dual solution is unique up to that constant. + +```{code-cell} ipython3 +res_dual = linprog(-np.hstack([p_ot, q_ot]), A_ub=A_eq.T, + b_ub=C_ot.reshape(-1, order="F"), bounds=[(None, None)] * (m + n)) +u_lp, v_lp = res_dual.x[:m], res_dual.x[m:] +print(f"linear program: u - u_1 = {np.round(u_lp - u_lp[0], 3)}, " + f"v + u_1 = {np.round(v_lp + u_lp[0], 3)}") +for ε in (1.0, 0.1, 0.03): + _, α, β = sinkhorn(C_ot, p_ot, q_ot, ε) + print(f"ε = {ε:4}: α - α_1 = {np.round(α - α[0], 3)}, " + f"β + α_1 = {np.round(β + α[0], 3)}") +``` + +As $\varepsilon \to 0$, the multipliers of the regularized problem converge to the shadow prices of the linear program. + +The exponent in {eq}`ip_sinkhorn_plan` is minus the **reduced cost** $C_{ij} - \alpha_i - \beta_j$ divided by $\varepsilon$. + +In the linear program, the reduced costs $c_{ij} - u_i - v_j$ are nonnegative, and complementary slackness makes them zero wherever an optimal plan ships a positive amount. + +As $\varepsilon \to 0$, the regularized plan puts vanishing weight on every cell whose reduced cost stays positive. + +```{code-cell} ipython3 +print("reduced costs of the linear program:\n", + np.round(C_ot - u_lp[:, None] - v_lp[None, :], 2)) +print("cells used by the limit of the regularized plans:\n", + (P_small > 1e-6 * p_ot.sum()).astype(int)) +``` + +The limit of the regularized plans uses exactly the cells with zero reduced cost. + +Dividing row $i$ of {eq}`ip_sinkhorn_plan` by its total $p_i$ gives the distribution of the destination of a unit shipped from origin $i$: + +$$ +\frac{P_{ij}}{p_i} = \frac{\exp\left( (\beta_j - C_{ij}) / \varepsilon \right)}{\sum_k \exp\left( (\beta_k - C_{ik}) / \varepsilon \right)} . +$$ + +This is a multinomial logit with utilities $\beta_j - C_{ij}$ and scale $\varepsilon$. + +If each unit shipped from origin $i$ chose its destination by this logit rule, valuing destination $j$ at $\beta_j$ minus the cost of getting there, then the $\beta_j$ would be prices at which arrivals at each destination equal $q_j$. + +In the matching model of {cite:t}`ChooSiow2006`, agents on both sides of the market choose partners by logit rules of this kind. + +Sinkhorn's row update sets + +$$ +\alpha_i = \varepsilon \log p_i - \varepsilon \log \sum_j \exp\left( \frac{\beta_j - C_{ij}}{\varepsilon} \right) . +$$ + +The second term is minus the inclusive value {eq}`ef_logit` of this logit, with $\tau = \varepsilon$. + +As $\varepsilon \to 0$, the inclusive value converges to the largest utility, so the update converges to $\alpha_i = \min_j (C_{ij} - \beta_j)$. + +The linear program has the same relation: the dual constraints $u_i + v_j \leq c_{ij}$ hold for every $j$, and one of them binds because origin $i$ ships to some destination, so $u_i = \min_j (c_{ij} - v_j)$. + +Optimal transport calls this operation the **c-transform**; with the cost $c(x, y) = -x \cdot y$, it is the Legendre transform of {doc}`exponential_families`, up to signs {cite}`KhanZhang2022`. + +Sinkhorn's algorithm replaces the minimum in the c-transform by a logit inclusive value. + +### An exponential family of plans + +Divide a plan by its total $M = \sum_i p_i$ to turn it into a probability distribution over the cells $(i, j)$. + +For a fixed cost matrix and $\varepsilon$, the plans {eq}`ip_sinkhorn_plan` for all vectors $\alpha$ and $\beta$ form an exponential family on the cells. + +Its base measure is $K_{ij} = \exp(-C_{ij} / \varepsilon)$, its sufficient statistic is the pair of indicator vectors of the row $i$ and the column $j$, its natural parameters are $\alpha / \varepsilon$ and $\beta / \varepsilon$, and its expectation parameters are the row and column totals of the normalized plan {cite}`AmariKarakidaOizumi2018`. + +The regularized plan is the model in this family whose expectation parameters equal the required totals $p / M$ and $q / M$, so Sinkhorn's algorithm maps expectation parameters to natural parameters. + +The plan is therefore two projections at once. + +It is the e-projection of $K$ onto the linear family of plans with the required totals, and, by {prf:ref}`ip_thm_m_projection`, it is the m-projection of every plan with those totals onto the exponential family. + +The linear family and the exponential family cross at one point, as in the right panel of the figure of the two projections. + +We check the Pythagorean theorem {eq}`ip_pythagoras_m` with two plans that have the required totals, the plan of the linear program and the independent plan $p q^\top / M$, and a model in the family with arbitrary multipliers. + +```{code-cell} ipython3 +M = p_ot.sum() +P_1, _, _ = sinkhorn(C_ot, p_ot, q_ot, 1.0) +rng_ot = np.random.default_rng(7) +log_w = rng_ot.normal(size=m)[:, None] + rng_ot.normal(size=n)[None, :] - C_ot +other = np.exp(log_w - logsumexp(log_w)) +for name, P in (("linear program", P_lp), ("independent plan", np.outer(p_ot, q_ot) / M)): + print(f"{name:16}: D(P || other) = {kl(P / M, other):.6f}, " + f"D(P || P_ε) + D(P_ε || other) = {kl(P / M, P_1 / M) + kl(P_1 / M, other):.6f}") +``` + +### A cost of information + +{cite:t}`KhanZhang2022` point out that the entropy term of the regularized problem is a KL divergence in disguise. + +Let $\pi = P / M$, and let $r = p / M$ and $c = q / M$ be its marginal distributions. + +For every plan with the required totals, + +$$ +\sum_{i, j} P_{ij} \log P_{ij} = M \left[ I(\pi) - H(r) - H(c) + \log M \right] , +$$ + +where $I(\pi) = D(\pi \| r c^\top)$ is the mutual information between origin and destination, as in the section on independence and mutual information. + +Only $I(\pi)$ depends on the plan, so the regularized problem is equivalent to + +$$ +\min_{\pi} \; E_\pi [C] + \varepsilon \, I(\pi) , +$$ (ip_ot_information) + +over joint distributions $\pi$ of origins and destinations with marginal distributions $r$ and $c$. + +A dispatcher who pays $\varepsilon$ for each nat of information that the destination of a unit carries about its origin chooses the regularized plan. + +{cite:t}`Sims2003` measures the cost of attention with mutual information, and {cite:t}`MatejkaMcKay2015` show that a decision maker who pays for mutual information makes logit choices. + +Here the totals of the destinations are fixed, and the prices $\beta$ adjust to meet them. + +As $\varepsilon$ grows, the plan approaches the independent plan $p q^\top / M$, which uses no information. + +As $\varepsilon \to 0$, it approaches the optimal plan with the largest entropy, and because $H(\pi) = H(r) + H(c) - I(\pi)$, this is the optimal plan that uses the least information. + +Because the regularized plan minimizes {eq}`ip_ot_information`, the pairs $(I(\pi_\varepsilon), E_{\pi_\varepsilon}[C])$ trace the lowest expected cost attainable with each amount of information, a convex curve whose slope at $\pi_\varepsilon$ is $-\varepsilon$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Cost and mutual information of regularized plans + name: fig-ip-ot-information +--- +def mutual_information(P): + π = P / P.sum() + return kl(π, np.outer(π.sum(axis=1), π.sum(axis=0))) + + +def cost_and_information(ε): + P_ε, _, _ = sinkhorn(C_ot, p_ot, q_ot, ε) + return mutual_information(P_ε), np.sum(C_ot * P_ε) / M + + +frontier = np.array([cost_and_information(ε) for ε in np.geomspace(0.05, 500, 80)]) +I_5, cost_5 = cost_and_information(5.0) +I_line = np.linspace(I_5 - 0.15, I_5 + 0.15, 2) + +fig, ax = plt.subplots() +ax.plot(*frontier.T, lw=2, label="regularized plans") +ax.plot(I_line, cost_5 - 5.0 * (I_line - I_5), "k--", lw=1, + label=r"slope $-\varepsilon$ at $\varepsilon = 5$") +ax.plot(0, np.sum(C_ot * np.outer(p_ot, q_ot)) / M**2, "o", label="independent plan") +ax.plot(mutual_information(P_lp), np.sum(C_ot * P_lp) / M, "s", + label="plan of the linear program") +ax.set_xlabel("mutual information between origin and destination (nats)") +ax.set_ylabel("expected cost per unit shipped") +ax.legend() +plt.show() + +print(f"independent plan: E[C] = {np.sum(C_ot * np.outer(p_ot, q_ot)) / M**2:.3f}") +print(f"ε = 0.05: I = {frontier[0, 0]:.4f}, E[C] = {frontier[0, 1]:.3f}") +print(f"plan of the linear program: I = {mutual_information(P_lp):.4f}, " + f"E[C] = {np.sum(C_ot * P_lp) / M:.3f}") +``` + +The plan that `linprog` reports attains the minimal cost with more information than it needs. + ## Chernoff information {doc}`divergence_measures` defines the Chernoff entropy, which information theorists call the Chernoff information, of densities $f$ and $g$ as @@ -1342,6 +1564,8 @@ The lecture applied m-projections to maximum likelihood estimation and mutual in The worst-case models of robust control, the biproportional tables of RAS, and the regularized transport plans are all exponential tilts of the kind that attains the logit formula {eq}`ef_logit_base` of {doc}`exponential_families`. +The regularized transport plans form an exponential family whose multipliers $\alpha$ and $\beta$, $\varepsilon$ times its natural parameters, converge up to a common constant to the shadow prices of the linear program; each plan charges for the information that destinations carry about origins. + {doc}`approximation_errors` applies m-projections to misspecified time series models and to seasonal adjustment, {doc}`specification_tests` describes specification tests as comparisons of m-projections, and {doc}`turbulence_inference` uses them to interpret a check of a calibrated search model against evidence on earnings instability. Other applications include the EM algorithm, which {cite:t}`CsiszarTusnady1984` interpret as alternating projections, and the hierarchical decomposition of interactions among many random variables of {cite:t}`Amari2001`, which {ref}`ip_ex_interactions` takes up. @@ -1532,7 +1756,7 @@ Consider three nested exponential families of joint distributions: * $\mathcal{E}_2$: $\log q(x, y, z)$ is a sum of functions of the pairs $(x, y)$, $(x, z)$, and $(y, z)$, so that there is no three-way interaction; and * $\mathcal{E}_3$: all distributions. -1. Use {prf:ref}`ip_thm_m_projection` to show that the m-projection of $p$ onto $\mathcal{E}_1$ is the product of its one-variable marginals and that the m-projection onto $\mathcal{E}_2$ is the member of $\mathcal{E}_2$ with the same two-variable marginals as $p$. +1. Use {prf:ref}`ip_thm_m_projection` to show that the m-projection of $p$ onto $\mathcal{E}_1$ is the product of its one-variable marginals and that the m-projection onto $\mathcal{E}_2$ is the model in $\mathcal{E}_2$ with the same two-variable marginals as $p$. 2. Compute the m-projection onto $\mathcal{E}_2$ by iterative proportional fitting: starting from the uniform distribution, repeatedly rescale the current distribution to match each of the three two-variable marginals of $p$. 3. Verify the decomposition $D(p \| p_1) = D(p \| p_2) + D(p_2 \| p_1)$, where $p_k$ is the m-projection onto $\mathcal{E}_k$. The left side, called the multi-information, measures the total dependence among the three variables; the first term on the right measures three-way interaction, and the second measures dependence through pairs. 4. Apply the decomposition to the distribution in which $X$ and $Y$ are independent fair coin flips and $Z = (X + Y) \bmod 2$ with probability $0.9$ and $Z = (X + Y + 1) \bmod 2$ with probability $0.1$. Interpret the result. @@ -1554,7 +1778,7 @@ The set $\mathcal{E}_2$ is an exponential family whose sufficient statistics are The product of the one-variable marginals is in $\mathcal{E}_1$ and matches them, so it is the m-projection onto $\mathcal{E}_1$. -Similarly, a member of $\mathcal{E}_2$ with the same two-variable marginals as $p$ is the m-projection onto $\mathcal{E}_2$. +Similarly, a model in $\mathcal{E}_2$ with the same two-variable marginals as $p$ is the m-projection onto $\mathcal{E}_2$. For part 2, the uniform starting point lies in $\mathcal{E}_2$, and each rescaling multiplies the current distribution by a function of one pair of variables, so every iterate lies in $\mathcal{E}_2$. @@ -1619,3 +1843,80 @@ Measures of dependence that look only at pairs of variables, such as correlation ```{solution-end} ``` + +```{exercise} +:label: ip_ex_inverse_ot + +{cite:t}`DupuyGalichon2014` and {cite:t}`GalichonSalanie2022` estimate the parameters of matching models from observed tables of matches. + +This exercise estimates the cost of a transport problem from an observed table of shipments. + +Let origins sit at points $x_i$ and destinations at points $y_j$ on the unit interval, with $d_{ij} = \lvert x_i - y_j \rvert$, and let the cost be $C_{ij} = \lambda d_{ij}$ with unknown $\lambda > 0$. + +Shipments follow the regularized plan with $\varepsilon = 1$; only $\lambda / \varepsilon$ can be identified. + +An analyst observes the counts $N_{ij}$ of $N$ shipments drawn independently from the plan, normalized to be a probability distribution $\pi$ over cells. + +1. Show that the distributions $\pi_{ij} \propto \exp(a_i + b_j - \lambda d_{ij})$, for all vectors $a$ and $b$ and all $\lambda$, form an exponential family, and that the maximum likelihood estimate matches the observed row totals, column totals, and average distance. +2. Draw $6$ origins and $8$ destinations from the uniform distribution, totals from Dirichlet distributions, and a table of $N = 2000$ shipments with $\lambda = 4$. Estimate $\lambda$ by finding the value at which the regularized plan with the observed row and column totals has the observed average distance. +3. Holding the row and column totals fixed, the derivative of the plan's average distance with respect to $\lambda$ is minus the Fisher information for $\lambda$ per shipment. Use it to compute a standard error, and compare it with the standard deviation of the estimates across $300$ simulated tables. +``` + +```{solution-start} ip_ex_inverse_ot +:class: dropdown +``` + +Here is one solution. + +For part 1, write the cell as the pair $(i, j)$; then $\log \pi_{ij} = a \cdot e_i + b \cdot e_j - \lambda d_{ij}$ minus a normalizing constant, where $e_i$ and $e_j$ are indicator vectors. + +This is an exponential family with sufficient statistic $(e_i, e_j, d_{ij})$ and natural parameter $(a, b, -\lambda)$. + +By the result of {doc}`exponential_families` that maximum likelihood matches moments, the estimate makes the model's means of the sufficient statistic equal to their sample means: the row totals, the column totals, and the average distance. + +For given $\lambda$, Sinkhorn's algorithm finds the $a$ and $b$ that match the totals, so we find $\lambda$ by one-dimensional root finding. + +The derivative in part 3 is the second derivative of the log likelihood per shipment after $a$ and $b$ have been chosen to match the observed totals, so $N$ times minus it is the information in the table. + +In an exponential family the second derivatives at given parameters do not depend on the data, so at the estimates this observed information equals the Fisher information. + +```{code-cell} ipython3 +rng_inv = np.random.default_rng(5) +m_s, n_s = 6, 8 +x_o, y_d = np.sort(rng_inv.uniform(size=m_s)), np.sort(rng_inv.uniform(size=n_s)) +d = np.abs(x_o[:, None] - y_d[None, :]) +p_s, q_s = rng_inv.dirichlet(5 * np.ones(m_s)), rng_inv.dirichlet(5 * np.ones(n_s)) +λ_true, N_ship = 4.0, 2000 +π_true, _, _ = sinkhorn(λ_true * d, p_s, q_s, 1.0) + + +def estimate_λ(counts, h=1e-4): + π_hat = counts / counts.sum() + r_hat, c_hat = π_hat.sum(axis=1), π_hat.sum(axis=0) + + def excess_distance(λ): + π_λ, _, _ = sinkhorn(λ * d, r_hat, c_hat, 1.0) + return np.sum(π_λ * d) - np.sum(π_hat * d) + + λ_hat = brentq(excess_distance, 0.0, 30.0) + info = -(excess_distance(λ_hat + h) - excess_distance(λ_hat - h)) / (2 * h) + return λ_hat, 1 / np.sqrt(counts.sum() * info) + + +def draw_table(): + return rng_inv.multinomial(N_ship, π_true.ravel()).reshape(m_s, n_s) + + +λ_hat, se = estimate_λ(draw_table()) +print(f"estimate {λ_hat:.3f}, standard error {se:.3f}") + +estimates = np.array([estimate_λ(draw_table()) for _ in range(300)]) +print(f"300 tables: mean estimate {estimates[:, 0].mean():.3f}, " + f"standard deviation {estimates[:, 0].std():.3f}, " + f"mean standard error {estimates[:, 1].mean():.3f}") +``` + +The standard errors match the spread of the estimates across simulated tables. + +```{solution-end} +``` diff --git a/lectures/opt_transport.md b/lectures/opt_transport.md index 3002f038d..56780aaef 100644 --- a/lectures/opt_transport.md +++ b/lectures/opt_transport.md @@ -28,6 +28,20 @@ We will provide other applications in followup lectures. {doc}`information_transfer` uses a transport problem with an extra averaging constraint to check whether one statistical experiment is a garbling of another. +{doc}`information_projections` adds an entropy term to the transport problem, +solves the new problem with Sinkhorn's algorithm, and shows that its Lagrange +multipliers converge to the shadow prices that we compute below. + +Optimal transport compares two distributions by how far mass must move to turn +one into the other, so it needs a cost of moving mass between locations. + +The Kullback–Leibler divergence of {doc}`divergence_measures` compares two +distributions location by location and uses no such cost; for the problems in +this lecture it would be infinite, because the factories and the locations +that they supply are different points. + +{doc}`exponential_families` contrasts the two kinds of comparison. + The optimal transport problem was studied in early work about linear programming, as summarized for example by {cite}`DoSSo`. A modern reference about applications in economics is {cite}`Galichon_2016`. @@ -133,7 +147,7 @@ More about this later. ## The Linear Programming Approach -In this section we discuss using using standard linear programming solvers to +In this section we discuss using standard linear programming solvers to tackle the optimal transport problem. @@ -225,7 +239,7 @@ $$ (\mathbf{1}_n' \otimes \mathbf{I}_m) \operatorname{vec}(X) = p. $$ -Similarly, the constraint $X' \ \mathbf{1}_m = q$ can be rewriten as: +Similarly, the constraint $X' \ \mathbf{1}_m = q$ can be rewritten as: $$ (\mathbf{I}_n \otimes \mathbf{1}_m') \operatorname{vec}(X) = q. @@ -472,7 +486,7 @@ Let's compare this transport plan with res.x ``` -Here the matrix $X$ contains entries $x_{ij}$ that tell amounts shipped **from** factor $i = 1, 2, 3$ +Here the matrix $X$ contains entries $x_{ij}$ that tell amounts shipped **from** factory $i = 1, 2, 3$ **to** location $j=1,2, \ldots, 5$. The vector $z$ evidently equals $\operatorname{vec}(X)$. @@ -514,7 +528,7 @@ res_qe = linprog_simplex(-c, A_eq=A_eq, b_eq=b_eq) While the two LP solvers use different algorithms (HiGHS vs. simplex), both should find optimal solutions. -The solutions differs since there are multiple optimal solutions, but the objective values are the same +The solutions differ because there are multiple optimal solutions, but the objective values are the same ```{code-cell} ipython3 np.allclose(-res_qe.fun, res.fun) @@ -548,7 +562,7 @@ time.) ## The Dual Problem -Let $u, v$ denotes vectors of dual decision variables with entries $(u_i), (v_j)$. +Let $u, v$ denote vectors of dual decision variables with entries $(u_i), (v_j)$. The **dual** to **minimization** problem {eq}`plannerproblem` is the **maximization** problem: @@ -563,7 +577,7 @@ The dual problem is also a linear programming problem. It has $m+n$ dual variables and $mn$ constraints. -Vectors $u$ and $v$ of **values** are attached to the first and the second sets of primal constraits, respectively. +Vectors $u$ and $v$ of **values** are attached to the first and the second sets of primal constraints, respectively. Thus, $u$ is attached to the constraints @@ -637,12 +651,37 @@ Similarly, $v_j$ is the cost of shipping one unit **to** location $j$. Call this the ship-in cost of one unit to location $j$. -Strong duality implies that total transprotation costs equals total ship-out costs **plus** total ship-in costs. +Strong duality implies that total transportation costs equals total ship-out costs **plus** total ship-in costs. It is reasonable that, for one unit of a product, ship-out cost $u_i$ **plus** ship-in cost $v_j$ should equal transportation cost $c_{ij}$. This equality is assured by **complementary slackness** conditions that state that whenever $x_{ij} > 0$, meaning that there are positive shipments from factory $i$ to location $j$, it must be true that $u_i + v_j = c_{ij}$. +The dual constraints and complementary slackness together determine each $u_i$ from the vector $v$. + +Because $u_i + v_j \leq c_{ij}$ for every $j$, and because equality holds for some location to which factory $i$ ships, + +$$ +u_i = \min_j \left( c_{ij} - v_j \right) . +$$ (ctransform) + +Optimal transport calls the map from $v$ to $u$ defined by {eq}`ctransform` the **c-transform**. + +With a cost $c(x, y) = -x \cdot y$, the c-transform becomes, up to signs, the Legendre transform that {doc}`exponential_families` uses {cite}`KhanZhang2022`. + +The **reduced cost** $c_{ij} - u_i - v_j$ of the route from factory $i$ to location $j$ is nonnegative, and it is zero on every route that an optimal plan uses. + +```{code-cell} ipython3 +u, v = res_dual.x[:m], res_dual.x[-n:] +print("reduced costs c_ij - u_i - v_j:\n", np.round(C - u[:, None] - v[None, :], 2)) +print("u:", u) +print("min_j (c_ij - v_j):", np.min(C - v[None, :], axis=1)) +``` + +Both optimal plans that we found above use only routes with zero reduced cost. + +{doc}`information_projections` shows that, when an entropy term is added to the objective, the solution ships along every route in amounts equal to $\exp(-(c_{ij} - \alpha_i - \beta_j)/\varepsilon)$, where, after a constant is added to $\alpha$ and subtracted from $\beta$, $\alpha$ and $\beta$ converge to $u$ and $v$ as $\varepsilon \to 0$. + @@ -819,6 +858,61 @@ nx.draw_networkx_edges(g, plt.show() ``` +### Entropic regularization + +The optimal plan ships along few routes. + +The linear program has $n_p + n_q = 64$ equality constraints, one of them redundant, and the solver returns a vertex of the set of feasible plans, which ships along at most $n_p + n_q - 1 = 63$ of the $1024$ routes. + +```{code-cell} ipython3 +print("routes used by the optimal plan:", np.sum(pi > 1e-12)) +``` + +{doc}`information_projections` describes an entropy-regularized version of the problem, + +$$ +\min_{X} \sum_{i, j} c_{ij} x_{ij} + \varepsilon \sum_{i, j} x_{ij} \log x_{ij} +$$ + +subject to the same constraints, whose solution ships a positive amount along every route. + +{cite:t}`Cuturi2013` showed that Sinkhorn's algorithm solves it quickly, and {cite:t}`PeyreCuturi2019` describe the computational methods that it opened up. + +The function `ot.sinkhorn` implements Sinkhorn's algorithm; its argument `reg` is our $\varepsilon$. + +For small $\varepsilon$, the option `method="sinkhorn_log"` carries out the computations in logarithms. + ```{code-cell} ipython3 +p_arr, q_arr = np.array(p_probs), np.array(q_probs) +plans = {"linear program": pi} +for ε in (0.1, 0.01): + plans[f"ε = {ε}"] = ot.sinkhorn(p_arr, q_arr, c, reg=ε, + method="sinkhorn_log", numItermax=20_000) +for name, plan in plans.items(): + mass = np.sort(plan.ravel())[::-1] + routes_99 = np.searchsorted(np.cumsum(mass), 0.99) + 1 + print(f"{name:15}: cost {np.vdot(plan, c):.4f}, " + f"routes carrying 99% of the mass {routes_99}") ``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Optimal and entropy-regularized transport plans + name: fig-ot-entropic +--- +fig, axes = plt.subplots(1, 3, figsize=(12, 4)) +for ax, (name, plan) in zip(axes, plans.items()): + ax.imshow(plan, cmap="Greys") + ax.set_title(name) + ax.set_xlabel("location $j$") + ax.set_ylabel("factory $i$") +plt.tight_layout() +plt.show() +``` + +As $\varepsilon$ falls, the regularized plans concentrate on fewer routes and their costs approach the minimal cost. + +The entropy term, which spreads the plan over many routes, also makes the regularized problem strictly convex and smooth, and so easy to solve {cite}`KhanZhang2022`. diff --git a/lectures/phillips_escaping_nash.md b/lectures/phillips_escaping_nash.md index 6a5094b58..ec36d19cd 100644 --- a/lectures/phillips_escaping_nash.md +++ b/lectures/phillips_escaping_nash.md @@ -58,6 +58,8 @@ The large-deviation results are statements about small gains. {ref}`en_simulation` simulates the model and finds that, at the gains used in this suite, escapes are frequent rather than rare. +{ref}`en_tilts` describes escapes as exponential tilts of the distribution of shocks, in the sense of {doc}`information_projections`, and prices them by KL divergence. + We work with the analytically tractable **static** model, in which the government regresses unemployment on current inflation and a constant. {doc}`phillips_learning` simulates CWS's richer *dynamic* model, in which the government's regression also includes lags; we compare the two near the end of the lecture. @@ -75,6 +77,7 @@ import matplotlib.pyplot as plt import numpy as np from scipy.integrate import solve_ivp from scipy.linalg import solve_discrete_are +from scipy.optimize import minimize_scalar ``` ## The model @@ -585,6 +588,102 @@ So pair 1 wins the race, and the escape forcing it induces is the $R^{-1}(\sigma CWS describe the winner's velocity as substantially larger than the other three; the table shows that this holds along the route, not at its start. +(en_tilts)= +## Escapes as exponential tilts + +Pair 1 replaces the four equally likely shock realizations by a distribution that puts probability $1/2$ on each of $(1, 1)$ and $(-1, -1)$, so that $W_1 W_2 = 1$ in every period. + +That distribution is the limit of a family of **exponential tilts** of the true shock distribution, in the sense of {doc}`information_projections`. + +For each real $\eta$, let + +$$ +q_\eta(w) = \frac{\exp(\eta \, w_1 w_2)}{4 \cosh \eta} , +\qquad w \in \{-1, 1\}^2 . +$$ + +Under $q_\eta$, the mean of $W_1 W_2$ is $m = \tanh \eta$, while $W_1$ and $W_2$ each still take the values $\pm 1$ with probability $1/2$. + +Because $W_2$ keeps its distribution, $R$ still follows its mean dynamics. + +The least squares update depends on the shocks only through their first and second moments, and the tilt changes only the mean of $W_1 W_2$, so averaging the update under $q_\eta$ adds the forcing $m \, (\sigma_1 \sigma_2, 0)^\top$ to $\bar g$. + +A tilt of size $m$ pushes beliefs in the direction of pair 1 at $m$ times its strength. + +Pair 1 is the limit $m \to 1$, reached only as $\eta \to \infty$, just as the distribution of a die whose mean is $6$ in {doc}`information_projections` is a limit of tilts whose parameter diverges. + +Large deviations theory puts a price on each tilt. + +By Sanov's theorem, as stated in {doc}`information_projections`, the probability that $n$ periods of shocks have empirical frequencies close to $q_\eta$ falls like $\exp(-n D(q_\eta \| q_0))$, where $q_0$ is the true distribution and + +$$ +D(q_\eta \| q_0) = \frac12 \left[ (1 + m) \log(1 + m) + (1 - m) \log(1 - m) \right] \equiv L(m) , +$$ (en_tilt_cost) + +which equals $\log 2$ at $m = 1$. + +$L$ is the Legendre transform {eq}`pl_legendre` of $\log \mathbb{E} \exp(\eta W_1 W_2) = \log \cosh \eta$, the log-partition function of the tilts, so {eq}`en_tilt_cost` bounds from above the integrand of the action functional {eq}`pl_action` along a path driven by a constant tilt. + +A path that takes time $t = n \varepsilon$ has probability of order $\exp(-t L(m) / \varepsilon)$, so its cost $t \, L(m)$ is measured in the same units as $\bar S$ in {eq}`en_control`. + +We compute escapes under constant tilts and find the cheapest one. + +```{code-cell} ipython3 +def tilt_cost(m): + "KL divergence (en_tilt_cost) of the tilt with E[W1 W2] = m from the true shocks." + if m == 1: + return np.log(2) + return 0.5 * ((1 + m) * np.log1p(m) + (1 - m) * np.log1p(-m)) + + +def tilted_escape(m, t_max=400): + "Conditional mean dynamics under the tilt with E[W1 W2] = m." + f = lambda γ, mod: m * np.array([mod.σ1 * mod.σ2, 0.0]) + return solve_ivp(cond_ode, [0, t_max], z0, args=(model, f), events=left_circle, + max_step=0.05, rtol=1e-9, atol=1e-11) + + +cheapest = minimize_scalar(lambda m: tilted_escape(m).t[-1] * tilt_cost(m), + bounds=(0.021, 0.1), method="bounded", options={"xatol": 1e-5}) + +print(f"{'tilt m':>8s} {'exit time':>10s} {'cost t·L(m)':>12s} {'exit slope':>11s} {'exit x':>7s}") +for m in (1.0, 0.5, 0.2, 0.1, 0.05, cheapest.x, 0.02): + s = tilted_escape(m) + γ_end = s.y[:2, -1] + if s.status == 1: + print(f"{m:8.4f} {s.t[-1]:10.3f} {s.t[-1] * tilt_cost(m):12.2e} " + f"{γ_end[0]:11.4f} {model.x(γ_end):7.3f}") + else: + print(f"{m:8.4f} {'never':>10s} beliefs settle at " + f"({γ_end[0]:.3f}, {γ_end[1]:.2f}), x = {model.x(γ_end):.2f}") +``` + +Every tilt that escapes leaves the circle at nearly the same point, with a slope between $-0.023$ and $-0.026$ and inflation near $0.12$. + +The tilt determines how fast the beliefs travel along the route; the route itself barely changes. + +The changed measure of CWS, the tilt $m = 1$, escapes fastest, by $t = 0.34$, but it is also the most expensive, at a cost of $0.24$. + +Weaker tilts take longer and cost less, down to a tilt of about $m = 0.0225$, which escapes at $t \approx 3.1$ at a cost of about $8 \times 10^{-4}$. + +Below $m = 0.02$ the mean dynamics win, and the beliefs settle near the self-confirming equilibrium. + +The cheapest constant tilt reproduces the timing of the dominant path in CWS's Figure 4, which leaves at about $t = 3$, and its exit slope, $-0.025$ in their Table 1. + +Its cost is an upper bound on $\bar S$, because a cheaper escape could vary the tilt along the way or tilt other statistics of the shocks; CWS find $\bar S \approx 5 \times 10^{-4}$. + +This explains the warning in CWS's footnote 14. + +The changed measure is the extreme tilt: it reaches the boundary first, but it is far less likely than the gentle tilts that a dominant escape uses. + +The lecture's shocks are Gaussian, while CWS's changed-measure argument uses binomial shocks. + +For Gaussian shocks whose variances stay at one, the cheapest distribution with $\mathbb{E}[W_1 W_2] = m$ is the bivariate normal with correlation $m$, whose KL divergence from the true distribution is $-\frac12 \log(1 - m^2)$; at $m = 0.0225$ it differs from $L(m)$ by less than $10^{-7}$. + +The epigraph states the conditional limit theorem of {doc}`information_projections` in words. + +Conditional on an escape, the shocks look as though they were drawn from the e-projection of their true distribution onto the set of distributions that produce the escape, the most likely of the unlikely distributions. + (en_vector_field)= ## Mean dynamics reinforce the escape diff --git a/lectures/phillips_learning.md b/lectures/phillips_learning.md index 68546372e..6fc02bad8 100644 --- a/lectures/phillips_learning.md +++ b/lectures/phillips_learning.md @@ -417,6 +417,40 @@ Read {eq}`pl_action2` as a cost that penalizes departures of the *realized drift The least-action escape therefore threads the beliefs through regions where the mean dynamics are weak and the noise is large — which, in our model, is the direction of the *induction hypothesis*. +```{note} +The integrand of {eq}`pl_action2`, with $w = 1$ and $\Sigma = \sigma \Omega \sigma^\top$ nonsingular, is the KL divergence of a normal distribution with mean $\tfrac{d}{ds}\phi$ from a normal distribution with mean $b(\phi)$, both with covariance matrix $\Sigma$. + +The matrix $\Sigma^{-1}$ is the Fisher information matrix of this family of normal models, as in {doc}`exponential_families`. + +The action therefore measures how far, in KL divergence, the innovations along a path are from the innovations that the mean dynamics expect. + +The escape problem {eq}`pl_escapeproblem` also chooses the duration $T$, so it can choose how fast to move along any curve of beliefs. + +Write $|v| = (v^\top \Sigma^{-1} v)^{1/2}$ and $\langle v, z \rangle = v^\top \Sigma^{-1} z$, and suppose that a curve $\phi(\alpha)$ is traversed with $d\alpha / ds = \lambda$. + +The cost per unit of $\alpha$ is $\frac{1}{2\lambda} |\lambda \phi' - b|^2$, where $\phi' = d\phi / d\alpha$, and the speed $\lambda = |b| / |\phi'|$ minimizes it, leaving + +$$ +\bar S(\phi) = \int \left( |\phi'| \, |b(\phi)| - \langle \phi', b(\phi) \rangle \right) d\alpha , +$$ + +the **geometric action** of {cite:t}`HeymannVandenEijnden2008`. + +The integrand does not change when the curve is traced at a different speed, so $\bar S$ is a length, and the escape route is the curve that joins $\phi_f$ to $\partial D$ with the shortest length in this sense. + +This length differs from the Fisher–Rao distance of {doc}`exponential_families`: + +* it is zero along the mean dynamics, where $\phi'$ points in the direction of $b$; +* it is not symmetric: moving against the mean dynamics costs $2 |\phi'| |b|$ per unit of $\alpha$; and +* its integrand is not the square root of a quadratic form, so it is not a Riemannian length. + +When $b = 0$ and $T$ is fixed, the minimizers of {eq}`pl_action2` are shortest paths for the Riemannian metric $\Sigma^{-1}$, traversed at constant speed. + +When the noise reaches only some components of $\phi$, as in the control problem {eq}`en_control` of {doc}`phillips_escaping_nash`, where the moment matrix $R$ follows its mean dynamics, the escape cannot be retimed freely, and the escape route solves a control problem instead of a shortest-path problem. + +{ref}`en_tilts` computes the KL cost of escapes in the static model. +``` + Our model does not satisfy the assumptions behind {eq}`pl_action2` exactly. Its innovation $F$ contains products such as $X_{C,t} X_{C,t}^\top$ and $X_{C,t} U_t$, so it is quadratic in the shocks rather than additive and Gaussian. diff --git a/lectures/phillips_priors.md b/lectures/phillips_priors.md index d74fd8eca..505ee6f20 100644 --- a/lectures/phillips_priors.md +++ b/lectures/phillips_priors.md @@ -386,6 +386,41 @@ Under a *general* prior $V$, the $P$ block of {eq}`pp_ode` does **not** decouple Prior beliefs about parameter drift now matter for whether the self-confirming equilibrium is even stable. +(ppr_natural_gradient)= +### Least squares as a natural gradient + +The government's regression {eq}`pp_belief`, with error variance $\sigma^2$, is a family of normal models for $U_n$ given $\Phi_n$, indexed by $\gamma$. + +For a fixed distribution of the data, the gradient of the expected log likelihood with respect to $\gamma$ is $\sigma^{-2}\, \mathbb{E}[\Phi (U - \Phi^\top \gamma)]$, and the Fisher information matrix of {doc}`exponential_families` is $\sigma^{-2}\, \mathbb{E}[\Phi \Phi^\top]$. + +Under the data that the beliefs $\gamma$ generate, these are $\sigma^{-2} \bar g(\gamma)$ and $\sigma^{-2} M(\gamma)$. + +Constant-gain recursive least squares, with its estimated moment matrix $R$ replaced by its mean $M(\gamma)$, sets $P = \varepsilon M^{-1}$ in {eq}`pp_ode`, so it moves the beliefs along the gradient premultiplied by the inverse of the Fisher information matrix, which {cite:t}`Amari1998` calls the **natural gradient**. + +Because the data depend on $\gamma$, $\bar g$ is not the gradient of a single function of $\gamma$; the statement holds at each $\gamma$ for the data that $\gamma$ generates. + +The invariance table of {doc}`exponential_families` explains why the natural gradient matters. + +Suppose the government measures inflation in other units, or as a deviation from a constant. + +Its regressors become $\Phi' = K^\top \Phi$ for an invertible matrix $K$, and its beliefs become $\gamma' = K^{-1} \gamma$. + +The gradient becomes $K^\top \bar g$, and the Fisher information matrix becomes $K^\top M K$. + +The natural gradient $(K^\top M K)^{-1} K^\top \bar g = K^{-1} M^{-1} \bar g$ is the old natural gradient in the new coordinates. + +The full recursion has the same property without the approximation, because its moment estimate becomes $R' = K^\top R K$ and its update $\dot R = \varepsilon [M(\gamma) - R]$ transforms in the same way. + +So least squares traces the same path of models in every coordinate system, and its eigenvalues $-1$ and $-\tfrac12$ do not depend on how the government measures inflation. + +The prior of recursive least squares, $V^* = \sigma^2 M(\bar\gamma)^{-1}$, is proportional to the inverse of the Fisher information matrix. + +The learning cycles below appear when the prior departs from that shape. + +**Stochastic gradient** learning, $\gamma_{n+1} = \gamma_n + \varepsilon \Phi_n (U_n - \Phi_n^\top \gamma_n)$, premultiplies the gradient by the identity matrix in whatever coordinates the government uses. + +It is not a natural gradient, and the stability of the self-confirming equilibrium under it depends on the units of the regressors {cite}`Giannitsarou2005,EvansHonkapohjaWilliams2010`; {ref}`ppr_ex7` shows that measuring inflation as a deviation from a constant can make the equilibrium unstable. + ## Learning cycles Here is the paper's most striking result: some priors make the self-confirming equilibrium *unstable*, and the mean dynamics then cycle. @@ -1365,3 +1400,107 @@ What the data do identify, they keep identifying as the sample grows, because th ```{solution-end} ``` + +```{exercise-start} +:label: ppr_ex7 +``` + +**Stochastic gradient** learning updates beliefs by + +$$ +\gamma_{n+1} = \gamma_n + \varepsilon \Phi_n \left(U_n - \Phi_n^\top \gamma_n\right), +$$ + +so its mean dynamics are $\dot\gamma = \varepsilon \bar g(\gamma)$. + +1. Show that, at the self-confirming equilibrium, stochastic gradient learning is the approximate filter {eq}`pp_kalman` with $P = \varepsilon I$ and the prior $V = \varepsilon^2 \sigma^2 M(\bar\gamma)$, which is proportional to the Fisher information matrix instead of its inverse. +1. Suppose that the government measures inflation as a deviation from a constant $c$, so that its regressors are $\Phi' = (1, \pi - c)$ and its beliefs are $\gamma' = (a + c b, b)$. Show that $\gamma = K \gamma'$ with $K = \begin{bmatrix} 1 & -c \\ 0 & 1 \end{bmatrix}$, that the mean dynamics of stochastic gradient learning in the new coordinates are $\dot\gamma' = \varepsilon K^\top \bar g(K \gamma')$, and that the mean dynamics of recursive least squares in the new coordinates describe the same path of beliefs as before. +1. Compute the eigenvalues of $K^\top (\partial \bar g / \partial \gamma) K$ at the self-confirming equilibrium for several values of $c$, and for inflation measured in hundredths, with regressors $(1, \pi / 100)$. For which values of $c$ is the self-confirming equilibrium unstable under stochastic gradient learning? +1. For $c = 7.5$, measure time in units of $1/\varepsilon$ periods, integrate the stochastic gradient mean dynamics from a point near the self-confirming equilibrium, and describe the path of inflation $x$. + +```{exercise-end} +``` + +```{solution-start} ppr_ex7 +:class: dropdown +``` + +For part 1, setting $P = \varepsilon I$ in {eq}`pp_kalman` gives the stochastic gradient update, and $P = \varepsilon I$ solves the Riccati equation {eq}`pp_riccati` at $\bar\gamma$ exactly when $\sigma^{-2} V = \varepsilon^2 M(\bar\gamma)$. + +For part 2, $\Phi'^\top \gamma' = a' + (\pi - c) b'$ equals $\Phi^\top \gamma = a + \pi b$ when $a = a' - c b'$ and $b = b'$, which is $\gamma = K \gamma'$, and then $\Phi' = K^\top \Phi$. + +So $\bar g'(\gamma') = \mathbb{E}[\Phi' (U - \Phi'^\top \gamma')] = K^\top \bar g(K \gamma')$. + +Under stochastic gradient learning, $\dot\gamma = K \dot\gamma' = \varepsilon K K^\top \bar g(\gamma)$, which differs from $\varepsilon \bar g(\gamma)$ unless $K K^\top = I$. + +Under recursive least squares, $M' = K^\top M K$, so $\dot\gamma' = \varepsilon (K^\top M K)^{-1} K^\top \bar g = \varepsilon K^{-1} M^{-1} \bar g$, and $\dot\gamma = \varepsilon M^{-1} \bar g$ as before. + +For part 3, the function `coordinates` returns $K$ for regressors $(1, (\pi - c)/s)$. + +```{code-cell} ipython3 +def coordinates(c=0.0, scale=1.0): + "K with γ = K γ' when the regressors are (1, (π - c) / scale)." + return np.array([[1.0, -c / scale], [0.0, 1 / scale]]) + + +J_sce = jacobian(model, γ_sce) +print(f"{'regressors':16s} {'stochastic gradient':>24s} {'least squares':>16s}") +for name, K in (("(1, π)", coordinates()), ("(1, π / 100)", coordinates(scale=100.0)), + ("(1, π - 5)", coordinates(c=5.0)), ("(1, π - 7.5)", coordinates(c=7.5)), + ("(1, π - 10)", coordinates(c=10.0))): + sg = np.sort(np.linalg.eigvals(K.T @ J_sce @ K).real) + rls = np.sort(np.linalg.eigvals(np.linalg.solve(K.T @ M_sce @ K, K.T @ J_sce @ K)).real) + print(f"{name:16s} {np.array2string(sg, precision=5):>24s} " + f"{np.array2string(rls, precision=3):>16s}") +``` + +The least squares eigenvalues are $-1$ and $-\tfrac12$ in every case. + +The stochastic gradient eigenvalues change with the units: measured in hundredths, inflation gives one eigenvalue of about $-10^{-5}$, so beliefs return to the equilibrium very slowly in one direction. + +Because $\det K = 1$ for a shift, the determinant of $K^\top (\partial \bar g / \partial \gamma) K$ equals $\det(\partial \bar g / \partial \gamma) = \sigma_2^2 / 2 > 0$, so the equilibrium is unstable exactly when the trace is positive. + +Using {eq}`pp_jacobian`, the trace is $-\tfrac12 c^2 + \tfrac32 u c - u^2 - \sigma_2^2 - \tfrac12$, which is positive for $c$ between $\left(3u \pm \sqrt{u^2 - 4 - 8 \sigma_2^2}\right)/2$. + +```{code-cell} ipython3 +u, σ2 = model.u, model.σ2 +root = np.sqrt(u**2 - 4 - 8 * σ2**2) +print(f"unstable for c between {(3 * u - root) / 2:.3f} and {(3 * u + root) / 2:.3f}") +``` + +With $u = 5$, stochastic gradient learning is unstable when inflation is measured from any constant between about $5.25$ and $9.75$. + +For part 4, we integrate the mean dynamics in the centered coordinates and map the beliefs back. + +```{code-cell} ipython3 +K = coordinates(c=7.5) +sg_ode = lambda t, z: K.T @ model.g_bar(K @ z) +z_start = np.linalg.solve(K, γ_sce + np.array([0.0, 0.01])) +sol = solve_ivp(sg_ode, [0, 1000], z_start, max_step=0.5, rtol=1e-8, atol=1e-10) +γ_path = K @ sol.y +x_path = -γ_path[0] * γ_path[1] / (1 + γ_path[1]**2) + +fig, axes = plt.subplots(1, 2, figsize=(12, 4)) +axes[0].plot(sol.t, x_path) +axes[0].axhline(model.u, color='k', ls='--', lw=1, label='Nash') +axes[0].set_xlabel(r'time, in units of $1/\varepsilon$ periods') +axes[0].set_ylabel('inflation $x$') +axes[0].legend() +axes[1].plot(γ_path[1], x_path) +axes[1].set_xlabel('slope $b$') +axes[1].set_ylabel('inflation $x$') +plt.tight_layout() +plt.show() + +late = sol.t > 500 +print(f"after t = 500, x ranges from {x_path[late].min():.2f} to {x_path[late].max():.2f}") +``` + +The beliefs leave the self-confirming equilibrium at once and settle on a cycle. + +Inflation jumps to about $7.7$, above the Nash rate, collapses to about $0.6$, near the Ramsey outcome, and then drifts slowly back up, about every $220$ units of time. + +The same economy, observed by a government that runs least squares, has a stable self-confirming equilibrium; only the units in which the stochastic gradient government measures inflation have changed. + +```{solution-end} +``` diff --git a/lectures/turbulence_inference.md b/lectures/turbulence_inference.md index 6850c50bc..f7e936275 100644 --- a/lectures/turbulence_inference.md +++ b/lectures/turbulence_inference.md @@ -641,6 +641,85 @@ Raising the turbulence parameter from $0.02$ to $0.04$ spreads both distribution Ljungqvist and Sargent pointed out that the model's distribution of averages spans a smaller range than the data's, because their workers are ex ante identical, and that the increase in the model's standard deviations occurs at lower standard deviations than in the data. +### Where the distributions move + +Ljungqvist and Sargent's second remark is about where probability mass moves between the two periods, not only about how far the distributions spread. + +Optimal transport describes such movements. + +For distributions on the real line and a cost of moving mass that is a convex function of the distance moved, the cheapest way to turn one distribution into another pairs quantiles, as in {ref}`ef_wasserstein_section` of {doc}`exponential_families`: the mass at the $u$-quantile of the first distribution moves to the $u$-quantile of the second. + +The **shift** $s(u) = G^{-1}(u) - F^{-1}(u)$, where $F$ and $G$ are the cumulative distribution functions of the two periods, records how far that mass moves. + +The shift compares two distributions, not the same men in two periods, so it describes how the quantiles move, not how any man's earnings changed. + +We compute the shift of the distribution of men's standard deviations for Gottschalk and Moffitt's histograms, spreading the men in each bar uniformly across it, and for our artificial panels at turbulence parameters $0.02$ and $0.04$. + +```{code-cell} ipython3 +def histogram_quantiles(percents, centers, u): + """Quantiles of a histogram whose mass is spread uniformly within each bar.""" + width = centers[1] - centers[0] + edges = np.append(centers - width / 2, centers[-1] + width / 2) + cdf = np.concatenate([[0.0], np.cumsum(percents) / np.sum(percents)]) + return np.interp(u, cdf, edges) + + +u_grid = np.linspace(0.0005, 0.9995, 1000) +shift_data = (histogram_quantiles(gm_fig4["1979-87"], gm_fig4_bins, u_grid) + - histogram_quantiles(gm_fig4["1970-78"], gm_fig4_bins, u_grid)) +sd02, sd04 = y02.std(axis=1, ddof=1), y04.std(axis=1, ddof=1) +shift_model = np.quantile(sd04, u_grid) - np.quantile(sd02, u_grid) + +print(" quantile PSID shift model shift") +for u in (0.1, 0.25, 0.5, 0.75, 0.9, 0.95): + k = np.argmin(np.abs(u_grid - u)) + print(f" {u:4.2f} {shift_data[k]:+.3f} {shift_model[k]:+.3f}") +print(f"smallest shift: PSID {shift_data.min():+.4f}, model {shift_model.min():+.4f}") +print(f"average shift: PSID {shift_data.mean():.4f}, model {shift_model.mean():.4f}") +print(f"men's averages in the model at turbulence 0.02 range from " + f"{y02.mean(axis=1).min():.2f} to {y02.mean(axis=1).max():.2f}") +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Quantile shifts of men's standard deviations + name: fig-ti-shifts +--- +keep = u_grid <= 0.95 +fig, ax = plt.subplots() +ax.plot(u_grid[keep], shift_data[keep], lw=2, label="PSID, 1970–78 to 1979–87") +ax.plot(u_grid[keep], shift_model[keep], lw=2, label="model, turbulence 0.02 to 0.04") +ax.axhline(0, color="0.7", lw=0.8) +ax.set_xlabel("quantile $u$") +ax.set_ylabel("shift $s(u)$") +ax.legend() +plt.show() +``` + +The figure stops at the 95th percentile, because above it the PSID quantiles depend on how we spread the men in the last, sparsely populated bars. + +In the PSID, the shift grows with the quantile, from $0.004$ at the 10th percentile to $0.126$ at the 90th: the upper quantiles of the distribution of standard deviations rose much more than the lower quantiles, which changed little. + +In the model, the shift lies between about $0.01$ and $0.02$ at every quantile from the 10th to the 95th: turbulence raises every quantile of the distribution of standard deviations by about the same amount. + +Below about the 37th percentile the model's shift exceeds the data's, while at the 90th and 95th percentiles the data's shift is more than eight times the model's. + +That is a quantitative version of Ljungqvist and Sargent's remark. + +Averaged over quantiles, the shift equals the change in the mean standard deviation, $0.043$ in the PSID and $0.014$ in the model. + +Because the PSID shift is nowhere negative, $0.043$ is also the 1-Wasserstein distance between the PSID distributions for the two periods; the shape of the shift tells where the mass moved. + +A comparison of the histograms by KL divergence would fail here. + +In our panel at turbulence $0.02$, men's averages range from $-0.84$ to $0.29$, while Gottschalk and Moffitt's histogram for 1970–78 puts about $2$ percent of men below $-1.1$ and about $5$ percent above $0.6$. + +The KL divergence of the data's distribution of averages from the model's is therefore infinite, while transport distances stay finite. + +Gottschalk and Moffitt's decomposition avoids the problem by comparing second moments, the parameters of m-projections onto the random-effects model. + ### Binding function Gottschalk and Moffitt's decomposition of the model's earnings at turbulence parameter $v$ is a pair of numbers $b(v) = (\sigma^2_\mu(v), \sigma^2_\nu(v))$, the parameters of the m-projection of the model's distribution of earnings onto the random-effects model.