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 ¶
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
|
required |
test_data
|
Iterable[Element]
|
Iterable of test elements to score. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The perplexity value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
cross_entropy ¶
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
|
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 |
Examples:
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 |
required |
q_model
|
ScoringMethod
|
The approximate probability model |
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:
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
|
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 ¶
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 |
float
|
distribution. |
Examples:
chao_shen_entropy ¶
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 |
float
|
empty distribution. |
Examples:
nsb_entropy ¶
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
|
Returns:
| Type | Description |
|---|---|
float
|
The estimated entropy in nats (natural log), in |
float
|
Returns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples: