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
- 07Shannon entropyKullback-Leibler divergence (relative entropy)Mutual informationCross-entropyDifferential entropyVariational representations of divergences
- 05Bias of an estimatorMean squared error bias-variance decompositionNonparametric bootstrapBootstrap percentile and basic intervals
- 11KD-trees and ball trees
- 15Micro framework to PyTorch correspondence
- 00Canonical training and evaluation loop
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 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 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 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, is the natural logarithm and all quantities are in nats; divide by to convert to bits.
The plug-in estimator and its bias
Let be discrete with distribution and . With counts and frequencies , the natural approach is substitution:
The plug-in estimator is consistent: almost surely and is continuous on the simplex, so . The issue is the rate and the sign of the error. Since is concave and , Jensen’s inequality gives
The plug-in estimator always underestimates entropy, for any and any . 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 with , which satisfies and . Expand each term around :
Since , the linear term has zero expectation and . Summing,
The remainder contains moments of order 3 and higher of , which are ; the rigorous calculation (Harris, 1975) separately controls the event that some approaches 0, where is not differentiable, and which has exponentially small probability because is fixed. For the variance the linear term suffices (delta method): , a mean of independent variables with variance .
∎Three consequences to remember:
- Bias depends on , not . With and it is nats regardless of the entropy. It scales as , while standard deviation scales as : for moderate and large , bias dominates error.
- Miller-Madow replaces with because is unknown (symbols with tiny are never seen). It removes almost all bias when and falls short otherwise.
- Mutual information inherits the sum of the three biases, with positive sign. With full supports, the first-order term of is . Two independent variables appear dependent: with and , expected information is about nats when the truth is 0. It is no coincidence that is the independence-test statistic, which under the null is approximately with degrees of freedom and exactly that mean.
No unbiased estimator
Can a cleverer formula remove bias entirely? No.
Proof
For any , is a polynomial of degree at most in . Restrict it to the edge , : this gives a polynomial with bounded derivative on . But restricted to that edge is binary entropy , with as . Thus , and is biased for some .
∎The argument says something subtler: an estimator with samples only “sees” degree- 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 is comparable to or smaller than , the expansion no longer applies and a hard ceiling appears: at most distinct symbols are observed in samples, so
With equiprobable symbols ( nats) and samples, plug-in cannot exceed . Miller-Madow adds at most nats: not enough. There are estimators for this regime:
- Bayesian. A fixed-parameter Dirichlet prior seems neutral, but for large it induces an extremely concentrated prior over , letting the prior decide the result. NSB (Nemenman, Shafee and Bialek, 2002) uses a Dirichlet mixture whose induced prior on is approximately flat, and works with of order 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 samples suffice to estimate with small error, and Jiao et al. (2015) and Wu and Yang (2016) gave estimators attaining that optimal rate by approximating 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 , the reference quantity is differential entropy . The first idea is discretization: split the line into bins of width , count and use plug-in.
If is the bin index, and is the piecewise-constant density equal to in bin , then
The natural estimator is therefore , and its error has two biases of opposite sign:
- Discretization: , which for a smooth density is of order . It pushes upward and grows with .
- Sampling: plug-in over occupied bins has bias . It pushes downward and grows as shrinks.
An optimal width exists, depending on and the shape of , and no general rule finds it in every case. Mutual information is worse. By the data-processing inequality, , and discretization converges to the truth from below as ; but sampling bias is now positive, with bins per axis, and grows quadratically with bin count. With bins and 500 points it is nats; with , . 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 -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 .
Let in , fix a norm whose unit ball has volume (Euclidean: ; maximum: ), and let be the distance from to its -th nearest neighbor among the other points.
The derivation has an exact step and an approximate one; keep them separate.
Exact step. Let be the probability mass of ball . Conditional on , the other points are independent, and the ball reaching its -th neighbor contains exactly of them in its interior. That ball’s mass has the same distribution as the -th smallest of uniforms on (map each point mass of the ball centered at reaching , which is uniform): a . For , , hence
Approximate step. If density is nearly constant inside the ball, . Rearranging,
and averaging over , with , gives the formula. Entropy is , so the estimator averages an estimate of at each point. All bias comes from local uniformity: it is small where density is smooth at the scale of and large in tails, near support boundaries and in high dimensions, where neighbor distances become similar (a nearest-neighbor ball in is not “local” in any useful sense). Under regularity conditions, is consistent for fixed ; bias falls as a power of whose exponent worsens with .
The parameter is the only tuning choice. With small the ball is local (low bias) but the estimator noisy; with large , the reverse holds. Common values are 3 to 10, and neighbor search uses a kd-tree in in low dimension.
KSG: mutual information with canceling biases
Continuous-variable mutual information is . The obvious approach applies Kozachenko-Leonenko three times with the same . It works poorly: each term has its own bias at a different scale (the joint-space -th neighbor is much farther away than in either marginal), and biases do not cancel. When and 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, , whose ball is the product of marginal balls (also maximum-norm), so .
Why it works. Apply Kozachenko-Leonenko to with neighbors and radius . For , use the same radius at each point, containing points in space: it is approximately the distance to neighbor number , so instead of fixing and measuring distance, fix distance and count . Do the same for . Subtracting,
where the bar denotes the mean over . Volumes and logarithms of distances cancel exactly, along with most local-uniformity bias, incurred at the same scale 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 and largest among the neighbors, separately), giving ; it has slightly less bias and slightly more variance.
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 , nat and , KSG returns about two tenths of a nat. Local-uniformity bias no longer cancels.
- Choosing . Increasing reduces variance and increases bias. Kraskov et al. recommend to 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.
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 in nats. Use the maximum norm in joint and marginal spaces, count and 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.0Variational 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 and whose value for any candidate is a bound.
Samples from the product of marginals come for free from a batch of pairs: with 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 and conditional entropy is the minimum cross-entropy, any decoder 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 , which occurs only when you design (a label with known distribution, a message in a channel) or when is discrete and 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 and ,
The “” inequality for each is the Gibbs variational principle: with density , directly verify , with equality at for any constant . With and ,
MINE (Belghazi et al., 2018) maximizes 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 of a mean. By Jensen, : the batch estimate of 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 with a moving average of previous batches; the reported value remains biased.
NWJ: without a logarithm
To remove the logarithm, use its tangent: for (the tangent to at ). Applied to ,
This is the Nguyen, Wainwright and Jordan (2010) bound, which also follows from the -divergence representation with . Both terms are now expectations: a batch mean is an unbiased estimator of , as is its gradient. The optimal critic is , with the density ratio. The price is variance.
Proof
and by definition of ; Rényi divergences increase with order and order 1 is KL, so . For the bivariate Gaussian with correlation , and :
because and have eigenvalues and . Since , this is . With independent pairs of coordinates, factors multiply and equality remains.
∎Estimating nats with standard deviation in that term would require pairs. Song and Ermon (2020) proved this explosion affects all estimators in the family and proposed SMILE, clipping to : 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 pairs . For each there are candidates , only one paired with it. A critic scores each combination and a softmax classifier tries to guess the correct one.
Proof
One anchor, say , suffices because the terms have the same distribution. Reformulate the batch as an experiment: an index uniform on , and the other independent; call . By Bayes’ rule, the index posterior is
because the likelihood of given is .
First inequality. The InfoNCE term is , with the softmax of logits. Expected cross-entropy is never less than conditional entropy, , so
Second. Since , taking expectations,
where is the distribution of (with marginalized) and that of a batch with no pair: their ratio is exactly . Since KL is nonnegative, . With , is the exact posterior and the first inequality is equality. You will prove the bound in the exercises.
∎The proof explains the ceiling: InfoNCE does not measure , but how much information the batch has about which pair is correct, at most the entropy of a uniform index among , . If nats and , even the best critic gives at most . In return, InfoNCE has very little variance: it is an average of log-softmax values, bounded above.
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 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 , it works only below .
Fundamental limits
The InfoNCE ceiling, NWJ’s variance and KSG’s need for samples are not three accidents. McAllester and Stratos (2020) showed they are the same phenomenon:
The intuition concerns tails. Large means is large on true pairs, meaning those pairs have tiny probability, of order , under the product of marginals. To certify this one must rule out product-of-marginals mass hiding in events the sample never saw, and samples only explore events of probability down to . A bound valid for all distributions cannot go beyond (plus a constant and ).
Two practical readings. First: if a paper reports a lower bound of nats with batches of , 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 and correlation between corresponding coordinates, . 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, because is a function of . And for the same reason. Thus they are equal; repeat with on the other variable.
∎A useful consequence: if with invertible and continuous , then , and for any quantization . Mutual information is infinite. Any estimator returns a finite number growing with or bin count: KSG as (with it gives exactly because each strip contains exactly the interior neighbors of the box), and a histogram as the logarithm of bin count. This is the information-plane problem in deterministic networks.
The rank transformation (the empirical copula) cheaply inherits invariance: 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 .
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 , the first-order prediction is off by 2% at (and not at all at ), 10% at , and loses meaning at : it predicts , but plug-in is trapped under the ceiling and its actual bias is . Miller-Madow leaves residual bias of at 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 , and even more below that: since , the term of the deviation vanishes and it too is order . The proof’s quadratic term explains this: with it equals , where is Pearson’s statistic, approximately ; its mean divided by its deviation is . Repeating the experiment would always give “almost the same” wrong number. With Zipf, deviation is order and bias stops dominating around .
Now the bootstrap. It estimates bias well, but the percentile interval inherits and doubles the bias. The basic (reflected) interval, , corrects it to first order.
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 : 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 in low dimensions. Argument p=np.inf selects the maximum norm; np.nextafter(eps, 0) converts the radius to the greatest number below , enforcing strict inequality.
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 and begins to deviate at dimensions 5 and 10. The “three KL” column applies the estimator separately to , and . 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:
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 the truth is infinite and KSG returns a finite number rising about nats when quadruples, the same rate as , although below that value (which is for exactly ): the cubic stretches some boxes and compresses others, and strips no longer contain only the 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 and rescale dispersion by .
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 . Subsampling gives a reasonable interval. It assumes the estimator fluctuates as around a value that changes little between and , 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 pairs in , the cell computes the matrix of critic values and all three bounds.
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 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 . The mean of 30 batches misleads: 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 and NWJ exceeds ; the rare batch that reaches the tail depresses it. With independent pairs the variance of would be ; the off-diagonal pairs share or 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: , information rises in increments of 2 to 10 nats and each bound trains its own separable critic, , with and perceptrons with a direct linear connection. CLIP uses a separable critic: one pass through each branch gives the 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).
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))))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 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 .
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 3. How do you rewrite term ?
Step 1 of 3. What do you want to show about ?
Summary
- Plug-in entropy is downward biased (Jensen) with bias ; Miller-Madow corrects it using . No unbiased estimator exists, and with plug-in cannot exceed . Plug-in mutual information is upward biased by .
- For continuous variables, a histogram mixes discretization and sampling biases of opposite sign, and its mutual information depends on bins.
- Kozachenko-Leonenko estimates from -th-neighbor distances: . 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 ), DV and MINE (batch biased), NWJ (unbiased, with variance ) and InfoNCE (low variance, ceiling ).
- 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 .