Skip to content

Evaluating models

perplexity, cross_entropy, kl_divergence, model_comparison · need log-scorers

The way to choose between estimators is to ask how well each predicts data it was not fitted to. These metrics score a fitted model on a list of held-out elements. All of them need models built with logprob=True (the default).

Definition

For held-out elements \(w_1, \ldots, w_n\) and a model \(P\),

\[ H = -\frac{1}{n}\sum_{i=1}^{n} \ln P(w_i), \qquad \mathrm{PP} = e^{H}. \]

cross_entropy returns \(H\) in nats and perplexity returns \(\mathrm{PP}\): the effective number of equally likely choices the model faces at each element. Lower is better for both. kl_divergence(p, q, elements) is the Kullback–Leibler divergence of \(Q\) from \(P\) over the support formed by the distinct elements given, \(\sum_w P(w) \ln \big(P(w)/Q(w)\big)\); an element listed more than once counts once. model_comparison returns the perplexity and cross-entropy of several models at once.

Example

Fit on the example counts and evaluate on a held-out sample that includes an unseen word:

>>> import freqprob
>>> counts = dict(the=10, cat=5, sat=4, on=3, mat=2, a=2, dog=1, ran=1, far=1, away=1)
>>> held_out = ["the", "cat", "sat", "on", "the", "rug"]
>>> models = {
...     "laplace": freqprob.Laplace(counts, bins=20),
...     "good_turing": freqprob.SimpleGoodTuring(counts),
...     "witten_bell": freqprob.WittenBell(counts, bins=20),
... }
>>> report = freqprob.model_comparison(models, held_out)
>>> for name, metrics in report.items():
...     print(name, round(metrics["perplexity"], 2))
laplace 10.12
good_turing 7.73
witten_bell 9.38
>>> round(freqprob.cross_entropy(models["good_turing"], held_out), 3)
2.045

Properties

  • Hold data out. Evaluated on its own training data, the unsmoothed MLE always wins, because it gives the training data the highest possible likelihood.
  • Unseen elements dominate. One unseen element scored at the log floor of a model that reserves no mass adds about 23 nats to the sum; see Pitfalls.
  • Compare models on the same support. A model that spreads mass over more possible elements gives each a lower probability; compare models with the same bins, or report it.
  • Only for probability models. Stupid Back-off returns unnormalized scores.

API

freqprob.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

freqprob.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

freqprob.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

freqprob.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

References

  • Shannon (1948); Kullback & Leibler (1951). See References.