Differential entropy, Gaussians and the Gaussian channel
Extend information theory to continuous variables. Differential entropy may be negative and depends on scale, while KL divergence and mutual information retain their meaning. Derive the Gaussian maximum-entropy property, the Gaussian KL used by VAEs, Gaussian channel capacity, and water filling.
After this lesson you can
- Calculate differential entropy for uniform, exponential, Gaussian, and multivariate Gaussian distributions.
- Derive the effect of affine transformations on differential entropy and the invariance of KL divergence and mutual information.
- Prove that a Gaussian maximizes differential entropy at fixed covariance.
- Derive the KL divergence between multivariate Gaussians and its diagonal standard-normal case, and implement it with Cholesky factorization.
- Derive Gaussian channel capacity and allocate power across parallel channels by water filling.
Before you start
Motivation: when variables are real numbers
So far every random variable had a finite alphabet and its information fit in a probability table. But almost everything measured, transmitted, and modeled is continuous: a cable’s voltage, the amplitude of a radio wave, a normalized pixel, the latent vector of a variational autoencoder. Two concrete questions require us to extend the theory.
- The VAE divergence. A variational autoencoder’s regularization term is the divergence between two Gaussian densities. It is evaluated at every training step, thousands of times per second, and has a closed form that you should know how to derive and, above all, implement without numerical blow-ups in high dimensions.
- The physical channel. A signal with average power bounded by arrives contaminated by thermal noise of power : . How many bits per use can it carry reliably? The answer, , governs the design of modems, mobile networks, and satellite links.
An exact real number contains infinite information (infinitely many decimal places), so the entropy from previous lessons cannot be applied as it stands. Noise nevertheless limits what can be distinguished. For intuition, if the signal varies over and noise has standard deviation , two levels closer than are confused, and roughly distinguishable levels fit. That is bits, apart from a constant. This lesson turns that level count into an exact theorem, using three ingredients: entropy for densities, the fact that a Gaussian has the greatest entropy at equal variance, and the way divergence and mutual information survive the transition to the continuous case.
Unless stated otherwise, is the base-2 logarithm (bits) in channel formulas and the natural logarithm (nats) in Gaussian formulas; nat bits.
Differential entropy
The definition is the obvious one: replace the sum with an integral.
This is the same expected surprise as in Shannon entropy, but surprise is no longer the logarithm of a probability: is a density and can exceed 1. That is where the peculiarities arise. First consider the standard examples.
| Density | in nats | Comment |
|---|---|---|
| Uniform | maximum among densities supported on | |
| Exponential | is the rate; mean | |
| Gaussian | does not depend on | |
| Laplace with scale | variance | |
| Gaussian in | proved below |
The first three follow in one line. For the uniform density, is constant. For the exponential, and gives . For the Gaussian, and the second term has expectation .
Differential entropy can be negative, which can be surprising at first. For , bits. For a Gaussian, whenever , that is, . A highly concentrated density reaches values above 1 and its surprise is negative on average.
The effective volume interpretation makes sense of this: (with in bits) is the length of the uniform interval with the same entropy. For a uniform distribution it is exactly ; for a Gaussian, . Negative entropy means an effective volume smaller than the unit of measurement. In it is an -dimensional volume, and the channel section will show that this idea is literal: the number of elements in a typical set of samples is in the discrete case, and its volume is in the continuous case.
What is lost from the discrete case
- It can be negative, as just seen, and tends to when the distribution concentrates at a point ( if ).
- It depends on units. If is in meters and in centimeters, bits. A quantity that changes when measured in different units cannot be “the information bits of .” This is proved in general below.
- It is not the limit of . If is quantized with increasingly fine cells, grows without bound; the next section gives the exact relationship.
What survives: the chain rule, the fact that conditioning does not increase entropy (because ), and, as we will see, divergence and mutual information unchanged, with their units and meaning.
From discrete to differential entropy
Quantizing into cells of width gives a discrete variable , whose entropy is indeed the entropy of lesson 1. How is it related to ?
Proof
By the mean value theorem there is with . Then
The second sum is . The first is a Riemann sum of , which tends to . Thus .
∎This result says that is entropy relative to the unit of measurement. Asking for bits of precision () costs bits: is the cost of describing to precision 1, and each extra bit of precision costs exactly one bit. An infinitely precise real number costs infinitely many bits because , not because does. The figure shows all this together and adds what motivates the next section: a second variable , with Gaussian noise of standard deviation .
What to take away:
- Each bit of precision costs one bit. Halving increases by almost exactly 1 bit (a line with slope in ), while flattens at . For the standard Gaussian and , and , within bits of .
- Stretching shifts but not information. With the magenta curve moves to : . Mutual information converges to the same value, bits for the Gaussian, whatever . With coarse cells the curves differ (with the variable is resolved more finely relative to its scale), but the limit is the same. For the bimodal mixture it is and for the uniform distribution .
- can be negative; never can. For the uniform distribution and the interval has length and bits, and the magenta curve falls below zero with fine cells; meanwhile, quantized mutual information is discrete mutual information and never falls below .
- The mixture has no closed form: its is computed numerically (the figure’s tool uses an integral). This is a case of “no formula exists” that recurs in common mistakes.
What is invariant: transformations, divergence, and mutual information
The second point in the figure follows from a change of variables. If with a diffeomorphism, the density is , with the Jacobian (this is the change-of-variables formula).
Proof
We prove the fourth, which includes the others. Since ,
For the Jacobian is constant, .
∎The interpretation is in terms of volume: applying multiplies volumes by and adds to entropy. In case 4, the term is the mean logarithm of the local expansion factor (not the logarithm of its mean), and is what a normalizing flow computes to give the likelihood of its samples.
What matters is what does not change. The two quantities defined by a ratio of densities inherit their properties without loss.
Proof
Let be the support of . Since is concave, Jensen’s inequality gives . Equality requires to be constant on (strict Jensen) and , hence . For mutual information, , and .
∎Proof
The densities of under and under carry the same Jacobian factor, which cancels in the ratio: . Divergence is the expectation under of the logarithm of that ratio, and the expectation under of the function is the expectation under of the same function evaluated at , so it does not change. For mutual information, apply the argument to the pair : the joint density and product of marginals gain the same factor .
∎That is why divergence and mutual information are the “real” objects of continuous theory. They are also limits of their discrete versions: quantizing with increasingly fine partitions, each a refinement of the previous one, gives discrete divergences and mutual informations that increase (by data processing, mutual information does not increase on grouping) toward the continuous value, which is the supremum over all partitions (Gelfand–Yaglom–Perez; see Polyanskiy and Wu). This is what the figure’s orange curve shows. In summary, measures a volume, whose units are arbitrary; and compare two volumes in the same units, which cancel.
The Gaussian maximizes entropy
Before the result, we need the entropy of a multivariate Gaussian. Let with positive definite (see the multivariate Gaussian and positive definite matrices). With the Cholesky factorization (Cholesky), with . The two preceding properties give
because (independent coordinates) and . Entropy depends only on : the volume of the covariance ellipsoid. The mean does not enter (translation).
Now the Gaussian maximum-entropy property: among all densities with a given covariance, the Gaussian is the most “spread out.”
Proof
Let be the density of . By the continuous Gibbs lemma, . Since is a degree-2 polynomial in , its expectation under depends only on second-order moments, which match those of :
Therefore , equal to the entropy of , and . Equality occurs only if , that is, .
∎We have proved more: . The entropy gap from the Gaussian is exactly the KL divergence to it. At the same scale (variance 1), the Gaussian has nats, the Laplace distribution , and the uniform distribution . No other density with variance 1 exceeds it.
Two variants used later have the same proof. If only the second moment is fixed, , we obtain (the variance is at most , and increases with Gaussian variance). Among densities supported on the maximum is uniform, while among those supported on with mean it is exponential. All are cases of the maximum-entropy principle in lesson 13, proved there with a single variational argument.
KL divergence between Gaussians
This is the formula evaluated most often in the lesson. KL divergence between multivariate Gaussians has a closed form, derived by computing the expectation of a degree-2 polynomial.
Proof
. The first logarithm averages to . For the second, , and writing , the cross term has zero expectation under , leaving
Adding: , which is the formula.
∎Two cases you will use constantly. In one dimension, with against ,
and with equal variance this becomes : against gives exactly nats. And the case that makes VAEs work: a diagonal encoder against the standard prior, , ,
Each coordinate contributes , pulling the mean toward , and , pulling the variance toward and vanishing only there (the function is convex with minimum at ). This term pushes each individual encoding toward the prior, while reconstruction pulls in the opposite direction (favoring small and well-separated means); the balance makes the set of encodings resemble a standard Gaussian without each one being standard Gaussian. This is the KL regularization of lesson 15, which recurs in the VAEs of module 19.
Asymmetry
The figure lets you manipulate the formula. Each Gaussian is controlled by three handles (the mean and the two semiaxes of the one-standard-deviation ellipse), and the trace, log-determinant, and mean terms are shown separately.
What to look for:
- A narrow ellipse inside a wide one is cheap in one direction and costly in the other. With narrow and wide, is moderate: puts mass only where also has plenty. In reverse, puts mass in regions where has almost none, and the surprise there is enormous. In one dimension, with and equal means, : with it equals nats, with it equals . The cost grows linearly in when is wider, and only logarithmically when it is narrower.
- Trace and log-determinant partly offset one another. Each can be negative, but their sum, decomposed into the eigenvalues of , is . The “crossed ellipses” have the same determinant (zero log-determinant) and still have a large trace: volume agrees, orientation does not.
- The mean term uses the covariance of the second argument. measures the distance between means using the Mahalanobis metric of ; in it uses that of . Only with the same covariance do the terms agree, and then .
- The Monte Carlo estimator, the mean of over the samples from , converges to the formula (the lower readout) with error of order . Having a closed form is a luxury of Gaussians.
Implementation from scratch
First check numerically the claims about differential entropy: closed forms against numerical integration, the mixture with no formula, convergence under quantization, and the effect of rescaling.
import numpy as np
from scipy import integrate, stats
def h_numerica(pdf, cortes):
"""h(X) = -∫ f ln f dx en nats, por cuadratura adaptativa entre los puntos de corte."""
def integrando(x):
f = pdf(x)
return -f * np.log(f) if f > 0 else 0.0
return sum(integrate.quad(integrando, a, b, limit=200)[0] for a, b in zip(cortes[:-1], cortes[1:]))
casos = {
"N(0, 1)": (stats.norm(0, 1).pdf, [-12, 0, 12], 0.5 * np.log(2 * np.pi * np.e)),
"N(0, 0.1^2)": (stats.norm(0, 0.1).pdf, [-1.2, 0, 1.2], 0.5 * np.log(2 * np.pi * np.e * 0.1**2)),
"Exp(1)": (stats.expon().pdf, [0, 5, 60], 1.0),
"Exp(2)": (stats.expon(scale=0.5).pdf, [0, 3, 30], 1 - np.log(2)),
"Laplace(b=1)": (stats.laplace().pdf, [-60, 0, 60], 1 + np.log(2)),
"U(0, 1/8)": (lambda x: 8.0, [0, 1 / 8], np.log(1 / 8)),
}
print("densidad numérica cerrada (nats) cerrada (bits)")
for nombre, (pdf, cortes, cerrada) in casos.items():
print(f"{nombre:13s} {h_numerica(pdf, cortes):9.5f} {cerrada:9.5f} {cerrada / np.log(2):9.5f}")
# una mezcla de dos gaussianas no tiene forma cerrada: integración numérica frente a Monte Carlo
mezcla = lambda x: 0.5 * stats.norm(-1.2, 0.55).pdf(x) + 0.5 * stats.norm(1.2, 0.55).pdf(x)
h_mezcla = h_numerica(mezcla, [-8, 0, 8])
rng = np.random.default_rng(0)
x = np.where(rng.random(200_000) < 0.5, rng.normal(-1.2, 0.55, 200_000), rng.normal(1.2, 0.55, 200_000))
mc = -np.mean(np.log(mezcla(x)))
var = 1.2**2 + 0.55**2
print(f"\nmezcla: h numérica = {h_mezcla:.4f}, Monte Carlo = {mc:.4f} nats; cota de la gaussiana con su varianza = {0.5 * np.log(2 * np.pi * np.e * var):.4f}")
# cuantización de N(0, 1): H(X_Δ) + log2 Δ converge a h(X) en bits
h_bits = 0.5 * np.log2(2 * np.pi * np.e)
print(f"\nh(N(0,1)) = {h_bits:.5f} bits")
for D in [1, 0.5, 0.25, 0.125, 0.0625]:
k = np.arange(-int(8 / D) - 1, int(8 / D) + 2)
p = np.diff(stats.norm.cdf(k * D))
p = p[p > 0]
H = -np.sum(p * np.log2(p))
print(f" Δ = {D:6.4f}: H(X_Δ) = {H:7.4f} H + log2 Δ = {H + np.log2(D):.5f}")
# cambio de escala: h(aX) = h(X) + ln a
for a in [0.1, 3.0]:
h_a = 0.5 * np.log(2 * np.pi * np.e * a**2)
print(f"h(N(0,{a}^2)) - h(N(0,1)) = {h_a - 0.5 * np.log(2 * np.pi * np.e):.5f} ln a = {np.log(a):.5f}")Integration reproduces the closed forms to five digits. The two negative values are expected: nats and bits. The bimodal mixture has no formula, but numerical integration ( nats) and the Monte Carlo estimate () agree, and both lie below the Gaussian bound with the same variance (), as the theorem requires. In quantization, each time is halved, rises bit (from to ) and converges to . Scaling confirms (with , ).
Now KL between Gaussians. The naive formula with np.linalg.inv and np.linalg.det is correct in low dimensions, but a good implementation forms neither the inverse nor the determinant. With (Cholesky):
The first two follow from and the cyclic property of trace; the third follows because is the product of its diagonal. Instead of inversion, solve triangular systems.
import numpy as np
from scipy.linalg import cholesky, solve_triangular
from scipy import stats
def kl_gauss(mu0, S0, mu1, S1):
"""D( N(mu0, S0) || N(mu1, S1) ) en nats, con Cholesky: sin inversas ni determinantes explícitos."""
mu0, mu1 = np.asarray(mu0, float), np.asarray(mu1, float)
n = mu0.size
L0 = cholesky(S0, lower=True)
L1 = cholesky(S1, lower=True)
M = solve_triangular(L1, L0, lower=True) # L1^{-1} L0
traza = np.sum(M ** 2) # tr(S1^{-1} S0) = ||L1^{-1} L0||_F^2
z = solve_triangular(L1, mu1 - mu0, lower=True)
maha = z @ z # (mu1-mu0)^T S1^{-1} (mu1-mu0)
logdet = 2 * (np.sum(np.log(np.diag(L1))) - np.sum(np.log(np.diag(L0))))
return 0.5 * (traza + maha - n + logdet)
print("D(N(1,1) || N(0,1)) =", kl_gauss([1], [[1]], [0], [[1]]), "(esperado 0.5)")
rng = np.random.default_rng(0)
n = 5
def spd():
A = rng.normal(size=(n, n))
return A @ A.T + 0.5 * np.eye(n)
mu0, mu1, S0, S1 = rng.normal(size=n), rng.normal(size=n), spd(), spd()
# 1) contra la fórmula ingenua (inversa y determinante explícitos)
S1i, d = np.linalg.inv(S1), mu1 - mu0
ingenua = 0.5 * (np.trace(S1i @ S0) + d @ S1i @ d - n + np.log(np.linalg.det(S1) / np.linalg.det(S0)))
# 2) contra Monte Carlo: media de ln p(x) - ln q(x) con x ~ p
x = rng.multivariate_normal(mu0, S0, size=200_000)
lr = stats.multivariate_normal(mu0, S0).logpdf(x) - stats.multivariate_normal(mu1, S1).logpdf(x)
print(f"Cholesky = {kl_gauss(mu0, S0, mu1, S1):.5f} ingenua = {ingenua:.5f} Monte Carlo = {lr.mean():.5f} ± {lr.std() / np.sqrt(lr.size):.5f}")
print(f"asimetría: D(p||q) = {kl_gauss(mu0, S0, mu1, S1):.4f}, D(q||p) = {kl_gauss(mu1, S1, mu0, S0):.4f}")
# 3) el caso del VAE: codificador diagonal frente a N(0, I)
mu, sigma = np.array([0.5, -1.0]), np.array([0.8, 1.5])
vae = 0.5 * np.sum(sigma ** 2 + mu ** 2 - 1 - np.log(sigma ** 2))
print(f"VAE: fórmula diagonal = {vae:.5f}, Cholesky = {kl_gauss(mu, np.diag(sigma ** 2), np.zeros(2), np.eye(2)):.5f}")
# 4) alta dimensión: el determinante explícito se desborda, el log-determinante por Cholesky no
d = 200
S, I = 0.01 * np.eye(d), np.eye(d)
with np.errstate(divide="ignore"):
ingenua = 0.5 * (np.trace(I @ S) - d + np.log(np.linalg.det(I) / np.linalg.det(S)))
exacta = d * 0.5 * (0.01 - 1 - np.log(0.01))
print(f"d = {d}: det(0.01 I) = {np.linalg.det(S)}, KL ingenua = {ingenua}, KL Cholesky = {kl_gauss(np.zeros(d), S, np.zeros(d), I):.3f} (exacta {exacta:.3f})")
# 5) varianza del estimador Monte Carlo con p = N(0, 0.25 I), q = N(0, I) al crecer la dimensión
n_mc = 1000
print(" d KL exacta desv. del estimador error relativo")
for d in [1, 10, 100, 1000]:
xs = rng.normal(0.0, 0.5, size=(n_mc, d))
lp = -0.5 * np.sum(xs ** 2 / 0.25 + np.log(2 * np.pi * 0.25), axis=1)
lq = -0.5 * np.sum(xs ** 2 + np.log(2 * np.pi), axis=1)
r = lp - lq
kl = d * 0.5 * (0.25 - 1 - np.log(0.25))
print(f"{d:4d} {kl:10.3f} {r.std() / np.sqrt(n_mc):17.4f} {r.std() / np.sqrt(n_mc) / kl:14.4f}")The three evaluations agree: with Cholesky and the naive formula, and with 200 000 Monte Carlo samples (within two standard errors). Asymmetry is real even in this random example: and . The VAE case gives with both the diagonal formula and Cholesky. In dimension with , the determinant is , below the smallest representable value: np.linalg.det returns exactly 0.0 and the naive formula gives inf, while Cholesky sums logarithms and yields , the exact value. This is the number-one mistake in this topic (see common mistakes).
The last block contains a useful observation. The absolute Monte Carlo estimator error grows as ( in to in ), because the log ratio is a sum of independent terms, but relative error falls as ( to ), because KL grows as . For high-dimensional Gaussians the estimator is not what fails: the naive formula is. Monte Carlo is used when there is no formula (mixtures, flows), in which case estimator variance depends on the shape of the density ratio; with Gaussians, the closed form is always better.
The Gaussian channel
Return to the physical problem. The channel of lesson 9 had finite alphabets; here input and output are real, and input must be limited, because without a power constraint enormous amplitudes could separate levels arbitrarily far, giving infinite capacity.
Proof
With and independent of , , because given , is a translation of . Therefore , and is fixed. It remains to bound . Since , , and by the maximum-entropy theorem (second-moment variant), . Subtracting,
With , is Gaussian with the maximum allowed variance, and the bound is attained.
∎The proof has a clear skeleton: , noise sets a fixed floor and power limits a ceiling, attained if and only if the output is Gaussian. Since a sum of independent variables is Gaussian only if both are Gaussian, Gaussian input is the unique optimum. The figure compares Gaussian input with others of the same power.
Three things to read in the figure:
- An input with points saturates at bits, however high the SNR. With 2 points (binary modulation), information at 10 dB is bits, and capacity . With 4 and 8 points it rises further, but the limit remains. Capacity keeps growing without bound, and no finite constellation attains it at high SNR.
- At high SNR, a uniform input (bounded support) loses bits. This is the limiting gap, which is at 20 dB and at 30 dB. It is dB of power: the “shaping gain” and the reason modern modulation designs use probabilistic constellations that mimic a Gaussian.
- With Gaussian input, the output is the dashed curve. With any other input, output entropy is less than that of a Gaussian with the same variance (by maximum entropy), and since is unchanged, information falls by exactly that difference.
Geometric interpretation: counting spheres
The theorem gives information capacity; that it is also the largest rate for communication with arbitrarily small error is the Gaussian channel coding theorem (Cover and Thomas, theorem 9.1.1), obtained using the same techniques as lesson 10: random Gaussian codebooks and joint-typicality decoding. We do not reproduce it, but the geometric argument explains the formula, and is the level count from the motivation carried out in .
In uses, a codeword has , and noise has by the law of large numbers. The output falls, with nearly orthogonal to in high dimension, inside the ball of radius . For error-free decoding, noise balls of radius around codewords cannot overlap. Since the volume of a ball of radius in is proportional to , the number of words satisfies
This is no coincidence with the previous proof: it is the same proof. A typical set of samples with density has volume (the continuous version of asymptotic equipartition, with the same proof and the law of large numbers applied to ). Typical output occupies volume and each noise ball ; their ratio is . Mutual information is the logarithm (per sample) of the number of noise balls that fit in the output.
Regimes and robustness
- High SNR. : each 6.02 dB (four times the power) gains one bit, and each 3.01 dB half a bit. From to , and dB, capacity is , , , and bits per use: it grows as the logarithm of power.
- Low SNR. , linear in power. With , bits and the approximation gives . Here power buys bits at a constant rate; this is the deep-space-link regime.
- The Shannon limit. If is energy per bit and noise has spectral density (so per real sample), a rate bits per sample requires and , that is . As the ratio tends to : reliable communication below dB is impossible, however little is sent. With it requires dB.
Proof
Let and . Conditioning reduces entropy and is translation-invariant, so . By maximum entropy, , and whatever the distribution of . Therefore .
∎This is a design guarantee: with Gaussian input, the information crossing the channel does not decrease if the actual noise has another distribution with the same variance. The operational version also holds: a random Gaussian codebook decoded by minimum Euclidean distance, the decoder designed for Gaussian noise, achieves any rate below with any i.i.d. noise of variance independent of the input (Lapidoth, 1996). That is why noise is modeled as Gaussian when nothing else is known: it is the pessimistic assumption.
Parallel channels and water filling
A real channel often decomposes into independent channels with different noise levels: the subcarriers of an OFDM signal (each frequency is attenuated differently), antennas of a MIMO system after singular-value decomposition, or principal components of colored noise. We have channels , with independent , and total power to allocate. How much power should each receive?
Intuition says power should go to clean channels, but not just one: returns diminish (the logarithm is concave). The exact answer comes from convex optimization.
Proof
Reduction. Since the noises are independent, and , hence , with and the scalar channel inequality for each . Equality is attained with independent Gaussian inputs of powers . What remains is an allocation problem.
Optimization. The objective is concave in and the constraints are linear, so the KKT conditions are necessary and sufficient. With the Lagrangian (in nats, which does not change the optimum)
stationarity gives . If , and (the same for all active channels). If , gives , that is . Both cases are . The function is continuous, increasing, and piecewise linear, equals at , and tends to , so exists and is unique. Since capacity grows with power, constraint is active.
∎The image explains the name: the bottom of a vessel has height in channel and an amount of water is poured in; the water rises to a common level , and its depth in each channel is . Channels with stay dry. There is an economic interpretation: the marginal benefit of an extra watt in channel is bits, and the optimum equalizes it across active channels at ; a dry channel would yield less even for its first watt. That number is the multiplier of the constraint and also the slope of the capacity curve: .
With noise levels and : first try one active channel (, which exceeds , so it is insufficient), then two (, valid). The allocation is and capacity bits, versus with uniform allocation. A common mistake is to assume all three are active: this gives and , a negative power exposing the error.
What to look for in the figure:
- Activation follows increasing noise levels, and each new channel activates just as the level reaches its bottom. With the initial configuration (), the second channel activates at , the third at , the fourth at , and the fifth at (in each case, with the noise of the activating channel).
- Uniform allocation is worse, especially at low power: with it loses bits out of (). With very large the level exceeds all bottoms and the optimum approaches uniform allocation (with , versus ).
- Marginal value is the same in active channels. This makes the KKT equation visible: water has a single level.
In practice the same result governs power allocation among OFDM subcarriers; in MIMO, with singular-value decomposition , the parallel channels have effective noise ( are the singular values); and with colored noise of covariance water filling is performed over the eigenvalues of . The last case connects with module 12: under Gaussian noise, maximizing the information of a linear projection leads to principal components.
The algorithm uses bisection on and is verified with a generic optimizer and the KKT conditions:
import numpy as np
from scipy.optimize import minimize
def water_filling(ruido, P, tol=1e-13):
"""Potencias óptimas, nivel de agua nu y capacidad (bits por uso) de canales gaussianos paralelos."""
N = np.asarray(ruido, float)
lo, hi = N.min(), N.max() + P # en lo no hay agua; en hi sobra: la suma supera P
while hi - lo > tol * hi:
nu = 0.5 * (lo + hi)
if np.maximum(nu - N, 0).sum() > P:
hi = nu
else:
lo = nu
nu = 0.5 * (lo + hi)
p = np.maximum(nu - N, 0)
return p, nu, 0.5 * np.sum(np.log2(1 + p / N))
ruido, P = np.array([0.5, 1, 2, 4, 8]), 6.0
p, nu, C = water_filling(ruido, P)
uniforme = np.full(5, P / 5)
C_unif = 0.5 * np.sum(np.log2(1 + uniforme / ruido))
print(f"nivel nu = {nu:.4f} potencias = {np.round(p, 4)} suma = {p.sum():.4f}")
print(f"capacidad: agua = {C:.4f} bits, uniforme = {C_unif:.4f} bits (pierde {C - C_unif:.4f})")
# verificación con un optimizador genérico (SLSQP) sobre el simplex de potencias
neg_cap = lambda q: -0.5 * np.sum(np.log2(1 + np.maximum(q, 0) / ruido))
res = minimize(neg_cap, uniforme, method="SLSQP", bounds=[(0, None)] * 5, constraints=[{"type": "eq", "fun": lambda q: q.sum() - P}])
print(f"SLSQP: potencias = {np.round(res.x, 4)} capacidad = {-res.fun:.4f}")
# condiciones KKT: el valor marginal 1/(2 ln2 (N_i + P_i)) es el mismo en los canales activos y menor en los secos
marginal = 1 / (2 * np.log(2) * (ruido + p))
print("valor marginal por canal:", np.round(marginal, 4), " 1/(2 ln2 nu) =", round(1 / (2 * np.log(2) * nu), 4))
# la pendiente de C(P) es el valor marginal: derivada numérica
dP = 1e-4
print(f"dC/dP numérica = {(water_filling(ruido, P + dP)[2] - water_filling(ruido, P - dP)[2]) / (2 * dP):.5f}")
# capacidad frente a la potencia: canales que se van activando
print("\n P activos agua uniforme")
for P_ in [0.25, 0.5, 1, 2, 4, 8, 16, 32]:
q, v, c = water_filling(ruido, P_)
cu = 0.5 * np.sum(np.log2(1 + P_ / 5 / ruido))
print(f"{P_:5.2f} {int(np.sum(q > 0)):6d} {c:8.4f} {cu:8.4f}")With the level is and the powers : three channels active and the two noisiest dry, with capacity bits versus for uniform allocation. SLSQP, which does not know the structure, reaches the same value with powers agreeing to two decimals. The marginal value is in the three active channels (equal to and the numerical derivative ), and and in the dry ones, smaller values: the KKT inequality condition. The final table shows channels activating as increases.
The library version
scipy.stats.multivariate_normal already computes Gaussian entropy, and in PyTorch KL divergence between distributions is one call. In VAEs, the diagonal formula is evaluated by hand on the log-variance output by the network, because parameterizing with prevents negative variance:
import torch
from torch.distributions import Normal, MultivariateNormal, kl_divergence
mu, logvar = torch.tensor([0.5, -1.0]), torch.log(torch.tensor([0.8, 1.5]) ** 2)
# a mano, sobre la log-varianza (la forma habitual en un VAE): 1/2 sum(mu^2 + exp(lv) - 1 - lv)
kl_manual = 0.5 * torch.sum(mu**2 + logvar.exp() - 1 - logvar)
# con torch.distributions (gaussiana diagonal: un lote de Normal univariantes, una por coordenada)
q = Normal(mu, (0.5 * logvar).exp())
p = Normal(torch.zeros(2), torch.ones(2))
kl_torch = kl_divergence(q, p).sum()
# gaussianas completas: usa Cholesky por dentro (scale_tril)
Sigma = torch.diag(logvar.exp())
kl_full = kl_divergence(MultivariateNormal(mu, covariance_matrix=Sigma), MultivariateNormal(torch.zeros(2), torch.eye(2)))
print(kl_manual.item(), kl_torch.item(), kl_full.item()) # 0.88768 las tres
All three forms give the same value, . Two practical details. kl_divergence(Normal, Normal) returns a tensor per coordinate, and you must sum over the latent dimension (and average over the batch): confusing this scales regularization by . Parameterizing by log-variance makes the gradient with respect to equal to , stable and without singularities at , while parameterizing by gives , which blows up.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which inequality is used, and with which two densities?
Step 1 of 4. How does the problem reduce to one dimension?
water_filling(noise, P), which takes noises noise (a vector of positive numbers) and total power P and returns (p, C): the optimal allocation p (a vector of length ) and capacity C in bits per use, . The allocation must satisfy with . It must work with P = 0, repeated noise levels, one channel, and noises in any order.import numpy as np
def water_filling(noise, P):
"""Reparto óptimo de potencia entre canales gaussianos paralelos. Devuelve (p, C) con C en bits."""
N = np.asarray(noise, dtype=float)
# tu código: busca el nivel nu (bisección o ordenando los ruidos) y reparte p = max(nu - N, 0)
return np.zeros_like(N), 0.0Summary
- Differential entropy. . : . : . : . : . It can be negative (: bits).
- Quantization. : each bit of precision costs one bit. is entropy at precision 1.
- Transformations. ; in general, add the expected log-Jacobian. and are invariant under diffeomorphisms, and , .
- Maximum entropy. With covariance , with equality only for the Gaussian; the gap is . With : .
- KL between Gaussians. ; VAE: . Asymmetric: a narrow ellipse inside a wide one costs little in one direction and much in the other. Compute with Cholesky, not
invordet. - Gaussian channel. , : bits per use, with uniquely optimal, because with maximum . One extra bit costs 6 dB; the Shannon limit is dB; Gaussian noise is the worst. Geometrically, is the logarithm of the number of noise balls that fit in the output.
- Parallel channels. gives with (water filling, by KKT): channels with stay dry and marginal value is common.
- Practice. is not bits; units (nats or bits);
solve_triangularand log-determinants, notinvordet; sum over the latent dimension in the KL term; parameterize by log-variance; colored noise and MIMO reduce to parallel channels.