Cross-entropy 2026-10-14
Cross-entropy measures the average logarithmic loss incurred when outcomes follow one probability distribution , but a model assigns probabilities using another probability distribution . For a finite alphabet, write their probability mass functions as and . With base-two logarithms,
The expectation is under the true or stipulated source law , rather than the model . Terms with contribute nothing. If but for any outcome, the cross-entropy is : the model rules out an event that can occur. The result is measured in bits; natural logarithms give nats.
The useful identity is cross-entropy equals entropy plus relative entropy:
The source's information entropy is the baseline uncertainty. The Kullback-Leibler divergence is the extra average cost of a mismatched model, with the true law first and model second. Thus optimizing for a fixed reduces the mismatch, rather than changing the source's own uncertainty. For finite alphabets, the minimum is , attained exactly at .
Take a three-symbol source with . A matched binary prefix code assigns , , , with lengths . A mismatched prefix code instead assigns , , , with lengths , corresponding to . Both prefix codes decode exactly, but the most common symbol is shorter in the matched code. Under the same source ,
The mismatched code costs an extra (1/4) bit per source symbol on average. No information is lost; the penalty is inefficient representation of this source. The mismatch penalty in lossless coding explains when this coding interpretation is exact.
Figure 1.
Two lossless prefix codes have different average lengths for the same source
. Both sets of codewords are prefix codes. The source probabilities are fixed at . Each colored contribution is source probability times codeword length; changing which symbol receives the shortest word increases the total from to bits per source symbol. Details.
Cross-entropy is also useful when evaluating a predictive distribution. A report that places tiny probability on the realized outcome receives a large logarithmic loss, even when it usually predicts the most common outcome correctly. The loss convention is the negative of the reward convention in the logarithmic scoring rule. Its expected loss is uniquely minimized by the correct probability distribution, making it a strictly proper scoring rule. Strictly Proper Scoring Rules, Prediction, and Estimation by Tilmann Gneiting and others treats this connection in §3.1, Example 3; its discussion uses rewards, so the signs are reversed for the losses here.[ref]
I. J. Good's Rational Decisions by I. J. Good appeared in 1952. Its published summary describes a method for encouraging accurate probability estimates and a connection with information theory. Strictly Proper Scoring Rules, Prediction, and Estimation by Tilmann Gneiting and others traces the logarithmic scoring rule at least as far back as this 1952 paper.[ref]
Deflate 2026-10-13
Deflate is the lossless source coding method specified for PNG compression. It can describe repeated stretches of earlier data, going beyond the single-value repetitions of run-length encoding.[ref]
The format combines Deflate backreferences, which describe repeated stretches, with Deflate Huffman coding, which represents the resulting instructions using prefix codes. Deflate block framing tells the decoder which codes apply and where decoding stops. RFC 1951, DEFLATE Compressed Data Format Specification version 1.3 (May 1996), defines the format; different encoders can choose different instructions for the same input.[ref]
This separation is useful: discovering a repeated phrase and choosing short codewords solve different problems. A repeated phrase can contain many distinct bytes, while unequal codeword lengths can help even when no phrase repeats. Neither mechanism removes Deflate compression overhead or guarantees a saving on every input.
Deflate Huffman coding 2026-10-13
For a compressed block, Deflate Huffman coding uses one alphabet for Deflate literal bytes, length symbols and the end-of-block symbol, and another alphabet for distance symbols. Values 0 through 255 denote Deflate literal bytes, 256 ends the block, and 257 through 285 select lengths. A Deflate backreference is encoded as a length symbol, any length extra bits, a distance symbol, then any distance extra bits. Those extra bits select an offset within the symbol's prescribed range; they are not additional codewords.[ref]
In the illustrative Deflate backreference, length 9 uses symbol 263 and distance 3 uses symbol 2; neither needs extra bits. Under the fixed Huffman codes, A, B and C each cost eight bits, symbol 263 costs seven, and distance symbol 2 costs five. Adding the seven-bit end-of-block symbol and three-bit block header gives bits, packed into six bytes for a single final block. This is a cost calculation for the explicitly chosen instructions, not a displayed compressed stream.[ref]
Dynamic blocks transmit codeword lengths from which the decoder reconstructs the prescribed prefix codes. The code descriptions themselves use a smaller Huffman code and repeat instructions for successive codeword lengths, including runs of zero lengths. Here run-length encoding describes repeated code lengths, a separate role from copying repeated data bytes. Fixed blocks use predefined Huffman codes and avoid transmitting those descriptions.[ref]
Consider a binary Markov source with fair initial bit and flip probability . Its exact -symbol information entropy is . At ,
This includes the uncertainty of the initial bit; the entropy rate itself is bits per symbol. The finite-block difference is .
For any finite block distribution, the entropy lower bound for prefix codes gives expected codeword length , while Shannon coding achieves . These bounds apply to each block as one source symbol, without requiring consecutive blocks to be independent. Here Huffman coding on all possible 16-symbol words gives the independently calculated value bits per block, or bits per symbol. The noninteger value is an expected value; each actual codeword has an integer length. As the block length grows, the prefix code bounds squeeze towards the entropy rate when an optimal code is used.
Figure 1.
Fair marginal bits can have a lower entropy rate, with a finite-block initial cost
. The left panel shows the exact binary entropy for the symmetric binary Markov source; each individual symbol still has one bit of information entropy. Both near-persistence and near-alternation make the next symbol predictable. The right panel uses and plots , rather than literal fractional codeword lengths. The Huffman coding point is the exact expected length over all 16-symbol words. Details.
An entropy rate below one does not allow every word to fit into a shorter fixed binary word with zero error. For , all binary words are possible, so an injective fixed-length code needs at least bits. Compression instead exploits variable codeword lengths, or the vanishing-error convention in reliable source encoding at a rate. These are different guarantees.
Huffman code 2026-10-14
A Huffman code is the prefix code returned by Huffman coding; the algorithm chooses a code tree, while the code specifies the actual symbol-to-codeword assignment. For the probability distribution in symbol order , the illustrated binary tree gives
The codeword lengths are . This is a prefix code because no complete codeword is an initial segment of another complete codeword. Thus a decoder can start at the root of a tree, follow one edge per bit, emit a symbol on reaching its leaf, then restart at the root of a tree. In particular, 011010111 splits as 0 | 110 | 10 | 111 and decodes to . No separators are transmitted: the leaf tells the decoder where a codeword ends.
The expected codeword length is
bits per source symbol. Four symbols would require bits each if all codewords had the same length, so this Huffman code saves bit per symbol on average, or of that fixed-length payload. A particular message can grow: uses nine bits here instead of eight. These lengths count the encoded symbols only; transmitting a code description or message framing can add further cost.
The Kraft inequality is saturated by this Huffman code:
Its Shannon entropy is
bits per symbol, slightly below the expected codeword length . The entropy lower bound for prefix codes applies to every binary prefix code for this probability distribution. It need not be attainable with integer codeword lengths for individual symbols; Huffman coding reaches the best mean within that class. [ref]
A Huffman code need not be unique. In the first example, the tied and weights can exchange their edge labels, changing codewords but preserving their codeword lengths. Ties can also change the lengths themselves. For a second probability distribution , first merge to weight . The next merge can join with either or the subtree, since both have weight . Joining with permits , with all lengths . Joining with the subtree permits , with lengths . Both are optimal prefix codes with expected codeword length : for the latter, . Tie choices can change the code tree without changing the minimum mean.
// Target: algebra.bigb
Huffman coding Created 2026-09-24 Updated 2026-10-14
Huffman coding makes frequent symbols cheap to store by giving them short codewords, while allowing rare symbols longer codewords. For a known probability distribution on a finite alphabet with at least two positive-probability symbols, binary Huffman coding constructs a prefix code minimizing expected codeword length among binary prefix codes that encode one source symbol at a time. The objective is an average under that probability distribution; it does not promise to shorten every message. Encoder and decoder must agree on the resulting Huffman code. [ref]
The construction grows a binary tree from its leaves towards its root of a tree. Start with one leaf per symbol, weighted by its probability. Repeatedly join the two currently smallest weights beneath a new parent in a rooted tree, whose weight is their sum, and replace the pair by that subtree. Include newly formed subtrees when choosing the next pair. When one tree remains, label the two outgoing edges at every internal vertex with and ; the labels on the graph path from the root of a tree to a symbol give its codeword. This is a greedy algorithm: each step makes a locally cheapest merge, yet the result is an optimal prefix code.
For a concrete example, use probabilities , , , . First join and , creating weight . The remaining weights are for , for the subtree, and for . Join the two weights to make , then join with that subtree to make . The merge weights are therefore . Each merge adds one bit to every codeword below it, so their sum is the expected codeword length: bits per source symbol. The diagram fixes the edge labels to produce the Huffman code used below.
Figure 1.
Huffman merges for probabilities 0.4, 0.3, 0.2, 0.1 and their binary codewords
. Details.
The useful insight is that choosing short codewords is a resource allocation problem: the prefix code condition constrains the available codeword lengths through the Kraft inequality. Huffman coding solves this one-symbol problem exactly for the supplied probability distribution. For repeated emissions of a memoryless classical information source, the same Huffman code can be applied symbol by symbol. More general compression can exploit dependencies or encode groups of symbols; the one-symbol optimality statement does not compare all such methods.
Huffman sibling property Created 2026-09-24 Updated 2026-10-14
For a finite source alphabet of symbols with positive weights , choose any two least weights, breaking ties arbitrarily. There exists an optimal prefix code over the binary output alphabet whose chosen symbols occupy sibling leaves in a code tree at maximum leaf depth in a code tree. Weights may be counts or probabilities: dividing every weight by gives the same minimizers. The existence statement is what makes the first merge of Huffman coding safe. It does not say that every optimal prefix code already has the chosen pair together.[ref]
An exchange makes the idea tangible. Take probabilities . The prefix code , , , has expected codeword length bits. Exchange only the symbols at their existing leaves: the available codewords and code tree shape stay fixed, but the codeword lengths in symbol order become . The new expected codeword length is bits, and the two least probabilities, those of , now occupy deepest sibling leaves in a code tree. The saving is bit per source symbol.
Figure 1.
Exchanging two leaf labels reduces expected length from 2.5 to 1.9 bits; contracting the least-probability siblings leaves cost 1.6
. Details.
Here is the short proof outline. An optimal prefix code with positive weights has a full binary tree as its code tree: suppressing a vertex with only one child shortens every codeword in that subtree and strictly reduces cost. A deepest leaf therefore has a leaf as its sibling, giving the deepest sibling property of an optimal prefix code. Put the two chosen least weights at these positions by successive exchanges of leaf labels. Moving a weight from leaf depth in a code tree to a deepest position , occupied by , changes the weighted sum by
Fix one chosen weight there, then move the other into the neighbouring deepest position; if it is already there, no exchange is needed. The prefix code condition survives because the set of codewords is unchanged. Starting from an optimal prefix code, the cost cannot decrease below the minimum, so these exchanges preserve optimality. Strictly unequal weights at unequal depths would give a strict decrease, explaining probability monotonicity of optimal prefix-code lengths. Equal weights or equal depths allow cost-neutral exchanges. [ref]
Kullback-Leibler divergence Created 2026-09-24 Updated 2026-10-14
The Kullback-Leibler divergence, also called relative entropy, compares two probability distributions in a specified order. In , observations follow and the comparison probability distribution is : the first argument supplies the averaging weights. For probability mass functions on a finite alphabet,
Here is a random variable with probability distribution . For probability density functions relative to the same measure , replace the sum by . These formulas use natural logarithms unless stated otherwise. The expected value is under , even though appears in the denominator. [ref]
Take and on two outcomes. Direct calculation gives
The second outcome contributes negatively to the first sum: assigning it more probability than does makes its individual contribution negative. Nevertheless, relative entropy nonnegativity guarantees a nonnegative total. Reversing the arguments changes both the likelihood ratio and the averaging probabilities; taking an absolute value inside the logarithm would define a different quantity.
Figure 1.
Direction changes the averaging weights; a missing outcome can make relative entropy infinite
. Details.
The units depend on the logarithm: natural logarithms give nats, whereas base-two logarithms give bits. Divide a value in nats by to obtain bits; the forward example is approximately bits. Changing the base rescales every Kullback-Leibler divergence by the same positive factor. Since the two calculated directions differ, Kullback-Leibler divergence is asymmetric and cannot be a metric. It also need not satisfy the triangle inequality. [ref]
The operational meaning is an expected penalty for using the wrong probability distribution. A prediction incurs log-loss when outcome occurs, the negative of the logarithmic scoring rule. Under , its expected value is the cross-entropy . Predicting with itself incurs information entropy , so
Thus Kullback-Leibler divergence is exactly excess expected log-loss, whenever these separate quantities are finite. [ref]
For lossless source coding, ideal codeword lengths similarly give excess expected length in bits per symbol. Actual prefix codes require integer codeword lengths; Shannon's source coding theorem explains how long blocks approach ideal per-symbol lengths. The interpretation concerns an average, not a fractional physical bit attached to every outcome. In our example, ideal coding with costs one bit per symbol, while bits; the difference is exactly the computed bits. [ref]
Zeros require explicit conventions. An outcome with contributes zero, including when ; the convention agrees with the relevant limit. If but , the Kullback-Leibler divergence is infinite: the predictor has declared impossible an outcome that can occur. On a finite alphabet, the probability support of must therefore be contained in the probability support of for a finite answer. For example, and give , but . For general probability measures, failure of absolute continuity of measures likewise gives infinity. Even does not guarantee a finite integral. [ref]
To see how confidently wrong predictions are punished, hold the true Bernoulli distribution parameter at and vary the predicted parameter . Its binary relative entropy is
It vanishes at , equals approximately nats at , and equals nats at . Both endpoints give infinity because both outcomes remain possible under . Predicting almost no successes is especially costly because successes actually occur three quarters of the time. The reversed binary relative entropy stays finite at the endpoints: its averaging probability distribution concentrates on just one outcome, and assigns positive probability to both.
Figure 2.
Bernoulli relative entropy with true success probability 0.75 and varying predicted probability
. Details.
For model selection, minimizing expected log-loss ranks candidate statistical models by , since is common to them. The true probability distribution is usually unknown, so one estimates predictive performance using fresh observations or cross-validation. Fitting and assessing on the same data can reward overfitting; a small fitted Kullback-Leibler divergence alone does not establish useful prediction.
In variational inference, a tractable trial probability distribution commonly minimizes against a target posterior distribution . Maximizing the evidence lower bound accomplishes this without evaluating the target's normalization constant. The averaging now follows : placing trial probability where the posterior distribution assigns almost none is strongly penalized. The chosen direction and trial family therefore matter. [ref]
These comparisons do not by themselves establish causal inference. Two statistical models can reproduce the same observed probability distribution while predicting different responses to an intervention. Choosing the smaller Kullback-Leibler divergence therefore needs additional assumptions or experimental evidence before supporting a causal claim. [ref]
The original reference is S. Kullback and R. A. Leibler's 1951 paper [ref], published in The Annals of Mathematical Statistics 22(1), pages 79–86. Its title connects this comparison with sufficient statistics: the historical setting was statistical information, before today's widespread applications in prediction and variational inference.
Leaf depth in a code tree 2026-10-14
The number of edges on the graph path from the root of a tree to the leaf for symbol in a code tree. The root of a tree has depth zero. Each edge contributes one bit to a binary codeword, so this depth equals the codeword length; weighting these depths by probabilities gives expected codeword length.
Suppose a binary prefix code has integer codeword lengths . Under a source with probability mass function , its average codeword length is exactly cross-entropy, . The Kraft inequality is satisfied because . This exact interpretation requires suitable dyadic rational probabilities; a general is not an integer codeword length. For positive , a prefix code with lengths exists by the Kraft inequality and has average length between and . The ceiling function causes the one-symbol rounding overhead. The cross-entropy term describes mismatch overhead; those are distinct costs.
Nonunique optimal prefix code Created 2026-09-24 Updated 2026-10-14
An optimal prefix code can be nonunique in several different senses. Exchanging the labels on the outgoing edges of an internal vertex changes codewords while preserving every symbol's codeword length, the code tree shape, and expected codeword length. This freedom exists even with strictly unequal probabilities. Exchanging equal-probability symbols between leaves also preserves expected codeword length; if their leaf depths in a code tree differ, their individual codeword lengths change, though the set of leaf depths does not. For example, three equiprobable symbols have optimal codeword lengths : any of the three can receive the one-bit codeword.[ref]
Ties between weights of entire subtrees during Huffman coding can go further and change the code tree shape and its collection of codeword lengths. Take and first merge , creating weight . Next, of weight can merge either with or with the subtree, both of weight . The two resulting prefix codes are
For the second prefix code, bits. Both merge sequences add weights , whose sum is . Enumerating the full binary trees with four leaves also proves optimality independently: costs , while the least cost of is again . The two code trees cannot be obtained from each other merely by relabelling leaves or exchanging edge labels: their collections of leaf depths in a code tree differ.
Figure 1.
A tie between a symbol and a merged subtree gives two optimal prefix trees, with depths 2,2,2,2 and 1,2,3,3
. Details.
The quantifier in the Huffman sibling property is visible here too. Choose as two least-probability symbols. In the displayed balanced optimal prefix code, they are not sibling leaves in a code tree. Exchanging , which have equal probabilities, produces another balanced optimal prefix code in which are deepest sibling leaves in a code tree. Thus the proof supplies an optimal representative with the chosen pair together. It does not force that labelling on every optimum. An implementation can make its tie choices and edge assignments deterministic when encoder and decoder need to reproduce the same codewords; optimal mean length alone does not specify them.