Skip to content

Metrics

Evaluation of fitted models (Evaluating models) and statistics of a sample (Coverage and entropy).

Model-evaluation metrics: perplexity, cross-entropy, KL divergence, entropy.

Alongside the model-scoring metrics, this module provides sample-based estimators that work directly on a frequency distribution: sample_coverage (the Good-Turing estimate of observed mass) and the bias-corrected entropy estimators chao_shen_entropy and nsb_entropy, which correct the downward bias of the naive plug-in entropy when many types are rare or unobserved.

perplexity

perplexity(model: ScoringMethod, test_data: Iterable[Element]) -> float

Calculate the perplexity of a model on test data.

Perplexity is exp(H(p)) where H(p) is the cross-entropy. Lower perplexity indicates a model that better predicts the test data.

Parameters:

Name Type Description Default
model ScoringMethod

A fitted probability model. Must be configured with logprob=True.

required
test_data Iterable[Element]

Iterable of test elements to score.

required

Returns:

Type Description
float

The perplexity value.

Raises:

Type Description
ValueError

If model is not configured for log-probabilities.

Examples:

>>> from freqprob import MLE, perplexity
>>> model = MLE({"a": 3, "b": 2, "c": 1}, logprob=True)
>>> round(perplexity(model, ["a", "b", "a", "c"]), 4)
2.913

cross_entropy

cross_entropy(model: ScoringMethod, test_data: Iterable[Element]) -> float

Calculate the cross-entropy of a model on test data.

Cross-entropy is the average negative log-probability the model assigns to the test data. Lower values indicate a better fit.

Parameters:

Name Type Description Default
model ScoringMethod

A fitted probability model. Must be configured with logprob=True.

required
test_data Iterable[Element]

Iterable of test elements to score.

required

Returns:

Type Description
float

The cross-entropy value (in nats, since natural logs are used).

Raises:

Type Description
ValueError

If model is not configured for log-probabilities.

Examples:

>>> from freqprob import MLE, cross_entropy
>>> model = MLE({"a": 3, "b": 2, "c": 1}, logprob=True)
>>> round(cross_entropy(model, ["a", "b", "a", "c"]), 4)
1.0692

kl_divergence

kl_divergence(p_model: ScoringMethod, q_model: ScoringMethod, test_data: Iterable[Element]) -> float

Calculate the Kullback-Leibler divergence between two models.

KL divergence measures how much the approximate distribution Q diverges from the reference distribution P: KL(P||Q) = sum_w P(w) log(P(w) / Q(w)), summed over the distinct elements w of test_data (the support to compare the models on; repeated elements are counted once). It is not symmetric: KL(P||Q) != KL(Q||P).

Parameters:

Name Type Description Default
p_model ScoringMethod

The reference probability model P. Must use logprob=True.

required
q_model ScoringMethod

The approximate probability model Q. Must use logprob=True.

required
test_data Iterable[Element]

Iterable of elements over which to sum the divergence. Duplicates are ignored.

required

Returns:

Type Description
float

The KL divergence value.

Raises:

Type Description
ValueError

If either model is not configured for log-probabilities.

Examples:

>>> from freqprob import MLE, Laplace, kl_divergence
>>> p_model = MLE({"a": 3, "b": 2, "c": 1}, logprob=True)
>>> q_model = Laplace({"a": 3, "b": 2, "c": 1}, logprob=True)
>>> round(kl_divergence(p_model, q_model, ["a", "b", "c"]), 4)
0.0109

model_comparison

model_comparison(models: dict[str, ScoringMethod], test_data: Iterable[Element]) -> dict[str, dict[str, float]]

Compare multiple models using perplexity and cross-entropy.

Each model is evaluated on the same test data, producing a nested mapping of model name to its metric values.

Parameters:

Name Type Description Default
models dict[str, ScoringMethod]

Mapping of model names to fitted models. Every model must use logprob=True.

required
test_data Iterable[Element]

Iterable of test elements. It is materialized once and reused across all models.

required

Returns:

Type Description
dict[str, dict[str, float]]

A mapping of each model name to a ``{"perplexity": ..., "cross_entropy":

dict[str, dict[str, float]]

...}`` dictionary.

Raises:

Type Description
ValueError

If any model is not configured for log-probabilities.

Examples:

>>> from freqprob import MLE, Laplace, model_comparison
>>> models = {
...     "mle": MLE({"a": 3, "b": 2, "c": 1}, logprob=True),
...     "laplace": Laplace({"a": 3, "b": 2, "c": 1}, logprob=True),
... }
>>> results = model_comparison(models, ["a", "b", "a", "c"])
>>> sorted(results)
['laplace', 'mle']
>>> round(results["mle"]["perplexity"], 4)
2.913
>>> round(results["laplace"]["cross_entropy"], 4)
1.0561

sample_coverage

sample_coverage(freqdist: FrequencyDistribution) -> float

Estimate the proportion of total probability mass that was observed.

Uses the Good-Turing estimator of the missing mass: the share of probability belonging to unseen types is approximately N1 / N, where N1 is the number of types seen exactly once (singletons) and N the total number of observations. Coverage is the complement, 1 - N1 / N.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required

Returns:

Type Description
float

The estimated observed mass, in [0, 1]. Returns 0.0 for an empty

float

distribution.

Examples:

>>> from freqprob import sample_coverage
>>> sample_coverage({"a": 10, "b": 5, "c": 3})  # no singletons
1.0
>>> round(sample_coverage({"a": 8, "b": 1, "c": 1}), 3)  # two singletons of 10
0.8

chao_shen_entropy

chao_shen_entropy(freqdist: FrequencyDistribution) -> float

Estimate Shannon entropy with the Chao-Shen bias correction.

The naive plug-in entropy underestimates the true entropy when the sample misses probability mass. The Chao-Shen estimator combines Good-Turing coverage adjustment with a Horvitz-Thompson correction for unseen types, which reduces this bias:

H = - sum_i (C p_i) log(C p_i) / (1 - (1 - C p_i) ** N)

where p_i is the relative frequency of type i, C the sample coverage (see sample_coverage), and N the total count.

When every observation is a singleton the Good-Turing coverage is zero and the estimate would collapse to 0. Following Chao and Shen (2003), and reference implementations such as R's entropy::entropy.ChaoShen, the singleton count is then taken as N - 1, which keeps the coverage at 1 / N.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required

Returns:

Type Description
float

The estimated entropy in nats (natural log). Returns 0.0 for an

float

empty distribution.

Examples:

>>> from freqprob import chao_shen_entropy
>>> import math
>>> # Approaches the true entropy of a uniform distribution when well sampled.
>>> round(chao_shen_entropy({"a": 1000, "b": 1000, "c": 1000}), 3)
1.099
>>> round(math.log(3), 3)
1.099

nsb_entropy

nsb_entropy(freqdist: FrequencyDistribution, bins: int | None = None) -> float

Estimate Shannon entropy with the Nemenman-Shafee-Bialek estimator.

The NSB estimator is a Bayesian entropy estimator that averages the posterior mean entropy of a symmetric Dirichlet model over its concentration parameter, using a prior chosen so the a priori entropy is (nearly) uniform. It is well suited to the undersampled regime, where the number of possible types is comparable to or larger than the number of observations.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required
bins int | None

The size of the assumed alphabet (number of possible types), reserving entropy for types that could occur but were not seen. If None (the default), the number of observed types is used, so no unseen types are assumed. Must be at least the number of observed types.

None

Returns:

Type Description
float

The estimated entropy in nats (natural log), in [0, log(bins)].

float

Returns 0.0 for an empty distribution or a single possible type.

Raises:

Type Description
ValueError

If bins is smaller than the number of observed types.

Examples:

>>> from freqprob import nsb_entropy
>>> import math
>>> # Well-sampled uniform distribution approaches log(K).
>>> round(nsb_entropy({"a": 500, "b": 500, "c": 500, "d": 500}), 2)
1.39
>>> round(math.log(4), 2)
1.39