Discrete channels and capacity
Model noisy communication with a discrete memoryless channel, derive classical capacities, and compute capacity using convex optimization and Blahut–Arimoto.
After this lesson you can
- Compute capacities of binary symmetric, erasure, and symmetric channels.
- Prove mutual information concave in input and convex in the fixed-input channel.
- Derive the capacity KKT conditions.
- Implement Blahut–Arimoto with upper and lower bounds.
- Interpret capacity as information radius.
Before you start
Motivation: communicating despite noise
A bit travels through a wire, radio wave, disk surface, or memory cell and does not always arrive unchanged. Suppose each bit flips independently with probability . This binary symmetric channel is the simplest noise model, and the question is both naive and precise: how many bits of information can be sent reliably on average per channel use?
The first answer is repetition. Send each bit times and let the receiver take a majority vote. Error falls quickly, but so does rate, bits per use. The next cell quantifies it.
from math import comb, log2
eps = 0.11
h = -eps * log2(eps) - (1 - eps) * log2(1 - eps)
print(f"canal binario simétrico, eps = {eps}: C = 1 - h2(eps) = {1 - h:.4f} bits por uso")
def error_repeticion(n, eps):
"""Probabilidad de que la mayoría de n copias (n impar) llegue equivocada."""
return sum(comb(n, k) * eps**k * (1 - eps) ** (n - k) for k in range((n + 1) // 2, n + 1))
print(" n tasa 1/n error por bit")
for n in [1, 3, 5, 11, 21, 31, 51]:
print(f"{n:3d} {1 / n:8.4f} {error_repeticion(n, eps):.2e}")
n = 1
while error_repeticion(n, eps) > 1e-6:
n += 2
print(f"para bajar de 1e-6 hacen falta n = {n} copias: tasa {1 / n:.3f} bits por uso, un {1 / n / (1 - h):.1%} de C")To achieve error per bit requires 25 copies and reduces rate to bits per use. This seems the inevitable price of reliability: more safety, less information. Shannon proved in 1948 that it is not. Codes exist whose error tends to zero at a fixed positive rate arbitrarily close to a number depending only on the channel, its capacity. Here it is bits per use, about twelve times the repetition-code rate above. The theorem is the subject of lesson 10. This lesson builds what it needs and what makes the result useful: the channel model, capacity definition, exact classical capacities, tractable mathematical structure (a convex problem), and an algorithm with guarantees.
“Channel” is more general than a wire. It is any process corrupting a variable without complete recovery:
- Noisy labels. If an annotator changes true class according to a transition matrix, that matrix is a channel, and information each label retains about the true class never exceeds capacity.
- Privacy mechanisms. A randomized mechanism publishing a noisy sensitive datum is a channel; its leakage is bounded by capacity (revisited in module 30).
- Bottlenecks. A quantizer, sensor, or information-discarding network layer is a channel. Lesson 19 uses channels to describe what a representation should retain.
Blahut–Arimoto, the capacity algorithm, is a canonical example of alternating maximization with guarantees and recurs in rate–distortion theory (lesson 14) and the iterative bottleneck. Unless stated otherwise, is base-2 logarithm and information is measured in bits.
The discrete memoryless channel
A channel has input alphabet , output alphabet (both finite here), and a probabilistic rule for what output each input produces.
If the sender uses input distribution , the joint distribution is and output is the linear combination of rows
This gives a useful geometric interpretation. Each input is a point in the output-distribution simplex, and a channel is a set of points in that simplex. Noise is how close the points are: identical rows make those inputs indistinguishable to the receiver. Choosing chooses a point within the rows’ convex hull.
The channels used here are (rows are inputs):
| Channel | Parameter | Matrix | Outputs |
|---|---|---|---|
| Binary symmetric, | |||
| Erasure, | |||
| Z, | |||
| Noisy typewriter | 26 letters | each letter outputs itself or the next with probability | 26 letters |
In the erasure channel the receiver knows which positions are lost (output ), unlike the symmetric channel where flipped positions are unknown. In the Z channel is never corrupted and arrives as with probability : it models, for example, an optical detector that sometimes misses light but never confuses darkness with light.
Recall from lesson 3 that mutual information between input and output has three equivalent forms, the third governing everything here:
The last equality is the KL chain rule applied to versus product : mutual information is the average divergence between each channel row and mean output. Rows unlike the mean output (inputs easily identified by the receiver) contribute most information. Write to emphasize dependence and for divergence of row .
Capacity: maximize over the input
The channel is given, not chosen. The sender controls how to use it, namely input distribution (in practice, code design). Capacity is the best attainable value.
Here is a definition: a maximum of information. That it is also the largest communication rate with vanishing error (operational capacity) is the next lesson’s theorem. We can already check the result makes sense: it cannot exceed what fits in input or output and is zero only for a useless channel.
Proof
For every , and , since conditional entropies are nonnegative. This upper-bounds , and gives .
If all rows equal , then for every and , so . Conversely, if two rows differ, take uniform on : output is and . If both terms vanished, Gibbs’ inequality would force , contrary to assumption. Thus and .
∎Before calculating, explore a binary channel. For each channel the figure plots against and marks the maximum.
What to take from the figure and the following proofs:
- The curve is concave and has a unique maximum. At and it is zero: deterministic input communicates nothing because the receiver already knows what arrived. Concavity is proved below and makes the problem tractable.
- is a dome and a line. is linear in because each row’s entropy is independent of . In the symmetric channel the line is horizontal ( for both rows), and the maximum of matches the dome’s at . In the Z channel rows have different entropies (row has zero), so the line tilts and the maximum shifts. With it lies at .
- Uniform input is not always optimal. For Z with , uniform transmits bits and optimal . The difference is small (), but distinguishes a capacity-achieving code from one that is not.
- A channel with has maximum capacity. A channel always flipping a bit loses nothing: the receiver flips back. Capacity is , symmetric in , and vanishes at , where output is a coin independent of input.
Capacity is additive under extension
Before formulas, a property justifying “bits per use.” Using the channel times, even with correlated inputs, yields at most times capacity.
Proof
Let be any joint input distribution. Memorylessness gives and, by the entropy chain rule, , because given symbol is independent of everything else. Also . Subtracting gives . Equality is achieved by independent and identically distributed according to an optimal .
∎Thus using the channel times cannot exceed , regardless of input correlation: correlation does not help with independent noise. Lesson 10’s theorem also says is achievable with vanishing error.
Closed-form capacities
Using , classical channel capacities take a few lines. The common idea is to upper-bound and show uniform input attains it.
Proof
For each input, is a distribution on two symbols with probabilities , so regardless of . Then because is binary. With uniform output is and : the bound is attained.
∎With , and bits. Their near equality is a numerical coincidence at this , not an identity: , not .
Proof
Let indicate erasure. With probability , independently of , input is erased; otherwise . Since is a function of , : given output is deterministic, and given it is . Also . Subtraction yields , with equality for uniform .
∎The result reads cleanly: of symbols, arrive intact, each carrying at most one bit. Capacity is exactly the surviving fraction, as though the sender knew in advance which would be erased and used all survivors for data. With it is bits per use.
Symmetric channels
The symmetric-channel argument used only two properties: every row has equal entropy and uniform input yields uniform output. A broad class satisfies them.
Proof
Rows are permutations, so for every and for any . Thus . With uniform , is column ‘s sum divided by . All column sums agree and the total is , so each sum is and is uniform: and the bound is attained.
∎The Z channel: uniform input is not optimal
The Z channel is not symmetric (rows are not permutations) and shows uniform input can fail. Let . Then , (only row has uncertainty), and
This function is concave, so set its derivative to zero. With obtain , and since ,
For capacity use and (because ). The two terms containing cancel, leaving
With : , , , and bits, versus under uniform input. is always less than and, when , tends to . Intuitively is unreliable and used less than half the time; but not abandoned, because arriving certifies that was sent, and this unambiguous signal carries the most information.
Concavity and convexity: a convex optimization problem
The figure’s curve is concave. This general fact structures what follows.
Proof
(1) Write . Output is linear in . Entropy is concave because with uniform and divergence is convex in its first argument. Composition of a concave function with a linear map is concave, so is concave. The second term is linear in . Concave minus linear is concave.
(2) Use form . Let be two channels and their rowwise mixture. Each mixed row is and mixed output , with . By joint convexity of divergence,
Multiplying by and summing over yields .
∎Part two implies capacity is a maximum of functions convex in and therefore convex in the channel. Mixing two channels (a coin chooses one without the receiver knowing) never gives more capacity than their mean capacity. For example, mixing and equally gives , with , below mean capacity .
Part one matters for computation. Maximizing a concave function over the simplex, a convex set, is a convex optimization problem. Three consequences follow:
- Every local maximum is global; initialization is not a concern.
- KKT conditions are necessary and sufficient (no constraint qualification is needed because constraints are linear).
- Optimal inputs form a convex set. Even if there are several, optimal output is unique. If were optimal with outputs , mean input would have output and, since is strictly concave, ; with linear this yields , a contradiction.
Optimality conditions and information radius
Now characterize the maximum, with a clean result and geometric interpretation. First the gradient.
Proof
Differentiate with respect to : the term where contributes , and dependence of on (which is ) contributes . Since this simplifies to .
∎Two identities do the rest. The first, the compensation identity, relates mean divergence to an arbitrary point to mutual information: for every and ,
Substitute : the first term gives and the second, after summing over , . The latter divergence is nonnegative (Gibbs), so : true output minimizes mean divergence. The second identity is trivial: a weighted mean is at most the maximum, .
Proof
(1) ⇒ (2). Maximize a concave function on the simplex. Lagrangian has, by the gradient lemma, stationarity , with and (complementary slackness). For , and ; for , gives . Averaging with weights yields , hence . (If for some , the same calculation yields directional derivative when moving mass to and would not be optimal.)
(2) ⇒ (3) is immediate: is the maximum divergence and by the previous average equals .
(3) ⇒ (1). For any , the compensation identity with gives . Thus is optimal.
Radius. For any , , and achieves equality by (3): . If another also achieves maximum , compensation applied to gives , and the left side is at most . Hence and by Gibbs .
∎Condition (2) resembles “all active players are indifferent”: at optimum all used inputs transmit the same information per symbol, , and unused ones would transmit less. If an input could transmit more than per symbol, it would be worth assigning more mass. For example, in the Z channel with , optimum yields and
equal to each other and , while under uniform they are and , unequal: input “yields more” and should be used more.
Information radius
The second statement is geometric. Each row is a point of the output simplex and acts as a “distance” from point to center . Then is the radius of the smallest “ball” centered at containing every row, and capacity is the smallest possible radius, analogous to the minimum enclosing ball. Rows touching its boundary are used inputs, center is optimal output, and lies in the convex hull of used rows because it is . Since the hull lies in a simplex of dimension , Carathéodory’s theorem guarantees an optimal input using at most symbols, however many channel inputs exist.
Three points to observe:
- The figure draws the ball’s dual image. Row lies in the radius- ball centered at exactly when lies inside curve around the row. Valid centers are the intersection of these regions (shading), and minimum radius is when the intersection becomes a point. The curves are not circles: they stretch toward low row mass. The row is the first argument: divergence measures surprise of when data come from the row.
- Only boundary rows count. A row strictly inside the minimum ball (the small one in the figure, with , whose curve contains ) can move slightly without changing capacity. A “blurred” or redundant input does not help because it lies within the radius already fixed by others.
- It is a minimum-of-the-maximum problem, resembling a game. The sender chooses to maximize information; the “adversary” chooses to minimize divergence attributable to the worst input. At equilibrium () neither gains by moving: a saddle point of .
The characterization provides certificates. For any , (lower bound on ); for any , (upper bound). If bounds nearly agree, we know we are done. The next algorithm exploits this.
The Blahut–Arimoto algorithm
Computing maximizes a concave function over a simplex, so any optimizer could be used. Blahut and Arimoto independently observed in 1972 that it admits alternating maximization with closed-form steps. Introduce auxiliary variable , a “reverse channel” (a distribution over inputs for each output ), and functional
Proof
(1) Verify , with equality only if at every output with (Gibbs).
(2) Rewrite with . The final term is nonnegative and vanishes at .
∎Since , capacity is and can be maximized by alternating variables with exact block maximization (block coordinate descent, here ascent). Starting from , the best is , and then , so and . The algorithm follows:
This multiplicative update multiplies each input by and renormalizes: is multiplied by factor . Inputs with gain mass and those below lose it. Threshold is an exponential average of and by Jensen is slightly above arithmetic mean . A fixed point requires constant where : KKT equality, but not the inequality off support (every simplex vertex is a fixed point because zero mass is never regained). Thus start with full support.
Proof
(1) With we have . The step maximizes and by the lemma equals . The step gives . Also , and by information radius. gives monotonicity of .
(2) Let be optimal. Since has full support, every does too and is finite. Then
By compensation, , so the difference is , namely . Summing from to telescopes: . Since is nondecreasing, .
(3) By (2), . Every accumulation point of is optimal, and the optimal output is unique, so . If no row has (that row would have , contradicting optimality conditions), so each is continuous at and . Then and . The rest follows from (1).
∎Gap is a certificate: knowing is unnecessary to bound distance. This differs from general optimizers stopping on a small step or gradient and is the code’s criterion. The next figure shows the algorithm.
What to look for:
- Bars flatten against zero. Initially the three inputs yield differently: some above and others below. Each step moves mass toward the former, and rises. At optimum used-input bars vanish, all yielding and : KKT made visible. For the abandoned input, the bar stays below zero () and its probability approaches geometrically, with factor near per step.
- Bounds close. rises, falls, and remains between them. On a log plot the gap falls nearly linearly: convergence is geometric in these examples, much faster than provable bound . For the initial asymmetric channel, bits, the gap falls below at 19 iterations and at 84.
- Optimal input can be nonunique; output cannot. With and rows equal, only their combined mass matters; starting points reach different with the same and .
- A symmetric channel solves in one step: uniform input is already optimal, the gap is zero, and the algorithm stops.
Channels with input cost
Many real channels have unequal input costs: higher amplitude consumes more energy. Cost per symbol and budget change the problem to
Function is nondecreasing (more budget, more choices) and concave: if and are feasible for and , mixture is feasible for and is concave in . With multiplier (bits per cost unit), move to . Everything above transfers with a small change. KKT becomes on support and outside. Blahut–Arimoto retains its structure:
with bounds and on the Lagrangian value. Multiplier is slope at budget attained by the solution (where is differentiable; at a corner any intermediate slope), so sweeping traces . This anticipates the Gaussian channel in lesson 11, with continuous inputs, cost (power), and a solution yielding and power allocation (water-filling). The code checks a discrete example.
Implementation from scratch
First mutual information with support conventions (, without adding ) and Blahut–Arimoto with gap stopping. Verify against closed forms for symmetric, erasure, and Z channels, watch bounds close, check KKT for a channel with an abandoned input, and confirm a channel extension has double capacity.
import numpy as np
def info_mutua(p, W):
"""I(X;Y) en bits para la entrada p y el canal W (filas = entradas, filas suman 1)."""
p = np.asarray(p, float)
W = np.asarray(W, float)
q = p @ W
with np.errstate(divide="ignore", invalid="ignore"):
t = np.where(W > 0, W * np.log2(W / q), 0.0) # 0 log 0 = 0: solo cuentan las transiciones posibles
return float(p @ t.sum(axis=1))
def divergencias_filas(W, q):
"""D(W(.|x) || q) en bits para cada entrada x."""
with np.errstate(divide="ignore", invalid="ignore"):
t = np.where(W > 0, W * np.log2(W / q), 0.0)
return t.sum(axis=1)
def blahut_arimoto(W, tol=1e-9, max_iter=10_000):
W = np.asarray(W, float)
if W.ndim != 2 or np.any(W < 0) or not np.allclose(W.sum(axis=1), 1):
raise ValueError("W debe tener una distribución de probabilidad por fila")
p = np.full(W.shape[0], 1 / W.shape[0]) # soporte completo
historia = []
for k in range(max_iter):
q = p @ W
D = divergencias_filas(W, q)
inf = float(np.log2(np.sum(p * 2**D))) # cota inferior L_k
sup = float(D.max()) # cota superior U_k
historia.append((inf, sup))
p = p * 2**D # actualización multiplicativa
p = p / p.sum()
if sup - inf < tol: # parada por la brecha, no por el cambio en p
break
return {"C": (inf + sup) / 2, "p": p, "q": p @ W, "iter": k, "historia": historia}
def h2(x):
return -x * np.log2(x) - (1 - x) * np.log2(1 - x)
bsc = lambda e: np.array([[1 - e, e], [e, 1 - e]])
bec = lambda a: np.array([[1 - a, a, 0], [0, a, 1 - a]])
zch = lambda d: np.array([[1, 0], [d, 1 - d]])
r = blahut_arimoto(bsc(0.11)); print(f"BSC(0.11): C = {r['C']:.6f} 1 - h2 = {1 - h2(0.11):.6f} p* = {r['p']}")
r = blahut_arimoto(bec(0.3)); print(f"BEC(0.3): C = {r['C']:.6f} 1 - alfa = {0.7:.6f} p* = {r['p']}")
d = 0.5
r = blahut_arimoto(zch(d))
cerrada = np.log2(1 + 2 ** (-h2(d) / (1 - d)))
print(f"Z(0.5): C = {r['C']:.6f} cerrada = {cerrada:.6f} p* = {np.round(r['p'], 4)} iteraciones = {r['iter']}")
print(f" I(uniforme) = {info_mutua([.5, .5], zch(d)):.6f}")
for k in [0, 1, 2, 5, 10]:
inf, sup = r["historia"][k]
print(f" k = {k:2d}: {inf:.6f} <= C <= {sup:.6f} brecha {sup - inf:.1e}")
# una entrada se abandona: KKT con desigualdad en la tercera fila de la figura
W3 = np.array([[0.6, 0.3, 0.1], [0.5, 0.35, 0.15], [0.1, 0.2, 0.7]])
r = blahut_arimoto(W3)
print("\nentrada abandonada: C =", round(r["C"], 6), " p* =", np.round(r["p"], 4), " iteraciones =", r["iter"])
print(" D(W_x || q*) =", np.round(divergencias_filas(W3, r["q"]), 4), " (la segunda queda por debajo de C)")
# la extensión de un canal: C(W x W) = 2 C(W), con p* = p* x p*
W2 = np.kron(zch(0.5), zch(0.5))
r2 = blahut_arimoto(W2)
print(f"\nextensión 2ª del Z(0.5): C = {r2['C']:.6f} 2 C = {2 * cerrada:.6f} p* = {np.round(r2['p'], 4)} (0.6 x 0.6 = 0.36)")All three capacities match closed forms to six digits, and Z takes 40 iterations to close the gap below . At the gap is bits and at : roughly one order of magnitude every five steps. With an abandoned input, : the KKT inequality. The Z channel’s second extension has capacity and optimal input , the product of with itself, as additivity predicts.
Now the theorem’s rate guarantee: . To check without exact use final upper bound (at least ): if the inequality holds there, it also holds with . Monotonicity of is checked on every random channel.
import numpy as np
def divergencias_filas(W, q):
with np.errstate(divide="ignore", invalid="ignore"):
t = np.where(W > 0, W * np.log2(W / q), 0.0)
return t.sum(axis=1)
def trayectoria(W, tol=1e-9, max_iter=400):
p = np.full(W.shape[0], 1 / W.shape[0])
inf, sup = [], []
for _ in range(max_iter):
D = divergencias_filas(W, p @ W)
inf.append(np.log2(np.sum(p * 2**D)))
sup.append(D.max())
if sup[-1] - inf[-1] < tol:
break
p = p * 2**D
p = p / p.sum()
return np.array(inf), np.array(sup)
rng = np.random.default_rng(0)
peor, monotona, canales = 0.0, True, 60
for _ in range(canales):
nx, ny = rng.integers(2, 7), rng.integers(2, 7)
W = rng.dirichlet(np.ones(ny) * 0.5, nx)
L, U = trayectoria(W)
cotaC = U[-1] # U_final >= C: si la cota vale con ella, vale con C
monotona &= bool(np.all(np.diff(L) >= -1e-12))
for k in [0, 4, 19, 99]:
if k < len(L):
peor = max(peor, (cotaC - L[k]) * (k + 1) / np.log2(nx))
print(f"{canales} canales aleatorios: L_k monótona = {monotona}")
print(f"mayor valor de (U_final - L_k) (k+1) / log2|X| = {peor:.3f} (el teorema exige <= 1)")The theoretical bound holds with wide margin. It is a sublinear worst-case bound; practical convergence is much faster.
Using libraries
scipy.optimize solves the same problem without exploiting structure. Parameterize input with softmax to eliminate the simplex constraint and maximize with BFGS. Gradient with respect to follows from the lemma: with . Compare with Blahut–Arimoto on a random channel, counting function evaluations because Pyodide’s clock is unreliable.
import numpy as np
from scipy.optimize import minimize
from scipy.special import softmax
def divergencias_filas(W, q):
with np.errstate(divide="ignore", invalid="ignore"):
t = np.where(W > 0, W * np.log2(W / q), 0.0)
return t.sum(axis=1)
def info_mutua(p, W):
return float(p @ divergencias_filas(W, p @ W))
def blahut_arimoto(W, tol=1e-10, max_iter=20_000):
p = np.full(W.shape[0], 1 / W.shape[0])
for k in range(max_iter):
D = divergencias_filas(W, p @ W)
inf, sup = np.log2(np.sum(p * 2**D)), D.max()
p = p * 2**D
p = p / p.sum()
if sup - inf < tol:
break
return (inf + sup) / 2, k + 1
def menos_info(theta, W):
return -info_mutua(softmax(theta), W)
def menos_info_grad(theta, W):
p = softmax(theta)
g = divergencias_filas(W, p @ W) - np.log2(np.e)
return -(p * (g - p @ g))
rng = np.random.default_rng(3)
W = rng.dirichlet(np.ones(8) * 0.4, 8)
C_ba, n_ba = blahut_arimoto(W)
print(f"Blahut-Arimoto: C = {C_ba:.10f} iteraciones = {n_ba} (con certificado: brecha < 1e-10)")
res = minimize(menos_info, np.zeros(8), args=(W,), jac=menos_info_grad, method="BFGS", options={"gtol": 1e-10})
print(f"BFGS con gradiente: C = {-res.fun:.10f} evaluaciones = {res.nfev} error = {abs(-res.fun - C_ba):.1e}")
p_bfgs = softmax(res.x)
certificado = divergencias_filas(W, p_bfgs @ W).max() - info_mutua(p_bfgs, W)
print(f" certificado a posteriori para la p de BFGS: max_x D - I(p) = {certificado:.1e}")
res = minimize(menos_info, np.zeros(8), args=(W,), method="BFGS")
print(f"BFGS sin gradiente: C = {-res.fun:.10f} evaluaciones = {res.nfev} error = {abs(-res.fun - C_ba):.1e}")The result is nuanced. BFGS with analytic gradient needs about 100 evaluations versus over 1000 Blahut–Arimoto iterations on this channel (two of eight inputs are abandoned, and near optimum an abandoned input’s mass decays by factor per step, for one); without the gradient, about 600. The two BFGS values differ from Blahut–Arimoto by and . The fundamental difference is the guarantee. Blahut–Arimoto stops when gap proves the value is within of ; BFGS stops on small gradient without knowing distance. The information-radius certificate works for any , including BFGS output: evaluate , which is worth always doing. Here it is of order , far looser than actual error, because softmax never brings abandoned inputs to zero and gradient barely pushes them. Each method has a place: Blahut–Arimoto is short, robust (no step size or risk of leaving the simplex), and has a built-in certificate; a second-order optimizer may be faster on large channels when the former drags.
Finally, an input-cost example. Four amplitude levels with discretized Gaussian noise (standard deviation levels) and cost , “energy.” Sweep multiplier and show curve .
import numpy as np
def divergencias_filas(W, q):
with np.errstate(divide="ignore", invalid="ignore"):
t = np.where(W > 0, W * np.log2(W / q), 0.0)
return t.sum(axis=1)
def ba_coste(W, b, s, tol=1e-9, max_iter=20_000):
"""max_p I(p) - s E_p[b(X)] por Blahut-Arimoto con coste. Devuelve p, I(p), E[b]."""
p = np.full(W.shape[0], 1 / W.shape[0])
for _ in range(max_iter):
D = divergencias_filas(W, p @ W) - s * b
inf, sup = np.log2(np.sum(p * 2**D)), D.max()
p = p * 2**D
p = p / p.sum()
if sup - inf < tol:
break
I = float(p @ divergencias_filas(W, p @ W))
return p, I, float(p @ b)
niveles = np.arange(4.0)
W = np.exp(-((niveles[None, :] - niveles[:, None]) ** 2) / (2 * 0.7**2))
W /= W.sum(axis=1, keepdims=True)
b = niveles**2
print(" s (bits/coste) coste medio C(beta) p*")
curva = []
for s in [0, 0.05, 0.1, 0.2, 0.4, 0.8]:
p, I, coste = ba_coste(W, b, s)
curva.append((coste, I))
print(f" {s:4.2f} {coste:7.3f} {I:7.4f} {np.round(p, 3)}")
curva = sorted(curva)
pend = [(curva[i + 1][1] - curva[i][1]) / (curva[i + 1][0] - curva[i][0]) for i in range(len(curva) - 1)]
print("pendientes de la curva (decrecen: C(beta) es cóncava):", np.round(pend, 3))With (no cost), the solution mainly uses extreme levels and , easiest to distinguish, yielding bits at mean cost . Increasing reduces both cost and information, but information falls much more slowly: at mean cost (84% less energy), bits still get through. Slopes decrease as concavity requires, each between values of the two points joined: the multiplier is the slope of .
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How does depend on ?
Step 1 of 4. For fixed , how do you prove maximizes ?
channel_capacity(W, tol=1e-9, max_iter=20000) with Blahut–Arimoto (in bits). W is the channel matrix (one input per row, rows summing to 1); return (C, p), where C is the midpoint of bounds and from the last iteration and p the resulting input distribution. Stop when tol (not on change in p), mask zeros of W (no nan or epsilons), and raise ValueError if rows do not sum to 1. Handle repeated rows, useless inputs, unreachable outputs (zero columns), and zero-capacity channels.import numpy as np
def channel_capacity(W, tol=1e-9, max_iter=20000):
"""Capacidad (bits) de un canal W por Blahut-Arimoto. Devuelve (C, p)."""
W = np.asarray(W, dtype=float)
# tu código: valida W, itera p -> p * 2**D / suma y para con la brecha U - L
return 0.0, np.zeros(W.shape[0])Summary
- Channel. Row-stochastic matrix ; memorylessness means noise acts symbolwise, . Each row is a point in the output simplex.
- Capacity. , with . Bounds: ; it is additive under extension, . Operational meaning (maximum rate with vanishing error) is lesson 10’s theorem.
- Closed forms. : . : . Weakly symmetric channels: with uniform input. Z channel: with .
- Convexity. is concave in and convex in ; hence is convex in the channel, every local maximum is global, and optimal output is unique.
- KKT and radius. . Optimal has on support and outside, and : the smallest KL ball containing rows. An optimal input uses at most symbols.
- Blahut–Arimoto. , with , and gap stopping . It is block ascent on with exact maximization per block.
- With cost. is concave and nondecreasing; multiplier , slope of , enters the update as . This anticipates the Gaussian channel.
- Practice. Mask zeros rather than add epsilons; rows sum to 1 (not columns); stop on gap, not ; distinguish bits from nats.