kl_divergence
Computes the Kullback-Leibler divergence from
What does it measure?
KL divergence answers: if I believe the world follows distribution
It measures the information cost of using the wrong model. When
KL divergence is not symmetric
If you need a symmetric measure, use js_divergence instead.
Undefined for disjoint supports
If kl_divergence returns Err(InfoError::UndefinedDivergence) in this case.
This is a fundamental property, not a library limitation. If your distributions may have different supports, use js_divergence, which is always finite.
Formula
The probabilities are estimated empirically from the input slices.
Signature
pub fn kl_divergence<T>(p: &[T], q: &[T]) -> Result<f64, InfoError>
where
T: Eq + Hashpub fn kl_divergence_unchecked<T>(p: &[T], q: &[T]) -> f64
where
T: Eq + HashParameters
| Parameter | Description |
|---|---|
p | Samples from the true distribution |
q | Samples from the reference (model) distribution |
The slices do not need to have the same length — they are independent samples from each distribution.
Returns
| Error | When |
|---|---|
InfoError::EmptyInput | Either slice is empty |
InfoError::UndefinedDivergence | p contains a value absent from q |
Examples
use entropium::{kl_divergence, InfoError};
// Same distribution → KL = 0
let p = vec![0, 0, 1, 1, 1];
assert_eq!(kl_divergence(&p, &p).unwrap(), 0.0);
// KL is not symmetric
let p = vec![0, 0, 0, 1, 1, 2]; // P(0)=1/2, P(1)=1/3, P(2)=1/6
let q = vec![0, 1, 2, 2, 2, 2]; // Q(0)=1/6, Q(1)=1/6, Q(2)=2/3
let kl_pq = kl_divergence(&p, &q).unwrap();
let kl_qp = kl_divergence(&q, &p).unwrap();
assert!((kl_pq - kl_qp).abs() > 1e-10);
// Disjoint support → error
assert_eq!(
kl_divergence(&[0, 1], &[2, 3]).unwrap_err(),
InfoError::UndefinedDivergence
);
// Sample sizes can differ
let p_large = vec![0u8; 1000].into_iter().chain(vec![1u8; 500]).collect::<Vec<_>>();
let q_small = vec![0u8, 0, 1];
let kl = kl_divergence(&p_large, &q_small).unwrap();Practical uses
- Model evaluation:
measures how well a model approximates the data distribution. Minimising this is equivalent to maximum-likelihood estimation. - Variational inference: VI minimises
(note the reversed order), where is a tractable approximation and is the true posterior. - A/B testing: compare the output distributions of two system versions to quantify how much they differ.
- Anomaly detection: compute
over a rolling window; a spike signals a distribution shift.
Properties
| Property | Statement |
|---|---|
| Non-negativity | |
| Identity | |
| Asymmetry | |
| Unbounded | |
| Relation to cross-entropy |