cross_entropy
Computes the cross-entropy of
What does it measure?
Cross-entropy answers: how many bits do I need per observation if the data comes from
When you build an optimal code for distribution
- If
: the code is optimal, and you use exactly bits per symbol. - If
: the code is suboptimal, and you waste extra bits per symbol.
This decomposes neatly as:
Undefined for disjoint supports
If cross_entropy returns Err(InfoError::UndefinedDivergence) in this case.
Formula
Signature
rust
pub fn cross_entropy<T>(p: &[T], q: &[T]) -> Result<f64, InfoError>
where
T: Eq + Hashrust
pub fn cross_entropy_unchecked<T>(p: &[T], q: &[T]) -> f64
where
T: Eq + HashParameters
| Parameter | Description |
|---|---|
p | Samples from the true distribution |
q | Samples from the model distribution |
The slices do not need to have the same length.
Returns
| Error | When |
|---|---|
InfoError::EmptyInput | Either slice is empty |
InfoError::UndefinedDivergence | p contains a value absent from q |
Examples
rust
use entropium::{cross_entropy, entropy, InfoError};
// H(P,P) = H(P) — the code is optimal when P = Q
let p = vec![0, 0, 0, 1, 1];
let h = entropy(&p).unwrap();
let ce = cross_entropy(&p, &p).unwrap();
assert!((ce - h).abs() < 1e-12);
// H(P,Q) >= H(P) — any mismatch increases cost
let p = vec![0, 0, 1, 1, 1, 2];
let q = vec![0, 1, 1, 2, 2, 2];
assert!(cross_entropy(&p, &q).unwrap() >= entropy(&p).unwrap() - 1e-12);
// Disjoint support → error
assert_eq!(
cross_entropy(&[0, 1], &[2, 3]).unwrap_err(),
InfoError::UndefinedDivergence
);Practical uses
- Classification loss: in machine learning, training a classifier by minimising cross-entropy
over the training set is equivalent to maximum-likelihood estimation of the model parameters. This is the standard loss used in logistic regression, softmax classifiers, and language models. - Language model perplexity: the perplexity of a language model is
, where is the empirical distribution of the test corpus. Lower perplexity means the model's distribution is closer to the true one. - Information-theoretic lower bound:
is the minimum average description length achievable when the code is designed for but applied to data from .
Properties
| Property | Statement |
|---|---|
| Lower bound | |
| Equality | |
| Asymmetry | |
| Decomposition |