Module contents
Lesson 17 of 19Advanced 115 min

Estimating entropy and mutual information from samples

Estimate entropy and mutual information using plug-in, nearest-neighbor and variational methods, and understand their statistical limits.

After this lesson you can

  • Analyze plug-in estimator bias and its corrections.
  • Implement KSG and assess nearest-neighbor limitations.
  • Derive variational bounds and compare their bias and variance.
  • Validate estimates with known-information benchmarks and uncertainty intervals.

Before you start

Motivation: information must be estimated too

Throughout this module we have treated entropy and mutual information as numbers computed from a known distribution. In practice you almost never know it: you have nn samples and want a number.

  • Neuroscience. How many bits about a stimulus does a neuron’s spike train carry? It is measured with a few hundred repetitions of each stimulus and responses that, discretized into binary words, have thousands of possible values. This is where the naive estimator was found to make systematic errors and where almost all the corrections you will see originated.
  • Representations. The information plane of deep networks, contrastive learning methods such as CPC or SimCLR, and feature selection discuss I(X;T)I(X; T) between data and activations. That quantity is never observed; it is estimated, and the estimate inherits the estimator’s flaws.
  • Data science. “These two variables share 0.3 nats” is a population claim made from a sample, just like a mean. It needs error bars and bias analysis, which it rarely receives.

The best-known case is the information plane. Shwartz-Ziv and Tishby (2017) estimated I(X;T)I(X; T) by discretizing activations of a network with hyperbolic tangent and observed a “compression” phase. Saxe et al. (2018) showed that the phase depended on the nonlinearity (it did not appear with ReLU) and the estimator, while Goldfeld et al. (2019) pointed out the underlying problem: in a deterministic network with continuous inputs, the true mutual information between input and layer is infinite. Much of what was plotted was a property of the histogram. By the end of the lesson you will know exactly why.

This lesson treats the problem as seriously as any estimation problem: each estimator’s bias and variance, the regime where it works, and what none can do. The three families are plug-in estimators and corrections (discrete variables), nearest-neighbor estimators (low- or medium-dimensional continuous variables), and variational bounds with a trainable critic (high dimensions, the world of deep learning). Unless stated otherwise, log⁡\log is the natural logarithm and all quantities are in nats; divide by ln⁡2\ln 2 to convert to bits.

The plug-in estimator and its bias

Let XX be discrete with distribution p=(p1,…,pK)p = (p_1, \dots, p_K) and X1,…,Xn∼iidpX_1, \dots, X_n \iid p. With counts Nk=#{j:Xj=k}N_k = \#\{j : X_j = k\} and frequencies p^k=Nk/n\hat p_k = N_k / n, the natural approach is substitution:

The plug-in estimator is consistent: p^→p\hat p \to p almost surely and HH is continuous on the simplex, so H^→H\hat H \to H. The issue is the rate and the sign of the error. Since HH is concave and E[p^]=p\E[\hat p] = p, Jensen’s inequality gives

E[H^]=E[H(p^)]≤H(E[p^])=H(p).\E[\hat H] = \E[H(\hat p)] \le H(\E[\hat p]) = H(p).

The plug-in estimator always underestimates entropy, for any pp and any nn. Intuitively, the empirical distribution is more “peaked” than the true one: rare unseen symbols count as impossible and observed ones weigh more than they should. The next result quantifies the error.

Proof

Write H^=∑kϕ(p^k)\hat H = \sum_k \phi(\hat p_k) with ϕ(t)=−tlog⁡t\phi(t) = -t\log t, which satisfies ϕ′(t)=−log⁡t−1\phi'(t) = -\log t - 1 and ϕ′′(t)=−1/t\phi''(t) = -1/t. Expand each term around pkp_k:

ϕ(p^k)=ϕ(pk)+ϕ′(pk)(p^k−pk)−(p^k−pk)22pk+Rk.\phi(\hat p_k) = \phi(p_k) + \phi'(p_k)(\hat p_k - p_k) - \frac{(\hat p_k - p_k)^2}{2p_k} + R_k.

Since Nk∼Bin⁡(n,pk)N_k \sim \Bin(n, p_k), the linear term has zero expectation and E[(p^k−pk)2]=pk(1−pk)/n\E[(\hat p_k - p_k)^2] = p_k(1 - p_k)/n. Summing,

E[H^]=H−∑k=1K1−pk2n+∑kE[Rk]=H−K−12n+∑kE[Rk].\E[\hat H] = H - \sum_{k=1}^K \frac{1 - p_k}{2n} + \sum_k \E[R_k] = H - \frac{K - 1}{2n} + \sum_k \E[R_k].

The remainder contains moments of order 3 and higher of p^k−pk\hat p_k - p_k, which are O(n−2)\bigO(n^{-2}); the rigorous calculation (Harris, 1975) separately controls the event that some p^k\hat p_k approaches 0, where ϕ\phi is not differentiable, and which has exponentially small probability because pkp_k is fixed. For the variance the linear term suffices (delta method): ∑kϕ′(pk)(p^k−pk)=−1n∑j(log⁡p(Xj)+1)+cte\sum_k \phi'(p_k)(\hat p_k - p_k) = -\frac{1}{n}\sum_j (\log p(X_j) + 1) + \text{cte}, a mean of nn independent variables with variance Var⁡[log⁡p(X)]\Var[\log p(X)].

∎

Three consequences to remember:

  1. Bias depends on KK, not pp. With K=100K = 100 and n=1000n = 1000 it is −99/2000≈−0.05-99/2000 \approx -0.05 nats regardless of the entropy. It scales as K/nK/n, while standard deviation scales as 1/n1/\sqrt{n}: for moderate nn and large KK, bias dominates error.
  2. Miller-Madow replaces KK with K^\hat K because KK is unknown (symbols with tiny pkp_k are never seen). It removes almost all bias when n≫Kn \gg K and falls short otherwise.
  3. Mutual information inherits the sum of the three biases, with positive sign. With full supports, the first-order term of I^\hat I is [−(KX−1)−(KY−1)+(KXKY−1)]/(2n)=(KX−1)(KY−1)/(2n)[-(K_X - 1) - (K_Y - 1) + (K_X K_Y - 1)]/(2n) = (K_X - 1)(K_Y - 1)/(2n). Two independent variables appear dependent: with KX=KY=10K_X = K_Y = 10 and n=200n = 200, expected information is about 0.20.2 nats when the truth is 0. It is no coincidence that 2nI^2n\hat I is the GG independence-test statistic, which under the null is approximately χ2\chi^2 with (KX−1)(KY−1)(K_X - 1)(K_Y - 1) degrees of freedom and exactly that mean.
InteractiveBias of the plug-in estimator
300 replicates of H^\hat H with K=100K = 100 and n=100n = 100
4.5904.6004.6104.620estimate (nats)log nHMean of each estimator by n (K = 100)024101001000n (logarithmic scale)
  • plug-in H^\hat H
  • Miller-Madow H^MM\hat H_{\mathrm{MM}}
  • true HH
  • ceiling log⁡n\log n
  • first order H−(K−1)/(2n)H - (K-1)/(2n)
100
100
Distribution
True HH (nats)4.605
Mean plug-in bias…
First-order prediction−0.495
Mean Miller-Madow bias…
Standard deviation of H^\hat H…
Symbols seen (mean)…
Ceiling log⁡n\log n4.605
Each replicate draws nn samples from a distribution over KK symbols and computes H^\hat H (blue) and the Miller-Madow correction (orange). The histogram of 300 replicates is compared with true HH; below, each estimator's mean versus nn, with the first-order prediction and the log⁡n\log n ceiling. Start with n=K=100n = K = 100: the entire blue histogram lies left of HH. Reduce nn to 20: plug-in cannot exceed log⁡n\log n, and Miller-Madow exceeds it by less than half a nat. Increase nn to 5000: bias falls as 1/n1/n. For the uniform distribution dispersion falls equally fast and bias remains about seven times larger; for Zipf it falls only as 1/n1/\sqrt n and eventually hides the bias.

No unbiased estimator

Can a cleverer formula remove bias entirely? No.

Proof

For any TT, Ep[T]=∑(x1,…,xn)T(x1,…,xn)∏j=1npxj\E_p[T] = \sum_{(x_1, \dots, x_n)} T(x_1, \dots, x_n) \prod_{j=1}^n p_{x_j} is a polynomial of degree at most nn in (p1,…,pK)(p_1, \dots, p_K). Restrict it to the edge p=(t,1−t,0,…,0)p = (t, 1 - t, 0, \dots, 0), t∈[0,1]t \in [0, 1]: this gives a polynomial g(t)g(t) with bounded derivative on [0,1][0, 1]. But HH restricted to that edge is binary entropy h(t)=−tlog⁡t−(1−t)log⁡(1−t)h(t) = -t\log t - (1-t)\log(1-t), with h′(t)=log⁡1−tt→∞h'(t) = \log\frac{1-t}{t} \to \infty as t→0+t \to 0^+. Thus g≠hg \neq h, and TT is biased for some pp.

∎

The argument says something subtler: an estimator with nn samples only “sees” degree-nn polynomials, and entropy near the simplex boundary (extremely rare symbols) resembles none of them. Every estimator trades bias against variance in the sense of mean squared error; what differs is where it accepts errors.

The undersampled regime

When nn is comparable to or smaller than KK, the expansion no longer applies and a hard ceiling appears: at most nn distinct symbols are observed in nn samples, so

H^≤log⁡min⁡(n,K).\hat H \le \log \min(n, K).

With K=1000K = 1000 equiprobable symbols (H=6.91H = 6.91 nats) and n=100n = 100 samples, plug-in cannot exceed 4.614.61. Miller-Madow adds at most (n−1)/(2n)<0.5(n - 1)/(2n) < 0.5 nats: not enough. There are estimators for this regime:

  • Bayesian. A fixed-parameter Dirichlet prior seems neutral, but for large KK it induces an extremely concentrated prior over HH, letting the prior decide the result. NSB (Nemenman, Shafee and Bialek, 2002) uses a Dirichlet mixture whose induced prior on HH is approximately flat, and works with nn of order K\sqrt{K} when the distribution is not too irregular.
  • Coverage correction (Chao-Shen): estimate the mass of unseen symbols from the fraction seen once (the Good-Turing idea) and rescale.
  • Unseen-part estimators. Valiant and Valiant (2011) showed that n≍K/log⁡Kn \asymp K / \log K samples suffice to estimate HH with small error, and Jiao et al. (2015) and Wu and Yang (2016) gave estimators attaining that optimal rate by approximating −tlog⁡t-t\log t with polynomials near the boundary: exactly where the previous theorem locates the difficulty.

Continuous variables: histograms and bin width

For a continuous variable with density pp, the reference quantity is differential entropy h(X)=−∫plog⁡ph(X) = -\int p \log p. The first idea is discretization: split the line into bins of width Δ\Delta, count and use plug-in.

If XΔX^\Delta is the bin index, Pj=P(XΔ=j)P_j = \Pr(X^\Delta = j) and qq is the piecewise-constant density equal to Pj/ΔP_j/\Delta in bin jj, then

H(XΔ)+log⁡Δ=−∑jPjlog⁡PjΔ=−∫plog⁡q=h(X)+KL⁡(p ∥ q).H(X^\Delta) + \log\Delta = -\sum_j P_j \log\frac{P_j}{\Delta} = -\int p \log q = h(X) + \KL(p \,\|\, q).

The natural estimator is therefore h^Δ=H^(XΔ)+log⁡Δ\hat h_\Delta = \hat H(X^\Delta) + \log\Delta, and its error has two biases of opposite sign:

  • Discretization: KL⁡(p ∥ q)≥0\KL(p\,\|\,q) \ge 0, which for a smooth density is of order Δ2\Delta^2. It pushes upward and grows with Δ\Delta.
  • Sampling: plug-in over Kef≈(rango)/ΔK_{\text{ef}} \approx (\text{rango})/\Delta occupied bins has bias ≈−(Kef−1)/(2n)\approx -(K_{\text{ef}} - 1)/(2n). It pushes downward and grows as Δ\Delta shrinks.

An optimal width exists, depending on nn and the shape of pp, and no general rule finds it in every case. Mutual information is worse. By the data-processing inequality, I(XΔ;YΔ)≤I(X;Y)I(X^\Delta; Y^\Delta) \le I(X; Y), and discretization converges to the truth from below as Δ→0\Delta \to 0; but sampling bias is now positive, ≈(BX−1)(BY−1)/(2n)\approx (B_X - 1)(B_Y - 1)/(2n) with BB bins per axis, and grows quadratically with bin count. With 10×1010 \times 10 bins and 500 points it is 0.080.08 nats; with 30×3030 \times 30, 0.840.84. The published number depends on the histogram as much as on the data.

Kozachenko-Leonenko: entropy from distances

The alternative to discretization is to let the data choose bin size: around each point, a ball reaching exactly its kk-th nearest neighbor. Where density is high the ball is small; where low, large. The ball’s volume measures local density, and entropy is the mean of −log⁡p-\log p.

Let X1,…,Xn∼iidpX_1, \dots, X_n \iid p in Rd\R^d, fix a norm whose unit ball has volume cdc_d (Euclidean: cd=πd/2/Γ(d/2+1)c_d = \pi^{d/2}/\Gamma(d/2 + 1); maximum: cd=2dc_d = 2^d), and let ρi\rho_i be the distance from XiX_i to its kk-th nearest neighbor among the other n−1n - 1 points.

The derivation has an exact step and an approximate one; keep them separate.

Exact step. Let PiP_i be the probability mass of ball B(Xi,ρi)B(X_i, \rho_i). Conditional on XiX_i, the other n−1n - 1 points are independent, and the ball reaching its kk-th neighbor contains exactly k−1k - 1 of them in its interior. That ball’s mass has the same distribution as the kk-th smallest of n−1n - 1 uniforms on [0,1][0, 1] (map each point Xj↦X_j \mapsto mass of the ball centered at XiX_i reaching XjX_j, which is uniform): a Beta⁡(k,n−k)\operatorname{Beta}(k, n - k). For U∼Beta⁡(a,b)U \sim \operatorname{Beta}(a, b), E[log⁡U]=ψ(a)−ψ(a+b)\E[\log U] = \psi(a) - \psi(a + b), hence

E[log⁡Pi]=ψ(k)−ψ(n).\E[\log P_i] = \psi(k) - \psi(n).

Approximate step. If density is nearly constant inside the ball, Pi≈p(Xi) cd ρidP_i \approx p(X_i)\, c_d\, \rho_i^d. Rearranging,

−log⁡p(Xi)≈−log⁡Pi+log⁡cd+dlog⁡ρi,-\log p(X_i) \approx -\log P_i + \log c_d + d\log\rho_i,

and averaging over ii, with E[−log⁡Pi]=ψ(n)−ψ(k)\E[-\log P_i] = \psi(n) - \psi(k), gives the formula. Entropy is E[−log⁡p(X)]\E[-\log p(X)], so the estimator averages an estimate of −log⁡p-\log p at each point. All bias comes from local uniformity: it is small where density is smooth at the scale of ρi\rho_i and large in tails, near support boundaries and in high dimensions, where neighbor distances become similar (a nearest-neighbor ball in R20\R^{20} is not “local” in any useful sense). Under regularity conditions, h^KL\hat h_{\mathrm{KL}} is consistent for fixed kk; bias falls as a power of k/nk/n whose exponent worsens with dd.

The parameter kk is the only tuning choice. With small kk the ball is local (low bias) but the estimator noisy; with large kk, the reverse holds. Common values are 3 to 10, and neighbor search uses a kd-tree in O(nlog⁡n)\bigO(n \log n) in low dimension.

KSG: mutual information with canceling biases

Continuous-variable mutual information is I(X;Y)=h(X)+h(Y)−h(X,Y)I(X; Y) = h(X) + h(Y) - h(X, Y). The obvious approach applies Kozachenko-Leonenko three times with the same kk. It works poorly: each term has its own bias at a different scale (the joint-space kk-th neighbor is much farther away than in either marginal), and biases do not cancel. When XX and YY are independent, the difference of three noisy estimates is not zero.

Kraskov, Stögbauer and Grassberger (2004) proposed using the same scale in all three terms. Use the maximum norm in joint space, ∥(x,y)−(x′,y′)∥=max⁡(∥x−x′∥,∥y−y′∥)\norm{(x, y) - (x', y')} = \max(\norm{x - x'}, \norm{y - y'}), whose ball is the product of marginal balls (also maximum-norm), so cdX+dY=cdXcdYc_{d_X + d_Y} = c_{d_X} c_{d_Y}.

Why it works. Apply Kozachenko-Leonenko to h(X,Y)h(X, Y) with kk neighbors and radius εi\varepsilon_i. For h(X)h(X), use the same radius εi\varepsilon_i at each point, containing nx(i)n_x(i) points in xx space: it is approximately the distance to neighbor number nx(i)+1n_x(i) + 1, so instead of fixing kk and measuring distance, fix distance and count kk. Do the same for h(Y)h(Y). Subtracting,

h^(X)+h^(Y)−h^(X,Y)=[ψ(n)−ψ(nx+1)‾+log⁡cdX+dXlog⁡ε‾]+[ψ(n)−ψ(ny+1)‾+log⁡cdY+dYlog⁡ε‾]−[ψ(n)−ψ(k)+log⁡cdX+dY+(dX+dY)log⁡ε‾],\hat h(X) + \hat h(Y) - \hat h(X, Y) = \Big[\psi(n) - \overline{\psi(n_x + 1)} + \log c_{d_X} + d_X\overline{\log\varepsilon}\Big] + \Big[\psi(n) - \overline{\psi(n_y + 1)} + \log c_{d_Y} + d_Y\overline{\log\varepsilon}\Big] - \Big[\psi(n) - \psi(k) + \log c_{d_X + d_Y} + (d_X + d_Y)\overline{\log\varepsilon}\Big],

where the bar denotes the mean over ii. Volumes and logarithms of distances cancel exactly, along with most local-uniformity bias, incurred at the same scale εi\varepsilon_i in all three terms. What remains is algorithm 1’s formula, depending only on counts. Algorithm 2 uses the rectangular box radius in each marginal (largest ∥xj−xi∥\norm{x_j - x_i} and largest ∥yj−yi∥\norm{y_j - y_i} among the kk neighbors, separately), giving ψ(k)−1/k+ψ(n)−ψ(nx)+ψ(ny)‾\psi(k) - 1/k + \psi(n) - \overline{\psi(n_x) + \psi(n_y)}; it has slightly less bias and slightly more variance.

InteractiveNeighbors that measure information
  • point ii
  • joint box: kk neighbors
  • strip ∣x−xi∣<εi\abs{x - x_i} < \varepsilon_i
  • strip ∣y−yi∣<εi\abs{y - y_i} < \varepsilon_i
Mean KSG estimate (4 samples of n=150n = 150, k=3k = 3) versus true II
012345012345True I (nats)
  • exact
  • KSG, mean of 4 samples
  • sample above
1.00
3
150
εi\varepsilon_i (box half-side)…
nx(i)n_x(i) in vertical strip…
ny(i)n_y(i) in horizontal strip…
Point ii contribution…
KSG I^\hat I (mean of nn)…
Exact −12log⁡(1−ρ2)-\tfrac12\log(1-\rho^2)1.000
Correlation ρ\rho0.930
A cloud of nn points from a two-dimensional Gaussian with mutual information II and correlation ρ=1−e−2I\rho = \sqrt{1 - e^{-2I}}. Hover over or touch any point: the magenta box reaches its kk-th joint neighbor, and the orange and aqua strips are what KSG counts in each marginal. A narrow cloud gives small boxes with full strips, and that is information. Below, mean estimate versus truth: with I≤2I \le 2 it is nearly exact, but above 3 nats the curve bends. Increase nn from 150 to 400: at I=5I = 5 about seven tenths of a nat are recovered, and closing the entire gap requires thousands of points.

What the figure shows, and what is known more generally:

  • Excellent near independence. The strips contain points they meet by chance, and the estimator is centered at 0 with very little bias: its main advantage over histogram plug-in.
  • It falls short under strong dependence. When the cloud is almost a curve, each point’s box is tiny but still square while the density is an even narrower ribbon: within the box density varies greatly (high on the curve and almost zero at corners), and local uniformity fails in all three terms at once. Gao, Ver Steeg and Galstyan (2015) showed KSG and related estimators need a sample count growing exponentially with true information, and proposed local corrections (LNC) that mitigate this in low dimensions.
  • Dimension is the enemy. In the lab, with X,Y∈R20X, Y \in \R^{20}, I=1I = 1 nat and n=1000n = 1000, KSG returns about two tenths of a nat. Local-uniformity bias no longer cancels.
  • Choosing kk. Increasing kk reduces variance and increases bias. Kraskov et al. recommend k=2k = 2 to 44 for estimation, and larger values for testing independence, where bias matters less than noise.

Before continuing, implement the algorithm as written: it will be a reference for the rest of the lesson.

CodeKSG estimator, algorithm 1
Implement ksg_mi(x, y, k=3), accepting x of shape (n,) or (n, dx) and y of shape (n,) or (n, dy), and returning the KSG estimate (algorithm 1) of I(X;Y)I(X; Y) in nats. Use the maximum norm in joint and marginal spaces, count nx(i)n_x(i) and ny(i)n_y(i) with strict inequality, and always exclude the point itself. Use NumPy and distance matrices (no trees); scipy.special.digamma is allowed. Tests compare against a reference implementation on small samples and Gaussians with known information.
import numpy as np
from scipy.special import digamma

def ksg_mi(x, y, k=3):
  """Estimación KSG (algoritmo 1) de I(X; Y) en nats."""
  x = np.asarray(x, dtype=float).reshape(len(x), -1)
  y = np.asarray(y, dtype=float).reshape(len(y), -1)
  n = len(x)
  # tu código: distancias del máximo en x, en y y conjuntas; eps_i del k-ésimo vecino conjunto;
  # recuentos estrictos n_x(i), n_y(i); y la fórmula con digamma
  return 0.0
Shift+Enter to run

Variational bounds: learning a critic

Nearest-neighbor estimators collapse in high dimensions. But in high dimensions we have something we did not before: neural networks able to learn functions of many variables. The idea is to turn mutual information into an optimization problem whose optimum is II and whose value for any candidate is a bound.

Samples from the product of marginals come for free from a batch of pairs: (xi,yj)(x_i, y_j) with i≠ji \neq j is an independent pair. All bounds compare what the critic sees on the diagonal (true pairs) with off-diagonal observations (shuffled pairs).

Barber-Agakov: a decoder

Since I(X;Y)=H(X)−H(X∣Y)I(X; Y) = H(X) - H(X \given Y) and conditional entropy is the minimum cross-entropy, any decoder q(x∣y)q(x \given y) gives a bound:

The proof is one line using KL divergence, and you will do it in the exercises. Its advantage is stability: it is cross-entropy, the most studied learning problem. Its drawback is that it requires knowing H(X)H(X), which occurs only when you design XX (a label with known distribution, a message in a channel) or when XX is discrete and H(X)H(X) is well estimated; and for continuous variables, a high-dimensional density decoder is as difficult as the original problem.

Donsker-Varadhan and MINE

The Donsker-Varadhan KL variational representation says that, for distributions PP and QQ,

KL⁡(P ∥ Q)=sup⁡T{EP[T]−log⁡EQ[eT]}.\KL(P \,\|\, Q) = \sup_{T} \Big\{ \E_P[T] - \log\E_Q[e^T] \Big\}.

The “≥\ge” inequality for each TT is the Gibbs variational principle: with density g=eTq/EQ[eT]g = e^T q / \E_Q[e^T], directly verify KL⁡(P ∥ Q)−EP[T]+log⁡EQ[eT]=KL⁡(P ∥ G)≥0\KL(P\,\|\,Q) - \E_P[T] + \log\E_Q[e^T] = \KL(P\,\|\,G) \ge 0, with equality at T=log⁡( ⁣dP/ ⁣dQ)+cT = \log(\dd P/\dd Q) + c for any constant cc. With P=pXYP = p_{XY} and Q=pX⊗pYQ = p_X \otimes p_Y,

I(X;Y)≥IDV(f)=Ep(x,y)[f(X,Y)]−log⁡Ep(x)p(y)[ef(X,Y)].I(X; Y) \ge I_{\mathrm{DV}}(f) = \E_{p(x,y)}[f(X, Y)] - \log\E_{p(x)p(y)}\big[e^{f(X, Y)}\big].

MINE (Belghazi et al., 2018) maximizes IDVI_{\mathrm{DV}} using a neural critic and batches. There is a catch: the second term is the logarithm of an expectation, estimated on a batch as the log⁡\log of a mean. By Jensen, E[log⁡Zˉ]≤log⁡E[Zˉ]\E[\log \bar Z] \le \log\E[\bar Z]: the batch estimate of IDVI_{\mathrm{DV}} is upward biased, so a particular batch is not a lower bound, and its gradient is biased too. MINE corrects the gradient by replacing denominator ef‾\overline{e^f} with a moving average of previous batches; the reported value remains biased.

NWJ: without a logarithm

To remove the logarithm, use its tangent: log⁡z≤z/e\log z \le z/e for z>0z > 0 (the tangent to log⁡\log at z=ez = e). Applied to z=EQ[ef]z = \E_Q[e^f],

I(X;Y)≥IDV(f)≥INWJ(f)=Ep(x,y)[f(X,Y)]−e−1Ep(x)p(y)[ef(X,Y)].I(X; Y) \ge I_{\mathrm{DV}}(f) \ge I_{\mathrm{NWJ}}(f) = \E_{p(x,y)}[f(X, Y)] - e^{-1}\E_{p(x)p(y)}\big[e^{f(X, Y)}\big].

This is the Nguyen, Wainwright and Jordan (2010) bound, which also follows from the ff-divergence representation with f(u)=ulog⁡uf(u) = u \log u. Both terms are now expectations: a batch mean is an unbiased estimator of INWJ(f)I_{\mathrm{NWJ}}(f), as is its gradient. The optimal critic is f∗=1+log⁡rf^* = 1 + \log r, with r=p(x,y)/(p(x)p(y))r = p(x, y)/(p(x)p(y)) the density ratio. The price is variance.

Proof

EQ[r]=1\E_Q[r] = 1 and EQ[r2]=∫p2/q=eD2(P ∥ Q)\E_Q[r^2] = \int p^2/q = e^{D_2(P\,\|\,Q)} by definition of D2D_2; Rényi divergences increase with order and order 1 is KL, so D2≥ID_2 \ge I. For the bivariate Gaussian with correlation ρ\rho, Σ=[1ρρ1]\Sigma = \begin{bmatrix} 1 & \rho \\ \rho & 1 \end{bmatrix} and Q=N(0,I)Q = \Normal(\vb{0}, \mat{I}):

∫p2q=1∣Σ∣∫e−12z⊤(2Σ−1−I)z2π ⁣dz=1∣Σ∣ ∣2Σ−1−I∣1/2=1∣Σ∣1/2∣2I−Σ∣1/2=11−ρ2,\int \frac{p^2}{q} = \frac{1}{\abs{\Sigma}}\int \frac{e^{-\frac12\vb{z}\T(2\Sigma\inv - \mat{I})\vb{z}}}{2\pi}\dd\vb{z} = \frac{1}{\abs{\Sigma}\,\abs{2\Sigma\inv - \mat{I}}^{1/2}} = \frac{1}{\abs{\Sigma}^{1/2}\abs{2\mat{I} - \Sigma}^{1/2}} = \frac{1}{1 - \rho^2},

because Σ\Sigma and 2I−Σ2\mat{I} - \Sigma have eigenvalues 1±ρ1 \pm \rho and 1∓ρ1 \mp \rho. Since I=−12log⁡(1−ρ2)I = -\frac12\log(1 - \rho^2), this is e2Ie^{2I}. With dd independent pairs of coordinates, factors multiply and equality remains.

∎

Estimating 1010 nats with standard deviation 0.10.1 in that term would require m≈e20/0.01≈5×1010m \approx e^{20}/0.01 \approx 5\times 10^{10} pairs. Song and Ermon (2020) proved this explosion affects all estimators in the family and proposed SMILE, clipping efe^f to [e−τ,eτ][e^{-\tau}, e^{\tau}]: lower variance in exchange for bias.

InfoNCE: classify the correct pair

The most widely used bound in representation learning begins with a classification question. Take a batch of KK pairs (xi,yi)∼iidp(x,y)(x_i, y_i) \iid p(x, y). For each xix_i there are KK candidates y1,…,yKy_1, \dots, y_K, only one paired with it. A critic ff scores each combination and a softmax classifier tries to guess the correct one.

Proof

One anchor, say x1x_1, suffices because the KK terms have the same distribution. Reformulate the batch as an experiment: an index cc uniform on {1,…,K}\{1, \dots, K\}, yc∼p(y∣x1)y_c \sim p(y \given x_1) and the other yj∼p(y)y_j \sim p(y) independent; call D=(x1,y1,…,yK)D = (x_1, y_1, \dots, y_K). By Bayes’ rule, the index posterior is

p(c=i∣D)=r(x1,yi)∑jr(x1,yj),r(x,y)=p(y∣x)p(y),p(c = i \given D) = \frac{r(x_1, y_i)}{\sum_j r(x_1, y_j)}, \qquad r(x, y) = \frac{p(y \given x)}{p(y)},

because the likelihood of DD given c=ic = i is p(x1)p(yi∣x1)∏j≠ip(yj)=p(x1)∏jp(yj)⋅r(x1,yi)p(x_1)p(y_i \given x_1)\prod_{j \neq i} p(y_j) = p(x_1)\prod_j p(y_j) \cdot r(x_1, y_i).

First inequality. The InfoNCE term is log⁡K+log⁡qf(c∣D)\log K + \log q_f(c \given D), with qfq_f the softmax of logits. Expected cross-entropy is never less than conditional entropy, E[−log⁡qf(c∣D)]≥H(c∣D)\E[-\log q_f(c \given D)] \ge H(c \given D), so

INCE(f)≤log⁡K−H(c∣D)=H(c)−H(c∣D)=I(c;D).I_{\mathrm{NCE}}(f) \le \log K - H(c \given D) = H(c) - H(c \given D) = I(c; D).

Second. Since log⁡p(c∣D)−log⁡p(c)=log⁡r(x1,yc)−log⁡(1K∑jr(x1,yj))\log p(c \given D) - \log p(c) = \log r(x_1, y_c) - \log\big(\frac1K\sum_j r(x_1, y_j)\big), taking expectations,

I(c;D)=E[log⁡r(x1,yc)]−E[log⁡1K∑jr(x1,yj)]=I(X;Y)−KL⁡(PD ∥ QD),I(c; D) = \E[\log r(x_1, y_c)] - \E\Big[\log \tfrac1K\textstyle\sum_j r(x_1, y_j)\Big] = I(X; Y) - \KL(P_D \,\|\, Q_D),

where PDP_D is the distribution of DD (with cc marginalized) and QD=p(x1)∏jp(yj)Q_D = p(x_1)\prod_j p(y_j) that of a batch with no pair: their ratio is exactly 1K∑jr(x1,yj)\frac1K\sum_j r(x_1, y_j). Since KL is nonnegative, I(c;D)≤I(X;Y)I(c; D) \le I(X; Y). With f=log⁡r+b(x)f = \log r + b(x), qfq_f is the exact posterior and the first inequality is equality. You will prove the ≤log⁡K\le \log K bound in the exercises.

∎

The proof explains the ceiling: InfoNCE does not measure I(X;Y)I(X; Y), but how much information the batch has about which pair is correct, at most the entropy of a uniform index among KK, log⁡K\log K. If I(X;Y)=10I(X; Y) = 10 nats and K=256K = 256, even the best critic gives at most 5.555.55. In return, InfoNCE has very little variance: it is an average of log-softmax values, bounded above.

InteractiveThe InfoNCE ceiling
024681012I = 0I = 2I = 4I = 6I = 8I = 10training step (nats on vertical axis)log K
  • InfoNCE
  • NWJ
  • MINE (DV)
  • true II
  • log⁡K\log K
Batch size KK
Critic
Visible bounds
Current step: true II0 nats
Ceiling log⁡K\log K4.16
InfoNCE (mean ± sd)…
NWJ (mean ± sd)…
MINE (DV) (mean ± sd)…
Training: step 0 of 1500. The dashed staircase is the true information.
The Poole et al. (2019) experiment in your browser: Gaussian X,Y∈R20X, Y \in \R^{20} whose mutual information rises in steps from 0 to 10 nats. Three quadratic critics f(x,y)=a x⊤y+b(∥x∥2+∥y∥2)+cf(x, y) = a\,x\T y + b(\norm{x}^2 + \norm{y}^2) + c, a family containing the optimal critic, are trained with Adam, each with its own bound, on batches of KK pairs. Thin line: batch bound at each step; thick: moving average. InfoNCE (blue) sticks to log⁡K\log K with minimal variance; NWJ (orange) rises higher but jumps by several nats, and a batch with enormous efe^f can depress it for dozens of steps; MINE (purple) rises further and oscillates. Switch to the optimal critic: the InfoNCE ceiling remains because it belongs to the bound, not training, and batch-evaluated MINE overestimates.

There is a continuum between the extremes. Poole et al. (2019) showed InfoNCE and NWJ are cases of a single family of multi-sample bounds, interpolating between them (the α\alpha bound) to trade bias for variance. In representation learning remember the warning of Tschannen et al. (2020): the success of contrastive losses is not explained by maximizing mutual information (with invertible encoders it is maximal and constant), but by the inductive bias of critic and architecture. InfoNCE is a good loss; as an estimator of II, it works only below log⁡K\log K.

Fundamental limits

The InfoNCE ceiling, NWJ’s eIe^{I} variance and KSG’s need for eIe^{I} samples are not three accidents. McAllester and Stratos (2020) showed they are the same phenomenon:

The intuition concerns tails. Large II means log⁡r\log r is large on true pairs, meaning those pairs have tiny probability, of order e−Ie^{-I}, under the product of marginals. To certify this one must rule out product-of-marginals mass hiding in events the sample never saw, and NN samples only explore events of probability down to ∼1/N\sim 1/N. A bound valid for all distributions cannot go beyond log⁡N\log N (plus a constant and log⁡(1/δ)\log(1/\delta)).

Two practical readings. First: if a paper reports a lower bound of 2020 nats with batches of 512512, either the bound is invalid (batch MINE is), or it is not distribution-free (it uses an assumption requiring justification). Second: the theorem does not prohibit estimation; it prohibits certification. Estimators without guarantees, such as KSG or the difference of two cross-entropies proposed by the same authors, can approach large values; they cannot accompany them with an assumption-free guarantee. That is why the only defense is a benchmark with known information.

A benchmark: transformations that change nothing

Validating an estimator requires known truth. The Gaussian is the canonical benchmark: with X,Y∈RdX, Y \in \R^d and correlation ρ\rho between corresponding coordinates, I=−d2log⁡(1−ρ2)I = -\frac d2\log(1 - \rho^2). But an estimator that works on Gaussians can fail on anything else. The following property allows arbitrarily unusual distributions without changing the truth.

Proof

By data processing, I(f(X);Y)≤I(X;Y)I(f(X); Y) \le I(X; Y) because f(X)f(X) is a function of XX. And I(X;Y)=I(f−1(f(X));Y)≤I(f(X);Y)I(X; Y) = I(f\inv(f(X)); Y) \le I(f(X); Y) for the same reason. Thus they are equal; repeat with gg on the other variable.

∎

A useful consequence: if Y=f(X)Y = f(X) with invertible ff and continuous XX, then I(X;Y)=I(X;X)I(X; Y) = I(X; X), and for any quantization I(X;X)≥I(XΔ;XΔ)=H(XΔ)≈h(X)−log⁡Δ→∞I(X; X) \ge I(X^\Delta; X^\Delta) = H(X^\Delta) \approx h(X) - \log\Delta \to \infty. Mutual information is infinite. Any estimator returns a finite number growing with nn or bin count: KSG as log⁡n\log n (with Y=XY = X it gives exactly ψ(n)−ψ(k)\psi(n) - \psi(k) because each strip contains exactly the k−1k - 1 interior neighbors of the box), and a histogram as the logarithm of bin count. This is the information-plane problem in deterministic networks.

InteractiveTransform and see
Cloud (x,g(y))(x, g(y)) with g(y)=y3g(y) = y^3 and histogram grid
−50−25025−202
Estimates for all four transformations (nats)
identitycubicexponentialarctangent0.000.100.200.300.400.50
  • histogram 10 × 10
  • KSG (k=3k = 3)
  • KSG on ranks
  • true II
Transformation of YY
0.80
10
True II (independent of gg)0.511
Histogram 10×1010\times10…
KSG on data…
KSG on ranks…
Range across transformations: histogram0.000
Range across transformations: KSG0.000
With few bins the histogram is stable but downward biased (discretization loses information); increase them and the opposite bias appears.
A sample of 500 Gaussian pairs with correlation ρ\rho, and four reparameterizations of YY: identity, y3y^3, eye^y and arctan⁡(2y)\arctan(2y). True information, the dashed line, is the same in all four. Below, for all four at once, the B×BB \times B equal-width histogram (squares), KSG on data (circles) and KSG on ranks (triangles). The exponential and cubic crowd points into few bins and the histogram collapses; KSG also moves, less so. On ranks, KSG gives exactly the same number in all four rows: ranks do not change under increasing transformations.

The rank transformation (the empirical copula) cheaply inherits invariance: I(X;Y)=I(FX(X);FY(Y))I(X; Y) = I(F_X(X); F_Y(Y)) with increasing marginal distribution functions, and normalized ranks are their sample version. It removes heavy-tail and scale problems, and on ranks KSG returns the same number under any increasing reparameterization of either variable. It does not fix strong dependence or dimension. A serious benchmark (e.g. Czyż et al., 2023) combines Gaussians, transformations like these, heavy tails and increasing dimensions, reporting bias and variance in each case.

Implementation from scratch

Start with the discrete case: plug-in, Miller-Madow and a table of biases versus the first-order prediction, with 2,000 replicates per nn.

[ ]Plug-in and Miller-Madow, measuredBrowser
import numpy as np

rng = np.random.default_rng(0)

def plugin_entropy(counts):
    """Entropía plug-in (nats) a partir de recuentos; los ceros no aportan."""
    counts = np.asarray(counts, dtype=float)
    p = counts[counts > 0] / counts.sum()
    return float(-(p * np.log(p)).sum())

def miller_madow(counts):
    counts = np.asarray(counts)
    return plugin_entropy(counts) + (np.count_nonzero(counts) - 1) / (2 * counts.sum())

def plugin_filas(C):
    """Lo mismo, vectorizado: una réplica por fila."""
    n = C.sum(1, keepdims=True)
    P = C / n
    T = np.where(C > 0, -P * np.log(np.where(C > 0, P, 1.0)), 0.0)
    return T.sum(1)

for nombre, p in [("uniforme", np.full(100, 1 / 100)), ("Zipf", (1 / np.arange(1, 101)) / (1 / np.arange(1, 101)).sum())]:
    K, H = len(p), float(-(p * np.log(p)).sum())
    print(f"{nombre}: K = {K}, H = {H:.4f} nats")
    print("     n   sesgo plug-in   -(K-1)/(2n)   sesgo MM   desv. típica   techo log n")
    for n in [30, 100, 300, 1000, 10000]:
        C = rng.multinomial(n, p, size=2000)
        h = plugin_filas(C)
        hm = h + ((C > 0).sum(1) - 1) / (2 * n)
        print(f"{n:6d}   {h.mean() - H:+.4f}         {-(K - 1) / (2 * n):+.4f}       {hm.mean() - H:+.4f}    {h.std():.4f}         {np.log(n):.3f}")
    print()

# información mutua de dos variables independientes con 10 x 10 celdas
n = 200
x, y = rng.integers(0, 10, (2, 2000, n))
mi = []
for xi, yi in zip(x, y):
    c = np.zeros((10, 10))
    np.add.at(c, (xi, yi), 1)
    mi.append(plugin_entropy(c.sum(1)) + plugin_entropy(c.sum(0)) - plugin_entropy(c.ravel()))
print(f"I plug-in con X, Y independientes (10 x 10, n = {n}): media {np.mean(mi):.4f}, primer orden {81 / (2 * n):.4f}, verdad 0")

With uniform K=100K = 100, the first-order prediction is off by 2% at n=1000n = 1000 (and not at all at n=10 000n = 10\,000), 10% at n=300n = 300, and loses meaning at n=30n = 30: it predicts −1.65-1.65, but plug-in is trapped under the log⁡30=3.40\log 30 = 3.40 ceiling and its actual bias is −1.40-1.40. Miller-Madow leaves residual bias of 10−310^{-3} at n=1000n = 1000 and falls short in the undersampled regime. Also compare bias with standard deviation. For uniform data, bias is about seven times the deviation for all n≥300n \ge 300, and even more below that: since Var⁡[log⁡p(X)]=0\Var[\log p(X)] = 0, the 1/n1/\sqrt n term of the deviation vanishes and it too is order 1/n1/n. The proof’s quadratic term explains this: with pk=1/Kp_k = 1/K it equals −K2∑k(p^k−1/K)2=−χ2/(2n)-\frac{K}{2}\sum_k (\hat p_k - 1/K)^2 = -\chi^2/(2n), where χ2=nK∑k(p^k−1/K)2\chi^2 = nK\sum_k(\hat p_k - 1/K)^2 is Pearson’s statistic, approximately χK−12\chi^2_{K-1}; its mean divided by its deviation is (K−1)/2(K−1)=(K−1)/2≈7.0(K-1)/\sqrt{2(K-1)} = \sqrt{(K-1)/2} \approx 7.0. Repeating the experiment would always give “almost the same” wrong number. With Zipf, deviation is order 1/n1/\sqrt n and bias stops dominating around n=1000n = 1000.

Now the bootstrap. It estimates bias well, but the percentile interval inherits and doubles the bias. The basic (reflected) interval, [2H^−q0.975,2H^−q0.025][2\hat H - q_{0.975}, 2\hat H - q_{0.025}], corrects it to first order.

[ ]Bootstrap: bias correction and intervalsBrowser
import numpy as np

rng = np.random.default_rng(1)
K, n = 100, 300
p = np.full(K, 1 / K)
H = np.log(K)

c = rng.multinomial(n, p)
muestra = np.repeat(np.arange(K), c.astype(np.intp))   # intp: en Pyodide los índices son de 32 bits
h0, hmm = plugin_entropy(c), miller_madow(c)
boot = plugin_filas(np.array([np.bincount(rng.choice(muestra, n), minlength=K) for _ in range(2000)]))
sesgo_boot = boot.mean() - h0
q_lo, q_hi = np.quantile(boot, [0.025, 0.975])

print(f"H verdadera = {H:.4f}")
print(f"plug-in = {h0:.4f}   Miller-Madow = {hmm:.4f}   corregido por bootstrap = {h0 - sesgo_boot:.4f}")
print(f"intervalo percentil del 95 %: [{q_lo:.4f}, {q_hi:.4f}]   ¿contiene H? {q_lo <= H <= q_hi}")
print(f"intervalo básico del 95 %:    [{2 * h0 - q_hi:.4f}, {2 * h0 - q_lo:.4f}]   ¿contiene H? {2 * h0 - q_hi <= H <= 2 * h0 - q_lo}")

The percentile interval lies entirely below HH: bootstrap resamples from the empirical distribution, which has even fewer distinct symbols, shifting replicates further down. This is the margin note’s warning.

For continuous variables, Kozachenko-Leonenko and KSG use scipy.spatial.cKDTree, which searches neighbors in O(nlog⁡n)\bigO(n\log n) in low dimensions. Argument p=np.inf selects the maximum norm; np.nextafter(eps, 0) converts the radius to the greatest number below εi\varepsilon_i, enforcing strict inequality.

[ ]Kozachenko-Leonenko and KSG with kd-treesBrowser
import numpy as np
from scipy.spatial import cKDTree
from scipy.special import digamma, gammaln

def kl_entropy(X, k=3):
    """Kozachenko-Leonenko con norma euclídea, en nats."""
    X = np.asarray(X, dtype=float).reshape(len(X), -1)
    n, d = X.shape
    r = cKDTree(X).query(X, k + 1)[0][:, k]              # la columna 0 es el propio punto
    log_cd = d / 2 * np.log(np.pi) - gammaln(d / 2 + 1)   # volumen de la bola unidad
    return digamma(n) - digamma(k) + log_cd + d * np.mean(np.log(r))

def ksg(x, y, k=3):
    """KSG, algoritmo 1, con árboles kd y norma del máximo."""
    x = np.asarray(x, dtype=float).reshape(len(x), -1)
    y = np.asarray(y, dtype=float).reshape(len(y), -1)
    n = len(x)
    xy = np.hstack([x, y])
    eps = cKDTree(xy).query(xy, k + 1, p=np.inf)[0][:, k]
    r = np.nextafter(eps, 0)
    nx = cKDTree(x).query_ball_point(x, r, p=np.inf, return_length=True) - 1
    ny = cKDTree(y).query_ball_point(y, r, p=np.inf, return_length=True) - 1
    return float(digamma(k) + digamma(n) - np.mean(digamma(nx + 1) + digamma(ny + 1)))

def gauss(n, d, rho, rng):
    x = rng.standard_normal((n, d))
    return x, rho * x + np.sqrt(1 - rho**2) * rng.standard_normal((n, d))

rng = np.random.default_rng(2)
print("Kozachenko-Leonenko, gaussiana estándar en R^d (n = 2000)")
for d in [1, 2, 5, 10]:
    est = np.mean([kl_entropy(rng.standard_normal((2000, d))) for _ in range(3)])
    print(f"  d = {d:2d}: estimación {est:.3f}   verdad {d / 2 * np.log(2 * np.pi * np.e):.3f}")

print("\nInformación mutua: tres KL frente a KSG (n = 500, 10 réplicas, media ± desviación)")
print("   d    verdad    tres KL           KSG")
for d in [1, 5]:
    for I in [0.0, 1.0]:
        rho = np.sqrt(1 - np.exp(-2 * I / d))
        tres, k_ = [], []
        for _ in range(10):
            x, y = gauss(500, d, rho, rng)
            tres.append(kl_entropy(x) + kl_entropy(y) - kl_entropy(np.hstack([x, y])))
            k_.append(ksg(x, y))
        print(f"  {d:2d}    {I:.2f}     {np.mean(tres):+.3f} ± {np.std(tres):.3f}    {np.mean(k_):+.3f} ± {np.std(k_):.3f}")

Kozachenko-Leonenko is accurate in low dimension with n=2000n = 2000 and begins to deviate at dimensions 5 and 10. The “three KL” column applies the estimator separately to h(X)h(X), h(Y)h(Y) and h(X,Y)h(X, Y). In one dimension both estimates are accurate on average, but under independence KSG has less than half the dispersion. At dimension 5 the difference is qualitative: the sum of three KL estimates gives negative information for independent variables (about three tenths of a nat), because the joint term, in dimension 10, has bias the marginals do not offset; KSG stays at 0 and, under dependence, recovers more information, although not all. The price appears as dimension rises further, with information fixed at 1 nat:

[ ]KSG in increasing dimension and versus scikit-learnBrowser
import numpy as np
from sklearn.feature_selection import mutual_info_regression

rng = np.random.default_rng(3)
print("KSG con I = 1 nat repartido en d pares de coordenadas (n = 1000, dos réplicas)")
for d in [1, 2, 5, 10, 20]:
    rho = np.sqrt(1 - np.exp(-2 * 1.0 / d))
    v = [ksg(*gauss(1000, d, rho, rng)) for _ in range(2)]
    print(f"  d = {d:2d}: {v[0]:.3f}  {v[1]:.3f}")

# scikit-learn implementa KSG para una característica y un objetivo (MI por columna, no multivariante)
x, y = gauss(1000, 1, 0.9, rng)
sk = mutual_info_regression(x, y[:, 0], n_neighbors=3, random_state=0)[0]
print(f"\nrho = 0.9: verdad {-0.5 * np.log(0.19):.4f}   nuestro KSG {ksg(x, y):.4f}   scikit-learn {sk:.4f}")

# dependencia determinista: la verdad es infinita
x = rng.standard_normal(1000)
for n in [250, 1000]:
    print(f"Y = X^3, n = {n}: KSG = {ksg(x[:n], x[:n] ** 3):.3f}   psi(n) - psi(3) = {digamma(n) - digamma(3):.3f}")

mutual_info_regression matches our implementation except for details: it rescales each feature to unit variance, adds tiny noise to break ties and clips negative values to zero. But it estimates only information of each column with the target, never that of a vector. In dimension 20 with 1,000 samples KSG recovers a small fraction of the true nat. The final two lines are deterministic: with Y=X3Y = X^3 the truth is infinite and KSG returns a finite number rising about 1.41.4 nats when nn quadruples, the same log⁡4\log 4 rate as ψ(n)−ψ(3)\psi(n) - \psi(3), although below that value (which is for exactly Y=XY = X): the cubic stretches some boxes and compresses others, and strips no longer contain only the k−1k - 1 neighbors.

Finally, intervals. For neighbor estimators naive bootstrap does not work: sampling with replacement duplicates points, a duplicate has a neighbor at zero distance and the estimate blows up. The alternative is subsampling without replacement (Politis and Romano): compute the estimator on subsamples of size m<nm < n and rescale dispersion by m/n\sqrt{m/n}.

[ ]KSG intervals: bootstrap versus subsamplingBrowser
import numpy as np

rng = np.random.default_rng(4)
n, rho = 500, 0.6
verdad = -0.5 * np.log(1 - rho**2)
x, y = gauss(n, 1, rho, rng)
I_n = ksg(x, y)

boot = []
for _ in range(100):
    idx = rng.integers(0, n, n)
    boot.append(ksg(x[idx], y[idx]))
print(f"verdad {verdad:.3f}   KSG {I_n:.3f}")
print(f"bootstrap ingenuo: media {np.mean(boot):.3f}, intervalo percentil [{np.quantile(boot, 0.025):.3f}, {np.quantile(boot, 0.975):.3f}]")

m = n // 2
sub = []
for _ in range(200):
    idx = rng.choice(n, m, replace=False)
    sub.append(ksg(x[idx], y[idx]))
dev = (np.array(sub) - I_n) * np.sqrt(m / n)
lo, hi = I_n - np.quantile(dev, 0.975), I_n - np.quantile(dev, 0.025)
print(f"submuestreo (m = {m}): intervalo del 95 % [{lo:.3f}, {hi:.3f}]   ¿contiene la verdad? {lo <= verdad <= hi}")

The bootstrap mean is several times the original estimate and the interval contains neither truth nor I^\hat I. Subsampling gives a reasonable interval. It assumes the estimator fluctuates as 1/n1/\sqrt{n} around a value that changes little between mm and nn, true in low dimension with moderate dependence; with large bias (high dimension), no resampling interval detects it, and that is what the benchmark measures.

Variational bounds with the optimal critic

Before training anything, separate what is due to the critic from what is due to the bound. For Gaussians the optimal critic is a known quadratic form, so each bound can be evaluated with it. For a batch of K=128K = 128 pairs in R20\R^{20}, the cell computes the K×KK\times K matrix of critic values and all three bounds.

[ ]InfoNCE, NWJ and DV with the optimal criticBrowser
import numpy as np

rng = np.random.default_rng(5)
d, K = 20, 128

def log_r(x, y, rho):
    """Matriz K x K de log p(x_i, y_j) / (p(x_i) p(y_j)) para la gaussiana con correlación rho por coordenada."""
    xx = (x**2).sum(1)[:, None]
    yy = (y**2).sum(1)[None, :]
    return -(rho**2 * (xx + yy) - 2 * rho * (x @ y.T)) / (2 * (1 - rho**2)) - d / 2 * np.log(1 - rho**2)

def logsumexp(A, axis=None):
    M = A.max(axis=axis, keepdims=True)
    return (M + np.log(np.exp(A - M).sum(axis=axis, keepdims=True))).squeeze()

def cotas(F):
    K = len(F)
    diag, fuera = np.diag(F), F[~np.eye(K, dtype=bool)]
    nce = np.mean(diag - logsumexp(F, axis=1)) + np.log(K)
    nwj = np.mean(diag + 1) - np.exp(-1) * np.mean(np.exp(fuera + 1))   # crítico óptimo de NWJ: 1 + log r
    dv = np.mean(diag) - (logsumexp(fuera) - np.log(fuera.size))
    return nce, nwj, dv

print(f"K = {K}, log K = {np.log(K):.2f}")
print("  I verdadera    InfoNCE        NWJ             DV (en el lote)")
for I in [1, 2, 4, 6, 8, 10]:
    rho = np.sqrt(1 - np.exp(-2 * I / d))
    R = []
    for _ in range(30):
        x = rng.standard_normal((K, d))
        y = rho * x + np.sqrt(1 - rho**2) * rng.standard_normal((K, d))
        R.append(cotas(log_r(x, y, rho)))
    m, s = np.mean(R, 0), np.std(R, 0)
    print(f"  {I:5d}        {m[0]:5.2f} ± {s[0]:.2f}   {m[1]:6.2f} ± {s[1]:5.2f}   {m[2]:6.2f} ± {s[2]:.2f}")

Three facts, all with the perfect critic. InfoNCE saturates at log⁡128=4.85\log 128 = 4.85 with minimal deviation. Batch-evaluated DV overestimates at high information: the logarithm of a batch mean is downward biased, MINE’s Jensen bias. NWJ appears centered on truth (even slightly above), but its deviation grows with II. The mean of 30 batches misleads: r‾\overline{r} has expectation 1, but much of it is in a huge tail rarely sampled by a small number of batches, so in a typical batch r‾<1\overline{r} < 1 and NWJ exceeds II; the rare batch that reaches the tail depresses it. With mm independent pairs the variance of r‾\overline{r} would be (e2I−1)/m(e^{2I} - 1)/m; the K(K−1)K(K-1) off-diagonal pairs share xix_i or yjy_j and are equivalent to far fewer independent pairs.

Neural critics in PyTorch

With a neural critic the experiment approaches practical use. The next cell follows Poole et al. (2019) at laptop scale: X,Y∈R20X, Y \in \R^{20}, information rises in increments of 2 to 10 nats and each bound trains its own separable critic, f(x,y)=g(x)⊤h(y)f(x, y) = g(x)\T h(y), with gg and hh perceptrons with a direct linear connection. CLIP uses a separable critic: one pass through each branch gives the K×KK\times K matrix. For MINE, the gradient uses a moving average in the denominator. It runs on CPU in seconds; the loop is the familiar training loop, and the correspondence between formulas and tensor operations is direct (from equations to PyTorch).

[ ]MLP critics for InfoNCE, NWJ and MINE (CPU)Local GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"     # experimento pequeño: CPU
import math
import numpy as np
import torch
import torch.nn as nn

torch.manual_seed(0)
torch.set_num_threads(2)
d, K, pasos = 20, 64, 200
niveles = [2, 4, 6, 8, 10]
fuera_diag = ~torch.eye(K, dtype=torch.bool)

def lote(I):
    rho = math.sqrt(1 - math.exp(-2 * I / d))
    x = torch.randn(K, d)
    return x, rho * x + math.sqrt(1 - rho**2) * torch.randn(K, d)

class Rama(nn.Module):
    """Perceptrón con conexión lineal directa: aprende pronto la parte lineal x·y del crítico óptimo."""
    def __init__(self, ancho=64, salida=32):
        super().__init__()
        self.lin = nn.Linear(d, salida, bias=False)
        self.mlp = nn.Sequential(nn.Linear(d, ancho), nn.ReLU(), nn.Linear(ancho, ancho), nn.ReLU(), nn.Linear(ancho, salida))
    def forward(self, x):
        return self.lin(x) + self.mlp(x)

class Critico(nn.Module):
    def __init__(self):
        super().__init__()
        self.g, self.h = Rama(), Rama()
    def forward(self, x, y):
        return self.g(x) @ self.h(y).T                   # F[i, j] = f(x_i, y_j)

def infonce(F):
    return (F.diag() - F.logsumexp(dim=1)).mean() + math.log(K)

def nwj(F):
    # recorte para no desbordar float32; si llegara a actuar, ese lote ya no daría una cota válida
    return F.diag().mean() - torch.exp(torch.clamp(F[fuera_diag] - 1, max=30)).mean()

def dv(F):
    f = F[fuera_diag]
    return F.diag().mean() - (f.logsumexp(0) - math.log(f.numel()))

def entrenar(nombre, cota, lr=1e-3):
    critico = Critico()
    opt = torch.optim.Adam(critico.parameters(), lr=lr)
    log_ma, trazas = None, []
    for I in niveles:
        for _ in range(pasos):
            x, y = lote(I)
            F = critico(x, y)
            valor = cota(F)
            if nombre == "MINE":
                f = F[fuera_diag]
                lme = f.logsumexp(0) - math.log(f.numel())
                log_ma = lme.detach() if log_ma is None else torch.logaddexp(log_ma + math.log(0.99), lme.detach() + math.log(0.01))
                perdida = -(F.diag().mean() - torch.exp(lme - log_ma))   # gradiente con el denominador suavizado
            else:
                perdida = -valor
            opt.zero_grad()
            perdida.backward()
            opt.step()
            trazas.append(valor.item())
    return np.array(trazas).reshape(len(niveles), pasos)

print(f"K = {K}, log K = {math.log(K):.2f}. Media ± desviación de la segunda mitad de cada escalón:")
print("I verdadera:  " + "   ".join(f"{I:9d}" for I in niveles))
for nombre, cota in [("InfoNCE", infonce), ("NWJ", nwj), ("MINE", dv)]:
    cola = entrenar(nombre, cota)[:, pasos // 2:]
    print(f"{nombre:8s}      " + "   ".join(f"{m:5.2f}±{s:4.2f}" for m, s in zip(cola.mean(1), cola.std(1))))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With only 200 steps per increment, critics lag behind the staircase, and exact numbers depend on the seed; Poole et al. use thousands of steps per increment. The qualitative pattern is robust. InfoNCE approaches log⁡64=4.16\log 64 = 4.16 from below without passing it, with the smallest deviation of the three. NWJ is the most irregular: its deviation at high steps is measured in nats, not tenths. MINE exceeds InfoNCE at high steps but remains far from truth. Longer training brings NWJ and MINE closer to the staircase and increases their noise, while InfoNCE remains fixed at log⁡K\log K.

Common mistakes

Exercises

NumericBias in bits
An alphabet has K=100K = 100 symbols, all with positive probability, and n=1000n = 1000 samples. What is the approximate first-order bias of the plug-in entropy estimator, in bits?
NumericInformation where there is none
XX and YY are independent and uniform over 10 values each. With n=1000n = 1000 pairs, what is the approximate first-order expected plug-in mutual information I^(X;Y)\hat I(X; Y) in nats?
NumericEntropy of a quantized Gaussian
X∼N(0,1)X \sim \Normal(0, 1) is quantized in bins of width Δ=0.01\Delta = 0.01. Approximately what is discrete entropy H(XΔ)H(X^\Delta) in nats?
NumericThe required batch
You want InfoNCE to be able, at least in principle, to reach information of 1010 nats. What is the smallest integer batch size KK that allows this?
NumericThe price of NWJ
X,YX, Y are Gaussian with I(X;Y)=5I(X;Y) = 5 nats. With the optimal critic, NWJ's second term is the mean of r=p(x,y)/(p(x)p(y))r = p(x,y)/(p(x)p(y)) over mm independent pairs from the product of marginals. How many pairs give this mean standard deviation 0.10.1?
QuizInfoNCE with large information
Why must InfoNCE batch size KK increase when mutual information is large, and at what cost?
QuizAn invertible function
Let XX be continuous with a density and Y=f(X)Y = f(X) with smooth invertible ff. What is I(X;Y)I(X; Y) and what do estimators return?
QuizWhat is a valid lower bound?
With a batch of KK pairs and a critic ff fixed in advance, which batch-computed quantities have expectation less than or equal to I(X;Y)I(X;Y) for any ff?

More than one answer may be correct.

ProofThe InfoNCE ceiling
Prove: For any critic ff and any batch of KK pairs, batch InfoNCE, 1K∑ilog⁡ef(xi,yi)1K∑jef(xi,yj)\frac1K\sum_{i}\log\frac{e^{f(x_i, y_i)}}{\frac1K\sum_j e^{f(x_i, y_j)}}, does not exceed log⁡K\log K. Consequently INCE(f)≤log⁡KI_{\mathrm{NCE}}(f) \le \log K.
0
Fix index ii and write sj=f(xi,yj)s_j = f(x_i, y_j) for j=1,…,Kj = 1, \dots, K.

Step 1 of 3. How do you rewrite term ii?

ProofThe Barber-Agakov bound
Prove: For any conditional distribution q(x∣y)q(x \given y), I(X;Y)≥H(X)+Ep(x,y)[log⁡q(X∣Y)]I(X;Y) \ge H(X) + \E_{p(x,y)}[\log q(X \given Y)], with equality if and only if q(⋅∣y)=p(⋅∣y)q(\cdot \given y) = p(\cdot \given y) for almost every yy.
0
Start from I(X;Y)=H(X)−H(X∣Y)I(X;Y) = H(X) - H(X \given Y) with H(X∣Y)=−Ep(x,y)[log⁡p(X∣Y)]H(X \given Y) = -\E_{p(x,y)}[\log p(X \given Y)].

Step 1 of 3. What do you want to show about H(X∣Y)H(X \given Y)?

Summary

Key idea
Estimating information is a statistical problem whose bias does not disappear with more calculation: plug-in underestimates entropy as −(K−1)/(2n)-(K-1)/(2n), neighbors fail under strong dependence and in high dimensions, and every reliable lower bound is limited to O(log⁡n)\bigO(\log n), of which InfoNCE’s log⁡K\log K ceiling is the most visible version.
  • Plug-in entropy is downward biased (Jensen) with bias −(K−1)/(2n)+O(n−2)-(K-1)/(2n) + \bigO(n^{-2}); Miller-Madow corrects it using K^\hat K. No unbiased estimator exists, and with n<Kn < K plug-in cannot exceed log⁡n\log n. Plug-in mutual information is upward biased by (KX−1)(KY−1)/(2n)(K_X - 1)(K_Y - 1)/(2n).
  • For continuous variables, a histogram mixes discretization and sampling biases of opposite sign, and its mutual information depends on bins.
  • Kozachenko-Leonenko estimates hh from kk-th-neighbor distances: ψ(n)−ψ(k)+log⁡cd+d log⁡ρ‾\psi(n) - \psi(k) + \log c_d + d\,\overline{\log\rho}. KSG fixes the scale in joint space and cancels volumes and distances; it succeeds near independence and falls short with strong dependence and high dimension.
  • Variational bounds turn estimation into optimization with a critic: Barber-Agakov (requires H(X)H(X)), DV and MINE (batch biased), NWJ (unbiased, with variance ≥(eI−1)/m\ge (e^{I} - 1)/m) and InfoNCE (low variance, ceiling log⁡K\log K).
  • Mutual information is invariant under invertible reparameterizations; estimators are not. Always validate on a benchmark with known information, report intervals (subsampling for neighbors), and distrust any bound promising more than log⁡n\log n.