Estimators¶
All estimators derive from ScoringMethod and share its contract: build from a
frequency distribution, call to score. See
How estimators work.
Base class¶
freqprob.ScoringMethod ¶
Bases: ABC
Abstract base class for frequency-based probability smoothing methods.
This class provides a unified interface for all probability estimation methods, supporting both regular probabilities and log-probabilities.
The general workflow is to initialize a method with a configuration, fit it
to a frequency distribution, and then score individual elements. Given a
frequency distribution mapping elements to their observed counts, each method
estimates a probability P(w) for every element w. For unobserved
elements, methods reserve probability mass to avoid returning zero.
Subclasses must implement _estimate, which returns the probability
of each observed element together with the mass reserved for the rest. The
method's own parameters are attributes on the estimator; the shared
ScoringMethodConfig carries only what every method may need.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
ScoringMethodConfig
|
Configuration parameters for the method. |
name |
str | None
|
Human-readable name of the method, or |
logprob |
bool | None
|
Whether this instance returns log-probabilities. |
Examples:
>>> from freqprob import MLE
>>> freqdist = {"apple": 3, "banana": 2, "cherry": 1}
>>> scorer = MLE(freqdist, logprob=False)
>>> scorer("apple") # most frequent item
0.5
>>> scorer("unknown") # unobserved item
0.0
Initialize the scoring method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ScoringMethodConfig
|
Configuration object containing the method parameters. |
required |
Note
This constructor should typically be called by subclass constructors, not directly by users.
revision
property
¶
Count of how many times this scorer's estimates have changed.
Starts at 0 and increases on every fit and on every
streaming update. A caller that caches anything derived from
support, unobserved_score, or the scores themselves
should record this value alongside the cache and rebuild when it
changes.
Examples:
support ¶
Return the elements this scorer holds an explicit estimate for.
Every other element is scored with unobserved_score. Together
with revision, this is what lets a caller build its own index
over the scorer without reaching into its internals.
Returns:
| Name | Type | Description |
|---|---|---|
Collection[Element]
|
The elements with an explicit estimate. The result is a read-only |
|
view |
Collection[Element]
|
it must not be mutated, and it may become stale once |
Collection[Element]
|
|
Examples:
unobserved_score ¶
Return the score given to every element outside support.
Returns:
| Type | Description |
|---|---|
Probability | LogProbability
|
The reserved probability (or log-probability) for unobserved |
Probability | LogProbability
|
elements. |
Examples:
fit ¶
Fit the scoring method to a frequency distribution.
This method trains the scorer on the provided frequency data, computing probability estimates for all observed elements. It resets any prior state so that re-fitting behaves like a fresh fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping elements to their observed counts. |
required |
Returns:
| Type | Description |
|---|---|
ScoringMethod
|
This scorer, to allow method chaining. |
Examples:
score ¶
Score a single element (scikit-learn-style alias for __call__).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
Element
|
The element to be scored. |
required |
Returns:
| Type | Description |
|---|---|
Probability | LogProbability
|
The probability (or log-probability) of the element. |
Examples:
predict ¶
Score many elements at once (scikit-learn-style batch alias).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elements
|
Iterable[Element]
|
The elements to be scored. |
required |
Returns:
| Type | Description |
|---|---|
list[Probability | LogProbability]
|
One probability (or log-probability) per input element, in order. |
Examples:
save ¶
Serialize this fitted scorer to a file.
The scorer can be restored later with load, avoiding the cost of
re-fitting. Serialization uses pickle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path. |
required |
Examples:
load
classmethod
¶
Load a scorer previously written with save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to a file created by |
required |
Returns:
| Type | Description |
|---|---|
T
|
The restored scorer. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the file does not contain a compatible scorer. |
Note
Only load files you trust: unpickling executes arbitrary code from the file, so never load a scorer from an untrusted source.
Examples:
Smoothing methods¶
Basic probability scoring methods.
This module implements fundamental probability scoring methods including Uniform, Random, and Maximum Likelihood Estimation (MLE). These methods serve as building blocks and baselines for more sophisticated smoothing techniques.
Uniform ¶
Bases: ScoringMethod
Uniform probability distribution.
The simplest baseline: assign equal probability to every observed element, ignoring the counts entirely. Useful as a non-informative prior or as a reference point when comparing smoothing methods.
For a vocabulary of size V with reserved mass p0, each observed
element gets (1 - p0) / V and any unobserved element gets p0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. The counts are ignored; only the number of distinct elements matters. |
required |
unobs_prob
|
Probability
|
Reserved probability mass |
0.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Counts are ignored, so both observed elements score the same:
>>> uniform = Uniform({"apple": 10, "banana": 1}, unobs_prob=0.1, logprob=False)
>>> uniform("apple")
0.45
>>> uniform("banana")
0.45
>>> uniform("cherry") # unobserved
0.1
Note
Because it discards frequency information, Uniform is meant as a
baseline. Use MLE, Lidstone, or Laplace when counts should matter.
Initialize Uniform distribution.
Random ¶
Random(freqdist: FrequencyDistribution, unobs_prob: Probability = 0.0, logprob: bool = True, seed: int | None = None)
Bases: ScoringMethod
Random probability distribution.
Assigns pseudo-random probabilities, useful for testing and as a randomized
baseline. Each element is given a random count drawn from the observed count
range, and those counts are then normalized like MLE. A fixed seed
makes the result reproducible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. Only the min/max counts are used, to bound the random counts. |
required |
unobs_prob
|
Probability
|
Reserved probability mass for unobserved elements.
Defaults to |
0.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
seed
|
int | None
|
Seed for the random number generator, for reproducible results.
Defaults to |
None
|
Examples:
The probabilities are random but form a valid distribution, and a fixed seed is reproducible:
>>> freqdist = {"apple": 5, "banana": 2, "cherry": 8}
>>> a = Random(freqdist, seed=123, logprob=False)
>>> b = Random(freqdist, seed=123, logprob=False)
>>> a("apple") == b("apple")
True
>>> round(sum(a(e) for e in freqdist), 6)
1.0
Note
Primarily for testing, debugging, and providing a randomized baseline for comparison. It is not a smoothing method in any meaningful sense.
Initialize Random distribution.
MLE ¶
Bases: ScoringMethod
Maximum Likelihood Estimation.
Estimates each element's probability as its relative frequency in the
observed data — the most intuitive baseline. For counts c_i with total
N, each observed element gets (1 - p0) * c_i / N and any unobserved
element gets the reserved mass p0 (0.0 by default, i.e. unseen
elements score zero).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
unobs_prob
|
Probability
|
Reserved probability mass |
0.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Probabilities are relative frequencies; unseen elements score zero:
>>> mle = MLE({"apple": 6, "banana": 3, "cherry": 1}, logprob=False)
>>> mle("apple")
0.6
>>> mle("banana")
0.3
>>> mle("unknown")
0.0
Reserving mass for unseen elements rescales the observed ones:
>>> smoothed = MLE({"apple": 6, "banana": 3, "cherry": 1},
... unobs_prob=0.1, logprob=False)
>>> round(smoothed("apple"), 3)
0.54
>>> smoothed("unknown")
0.1
Note
MLE underlies most smoothing methods but assigns zero probability to
unseen events, which is problematic for sparse data. Prefer Laplace,
Lidstone, or a more advanced method when unseen elements are likely.
Initialize MLE distribution.
Lidstone family probability scoring methods.
This module implements the Lidstone family of additive smoothing methods, including Lidstone smoothing (with arbitrary gamma), Laplace smoothing (gamma=1), and Expected Likelihood Estimation (gamma=0.5). These methods add virtual counts to observed data to handle the zero probability problem.
Lidstone ¶
Lidstone(freqdist: FrequencyDistribution, gamma: float, bins: int | None = None, logprob: bool = True)
Bases: ScoringMethod
Lidstone additive smoothing probability distribution.
Additive smoothing tackles the zero-probability problem by adding a virtual
count gamma to every possible element before normalizing. For counts
c_i, total N, and B bins, each observed element gets
(c_i + gamma) / (N + B * gamma) and any unobserved element gets
gamma / (N + B * gamma). This is the posterior mean under a symmetric
Dirichlet prior with concentration gamma. Use it when you need a simple,
principled way to keep unseen elements from scoring zero, and tune gamma
to trade off between staying close to the data (small gamma) and a more
uniform distribution (large gamma).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
gamma
|
float
|
Additive smoothing parameter ( |
required |
bins
|
int | None
|
Total number of possible elements. If |
None
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Add-gamma smoothing gives unseen elements non-zero probability:
>>> from freqprob import Lidstone
>>> freqdist = {"apple": 3, "banana": 1}
>>> lidstone = Lidstone(freqdist, gamma=1.0, logprob=False)
>>> round(lidstone("apple"), 3) # (3+1)/(4+2*1) = 4/6
0.667
>>> round(lidstone("banana"), 3) # (1+1)/(4+2*1) = 2/6
0.333
>>> round(lidstone("cherry"), 3) # 1/(4+2*1) = 1/6
0.167
A larger gamma pulls probabilities toward uniform:
>>> smooth = Lidstone(freqdist, gamma=2.0, logprob=False)
>>> smooth("apple") # (3+2)/(4+2*2) = 5/8
0.625
>>> smooth("cherry") # 2/(4+2*2) = 2/8
0.25
A larger bins reserves more mass for potential unseen elements:
>>> lidstone_big = Lidstone(freqdist, gamma=1.0, bins=1000, logprob=False)
>>> round(lidstone_big("apple"), 4) # (3+1)/(4+1000) = 4/1004
0.004
>>> round(lidstone_big("unseen"), 4) # 1/(4+1000) = 1/1004
0.001
Note
The choice of gamma is a bias-variance tradeoff: small values stay
close to MLE (low bias, high variance) while large values approach a
uniform distribution (higher bias, lower variance).
Initialize Lidstone smoothing.
Laplace ¶
Bases: Lidstone
Laplace (add-one) smoothing probability distribution.
The special case of Lidstone smoothing with gamma = 1.0, also called
"add-one smoothing." Each observed element gets (c_i + 1) / (N + B) and
any unobserved element gets 1 / (N + B) — i.e. one virtual observation
added to every possible element, corresponding to a uniform Dirichlet prior.
It is the most common additive smoother: reach for it when you want a simple,
reasonable default that never assigns zero probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
bins
|
int | None
|
Total number of possible elements. If |
None
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Add one to every count, then normalize:
>>> from freqprob import Laplace
>>> freqdist = {"red": 3, "blue": 2, "green": 1}
>>> laplace = Laplace(freqdist, logprob=False)
>>> round(laplace("red"), 3) # (3+1)/(6+3) = 4/9
0.444
>>> round(laplace("blue"), 3) # (2+1)/(6+3) = 3/9
0.333
>>> round(laplace("yellow"), 3) # 1/(6+3) = 1/9
0.111
Initialize Laplace smoothing.
ELE ¶
Bases: Lidstone
Expected Likelihood Estimation probability distribution.
The special case of Lidstone smoothing with gamma = 0.5, corresponding
to the Jeffreys prior for multinomial distributions. Each observed element
gets (c_i + 0.5) / (N + 0.5 * B) and any unobserved element gets
0.5 / (N + 0.5 * B) — half a virtual observation per element. This is a
middle ground between MLE and Laplace: use it when add-one smoothing feels
too aggressive but you still want unseen elements handled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
bins
|
int | None
|
Total number of possible elements. If |
None
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Add half a count to each element, then normalize:
>>> from freqprob import ELE
>>> freqdist = {"cat": 4, "dog": 2}
>>> ele = ELE(freqdist, logprob=False)
>>> round(ele("cat"), 3) # (4+0.5)/(6+0.5*2) = 4.5/7
0.643
>>> round(ele("dog"), 3) # (2+0.5)/(6+0.5*2) = 2.5/7
0.357
>>> round(ele("bird"), 3) # 0.5/(6+0.5*2) = 0.5/7
0.071
Note
ELE applies less smoothing than Laplace (gamma = 1), so it stays
closer to the observed frequencies while still avoiding zero
probabilities.
Initialize Expected Likelihood Estimation.
Bayesian (Dirichlet-prior) smoothing.
Bayesian ¶
Bases: ScoringMethod
Bayesian smoothing with a Dirichlet prior.
Estimates probabilities as the posterior mean under a symmetric Dirichlet
prior, adding alpha pseudocounts to each possible outcome. Each observed
element gets (c_i + alpha) / (N + V * alpha) and any unobserved element
gets alpha / (N + V * alpha), where N is the total count and V
the support size. This is numerically identical to Lidstone smoothing with
gamma = alpha, but framed so that alpha reads as prior belief: use it
when you want a theoretically principled smoother whose strength you can tune
from near-MLE (small alpha) to strongly uniform (large alpha).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
alpha
|
float
|
Dirichlet concentration parameter ( |
1.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Bayesian smoothing with a uniform prior (alpha = 1):
>>> from freqprob import Bayesian
>>> freqdist = {"apple": 8, "banana": 4, "cherry": 1}
>>> bayes = Bayesian(freqdist, alpha=1.0, logprob=False)
>>> bayes("apple") # (8+1)/(13+3*1) = 9/16
0.5625
>>> bayes("banana") # (4+1)/(13+3*1) = 5/16
0.3125
>>> bayes("unseen") # 1/(13+3*1) = 1/16
0.0625
A larger alpha smooths more strongly toward uniform:
>>> bayes_smooth = Bayesian(freqdist, alpha=2.0, logprob=False)
>>> round(bayes_smooth("apple"), 3) # (8+2)/(13+3*2) = 10/19
0.526
>>> round(bayes_smooth("unseen"), 3) # 2/(13+3*2) = 2/19
0.105
A small alpha stays closer to the observed frequencies:
>>> bayes_minimal = Bayesian(freqdist, alpha=0.1, logprob=False)
>>> round(bayes_minimal("apple"), 3) # (8+0.1)/(13+3*0.1) = 8.1/13.3
0.609
Note
A positive alpha is required; passing alpha <= 0 raises
ValueError. Equivalent to Lidstone with gamma = alpha.
Initialize Bayesian smoothing.
Good-Turing-family smoothing: Witten-Bell discounting and Simple Good-Turing.
WittenBell ¶
Bases: ScoringMethod
Witten-Bell smoothing.
Reserves probability mass for unseen elements based on how many distinct
types were observed, treating each new type as evidence that more unseen
types exist. The reserved mass is T / (N + T), where T is the number
of observed types and N the total number of observations; the remaining
mass is discounted proportionally so all estimates sum to one:
p = T / (Z * (N + T))for an unobserved element, andp = c / (N + T)for an element observedctimes.
Useful as a lightweight discounting method when a simple, parameter-free way to handle unseen elements is needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
bins
|
int | None
|
Optional total number of possible sample bins for the experiment.
If |
None
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Observed elements are scored by relative frequency over N + T, and
unseen elements share the reserved mass:
>>> from freqprob import WittenBell
>>> freqdist = {"the": 100, "a": 50, "cat": 3, "dog": 2, "rare": 1}
>>> wb = WittenBell(freqdist, logprob=False)
>>> round(wb("the"), 3)
0.621
>>> round(wb("rare"), 3)
0.006
>>> round(wb("unicorn"), 3) # unobserved
0.031
Initialize Witten-Bell smoothing.
SimpleGoodTuring ¶
SimpleGoodTuring(freqdist: FrequencyDistribution, p_value: float = 0.05, default_p0: float | None = None, bins: int | None = None, logprob: bool = True, allow_fail: bool = True)
Bases: ScoringMethod
Simple Good-Turing smoothing.
Reestimates counts using the frequency of frequencies (how many elements were seen once, twice, and so on), fitting a log-linear model to smooth the tail so that mass can be reserved for unseen elements. This is the practical Gale-Sampson formulation of the Good-Turing method originally developed by Turing and Good, and is a strong general-purpose smoother when the data show a spread of low-frequency counts (many singletons, fewer doubletons, etc.).
This implementation follows those by "maxbane" (2011, https://github.com/maxbane/simplegoodturing/blob/master/sgt.py), Geoffrey Sampson's original C code (1995-2008, https://www.grsampson.net/Resources.html), and the NLTK project (Loper, Bird et al., 2001-2018). Because of minor differences intended to guarantee non-zero probabilities under expected underflow, the reliance on scipy, and the handling of probabilities that are not computable when SGT assumptions are not met, most results will not exactly match the Gale-Sampson "gold standard", though the differences are never expected to be significant.
Note
Since v0.4.0, unseen queries return the per-word probability
p0 / (bins - V) rather than the total mass p0, making the method
compatible with perplexity calculations and consistent with the other
smoothers. Use the total_unseen_mass property to recover p0
(the total mass for all unseen words combined).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
p_value
|
float
|
The p-value for the confidence interval of the empirical Turing
estimate, guiding the choice between the Turing estimate |
0.05
|
default_p0
|
float | None
|
Optional probability for unobserved samples ( |
None
|
bins
|
int | None
|
Total support size for computing per-word unseen probabilities. If
|
None
|
logprob
|
bool
|
Return log-probabilities if |
True
|
allow_fail
|
bool
|
If |
True
|
Examples:
SGT needs a spread of low-frequency counts, so use a Zipfian-ish distribution with several singletons. Observed elements are discounted and unseen elements receive a share of the reserved mass:
>>> from freqprob import SimpleGoodTuring
>>> freqdist = {"a": 10, "b": 5, "c": 4, "d": 3, "e": 2,
... "f": 2, "g": 1, "h": 1, "i": 1, "j": 1}
>>> sgt = SimpleGoodTuring(freqdist, logprob=False)
>>> round(float(sgt("a")), 3)
0.307
>>> round(float(sgt("g")), 3) # a singleton
0.025
>>> round(sgt("unknown"), 3) # per-word unseen probability
0.033
>>> round(sgt.total_unseen_mass, 3) # total mass for all unseen words
0.133
Initialize Simple Good-Turing smoothing.
total_unseen_mass
property
¶
Total probability mass reserved for ALL unseen words (p0).
This is the value that Good-Turing actually estimates. The per-word
unseen probability returned by __call__() is this value divided by
the estimated number of unseen types (bins - V_observed).
Returns:
| Type | Description |
|---|---|
float
|
Total probability mass for all unseen words combined. |
Examples:
>>> from freqprob import SimpleGoodTuring
>>> freqdist = {"a": 10, "b": 5, "c": 1, "d": 1, "e": 1}
>>> sgt = SimpleGoodTuring(freqdist, logprob=False)
>>> round(sgt.total_unseen_mass, 3) # total mass for all unseen words
0.167
>>> round(sgt("unknown"), 3) # per-word probability for one unseen word
0.056
Kneser-Ney and Modified Kneser-Ney smoothing.
KneserNey ¶
Bases: BigramBackoff
Kneser-Ney smoothing probability distribution.
One of the most effective smoothing methods for language modeling. It
combines absolute discounting with interpolation and, crucially, weights a
word by the diversity of contexts it appears in (its continuation
probability) rather than its raw frequency. Each observed bigram scores
max(c - d, 0) / c(context) + backoff(context) * P_cont(word), and an
unseen bigram backs off to backoff(context) * P_cont(word).
This is absolute discounting with the unigram model replaced by the
continuation distribution, and it shares the back-off machinery with
freqprob.AbsoluteDiscounting accordingly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping bigrams to their observed
counts, in the form |
required |
discount
|
float
|
Absolute discounting parameter |
0.75
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Observed bigrams are discounted and interpolated with the continuation model, while unseen bigrams back off to it through the context's back-off weight:
>>> bigram_counts = {
... ("the", "cat"): 5, ("the", "dog"): 3, ("a", "cat"): 2,
... ("a", "dog"): 1, ("big", "cat"): 1, ("small", "dog"): 1,
... }
>>> kn = KneserNey(bigram_counts, discount=0.75, logprob=False)
>>> round(kn(("the", "cat")), 3)
0.625
An unseen bigram whose word is known scores through the context's
back-off weight rather than a flat average -- here 0.75 * P_cont(dog),
since big was only ever followed by one word:
An unseen context falls back to the continuation probability alone:
Note
This implementation assumes bigram input. The discount d is
typically between 0.5 and 0.8; 0.75 is a robust default.
Reliable continuation probabilities require sufficient bigram data.
A word that never appears in the data has no continuation probability,
so it scores at the floor rather than borrowing an average.
Initialize Kneser-Ney smoothing.
ModifiedKneserNey ¶
Bases: BigramBackoff
Modified Kneser-Ney smoothing probability distribution.
An enhanced Kneser-Ney variant that applies a different discount depending
on a bigram's count: d1 for singletons, d2 for doubletons, and
d3 for counts of three or more. Those discounts are estimated
automatically from the data's count-of-counts statistics, which usually
makes it more accurate than the fixed-discount version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping bigrams to their observed
counts, in the form |
required |
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
The discount adapts to each bigram's count, and the score interpolates the discounted estimate with the continuation model:
>>> bigram_counts = {
... ("the", "cat"): 5, ("the", "dog"): 3, ("a", "cat"): 2,
... ("a", "dog"): 1, ("big", "cat"): 1, ("small", "dog"): 1,
... }
>>> mkn = ModifiedKneserNey(bigram_counts, logprob=False)
>>> round(mkn(("the", "cat")), 3)
0.625
>>> round(mkn(("a", "cat")), 3)
0.558
Note
Modified Kneser-Ney is a standard, state-of-the-art classical smoothing method for n-gram language models. Because it estimates its discounts from the data, it is more robust than fixed-discount methods but needs enough varied counts to estimate them reliably.
Initialize Modified Kneser-Ney smoothing.
Absolute-discounting and Pitman-Yor bigram smoothing.
Both methods discount observed bigram counts and interpolate with a lower-order
unigram model. Absolute discounting subtracts a fixed amount from every count;
Pitman-Yor generalizes it with a second (concentration) parameter and has
absolute discounting as its strength = 0 special case.
AbsoluteDiscounting ¶
Bases: BigramBackoff
Absolute-discounting bigram smoothing.
Subtracts a fixed discount d from every observed bigram count and
redistributes the freed mass to a lower-order unigram model. For a bigram
(context, word) with count c and context total C,
P(word | context) = max(c - d, 0) / C + (d * N1+(context) / C) * P_uni(word)
where N1+(context) is the number of distinct words seen after the
context and P_uni is the unigram maximum-likelihood distribution. This is
the classic Ney-Essen-Kneser discounting scheme and the foundation Kneser-Ney
builds on — the difference is that Kneser-Ney replaces P_uni with a
continuation distribution. Reach for absolute discounting when you want simple,
well-understood discounting without Kneser-Ney's continuation weighting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping |
required |
discount
|
float
|
Absolute discounting parameter |
0.75
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Observed bigrams are discounted and interpolated with the unigram model, while unseen bigrams back off to it:
>>> bigram_counts = {
... ("the", "cat"): 5, ("the", "dog"): 3, ("a", "cat"): 2,
... ("a", "dog"): 1, ("big", "cat"): 1, ("small", "dog"): 1,
... }
>>> ad = AbsoluteDiscounting(bigram_counts, discount=0.75, logprob=False)
>>> round(ad(("the", "cat")), 3)
0.647
>>> round(ad(("a", "cat")), 3)
0.724
>>> round(ad(("big", "dog")), 3) # unseen word in a known context
0.288
>>> round(ad(("new", "cat")), 3) # unseen context backs off to unigram
0.615
Note
This implementation assumes bigram input. Unlike Kneser-Ney it uses raw unigram frequencies for the lower-order model, so a frequent word keeps its weight even if it appears in few distinct contexts.
Initialize absolute-discounting smoothing.
PitmanYor ¶
PitmanYor(freqdist: FrequencyDistribution, discount: float = 0.75, strength: float = 1.0, logprob: bool = True)
Bases: BigramBackoff
Pitman-Yor process bigram smoothing.
A two-parameter generalization of absolute discounting based on the
Pitman-Yor process. With discount d and concentration (strength)
theta, an observed bigram (context, word) with count c, context
total C, and t distinct words seen after the context scores
P(word | context) = (c - d + (theta + d * t) * P_uni(word)) / (theta + C)
and a word unseen in the context gets (theta + d * t) / (theta + C) *
P_uni(word). The concentration theta controls how much mass is reserved
for the base distribution independently of the discount: theta = 0
recovers absolute discounting, while larger theta pulls estimates toward
the unigram model. Pitman-Yor priors match the power-law behavior of natural
language and are the basis of the hierarchical Pitman-Yor language model,
which subsumes Kneser-Ney as a special case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping |
required |
discount
|
float
|
Discount parameter |
0.75
|
strength
|
float
|
Concentration parameter |
1.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Larger counts still dominate, but the concentration parameter reserves extra mass for the unigram base distribution:
>>> bigram_counts = {
... ("the", "cat"): 5, ("the", "dog"): 3, ("a", "cat"): 2,
... ("a", "dog"): 1, ("big", "cat"): 1, ("small", "dog"): 1,
... }
>>> py = PitmanYor(bigram_counts, discount=0.75, strength=1.0, logprob=False)
>>> round(py(("the", "cat")), 3)
0.643
>>> round(py(("a", "cat")), 3)
0.697
>>> round(py(("big", "dog")), 3) # unseen word in a known context
0.337
>>> round(py(("new", "cat")), 3) # unseen context backs off to unigram
0.615
Note
This implementation is a single-level (bigram) Pitman-Yor model using the unigram maximum-likelihood distribution as its base measure and the number of observed types as the table count. It is a practical approximation of the full hierarchical Pitman-Yor process.
Initialize Pitman-Yor smoothing.
Katz and Stupid Back-off bigram smoothing.
Both methods score an observed bigram directly and fall back to a lower-order unigram model for unseen bigrams. Katz back-off discounts observed counts with Good-Turing and computes normalized back-off weights so the result is a proper probability distribution; Stupid Back-off skips normalization for speed and returns unnormalized scores.
KatzBackoff ¶
Bases: BigramBackoff
Katz back-off bigram smoothing.
Katz's method discounts observed bigram counts with Good-Turing and
redistributes the freed mass to a lower-order unigram model through
normalized back-off weights. Following Katz (1987), only counts up to a
threshold k are discounted (counts above k are assumed reliable). For
a bigram (context, word) with count c and context total C,
P(word | context) = d_c * c / C if c > 0,
P(word | context) = alpha(context) * P_uni(word) otherwise,
where d_c is the Good-Turing discount ratio for count c and
alpha(context) is chosen so each context's distribution sums to one. It
is one of the classic n-gram smoothing methods and pairs naturally with
freqprob.SimpleGoodTuring, which uses the same count-of-counts
machinery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping |
required |
k
|
int
|
Good-Turing discounting is applied to counts |
5
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Reliable (high) counts are barely discounted, rare counts are discounted more, and unseen bigrams back off to the unigram model:
>>> bigram_counts = {
... ("the", "cat"): 4, ("the", "dog"): 3,
... ("a", "cat"): 2, ("a", "dog"): 2,
... ("my", "cat"): 1, ("my", "dog"): 1, ("my", "bird"): 1,
... ("his", "fish"): 1, ("her", "fish"): 1, ("its", "bird"): 1,
... }
>>> katz = KatzBackoff(bigram_counts, logprob=False)
>>> round(katz(("the", "cat")), 3) # reliable count, undiscounted
0.571
>>> round(katz(("my", "cat")), 3) # singleton, Good-Turing discounted
0.222
>>> round(katz(("my", "fish")), 3) # unseen in context, backs off
0.333
Note
This implementation assumes bigram input. Good-Turing discounting needs a
spread of low counts (singletons, doubletons, ...) to estimate discounts;
with too few distinct counts some discounts default to 1 (no
discounting), leaving little or no mass for unseen bigrams.
Initialize Katz back-off smoothing.
StupidBackoff ¶
Bases: BigramBackoff
Stupid Back-off bigram scoring.
A deliberately simple, unnormalized scheme introduced by Brants et al. (2007)
for web-scale language modeling. An observed bigram scores its relative
frequency; an unseen bigram scores a fixed weight alpha times the
lower-order unigram score:
S(word | context) = c(context, word) / c(context) if observed,
S(word | context) = alpha * P_uni(word) otherwise.
Because it skips the normalization Katz back-off performs, the scores do not form a probability distribution (they do not sum to one), but they are very cheap to compute and work well for ranking when data is plentiful.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution mapping |
required |
alpha
|
float
|
Back-off weight applied when falling back to the unigram model.
Defaults to |
0.4
|
logprob
|
bool
|
Return log-scores if |
True
|
Examples:
Observed bigrams score their relative frequency; unseen bigrams are
penalized by alpha and scored from the unigram model:
>>> bigram_counts = {
... ("the", "cat"): 5, ("the", "dog"): 3, ("a", "cat"): 2,
... ("a", "dog"): 1, ("big", "cat"): 1, ("small", "dog"): 1,
... }
>>> sb = StupidBackoff(bigram_counts, logprob=False)
>>> round(sb(("the", "cat")), 3) # 5 / 8
0.625
>>> round(sb(("a", "dog")), 3) # 1 / 3
0.333
>>> round(sb(("big", "dog")), 3) # 0.4 * P_uni("dog")
0.154
Note
Stupid Back-off returns scores, not normalized probabilities, so metrics that assume a valid distribution (such as perplexity) are not meaningful here. Use it for ranking and comparison, where only the relative ordering of scores matters.
Initialize Stupid Back-off scoring.
Interpolated (linear-combination) smoothing.
Interpolated ¶
Interpolated(high_order_dist: FrequencyDistribution, low_order_dist: FrequencyDistribution, lambda_weight: float = 0.7, logprob: bool = True)
Bases: ScoringMethod
Linear interpolation smoothing between two frequency distributions.
Blends a higher-order distribution with a lower-order one using a weighted
average, lambda_weight * P_high + (1 - lambda_weight) * P_low. This
keeps the specificity of the high-order model while borrowing robustness
from the smoother low-order model. Two modes are detected automatically
from the keys:
- N-gram interpolation, when the high-order keys are longer tuples than the
low-order keys. The lower-order context is taken as the suffix of each
high-order n-gram (e.g. bigram
(w2, w3)from trigram(w1, w2, w3)). - Same-type interpolation, when both distributions share the same key type (strings or equal-length tuples). Keys are matched directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
high_order_dist
|
FrequencyDistribution
|
Higher-order frequency distribution mapping elements to
counts (e.g. trigrams). For n-gram mode its tuple keys must be at
least as long as those of |
required |
low_order_dist
|
FrequencyDistribution
|
Lower-order frequency distribution (e.g. bigrams). |
required |
lambda_weight
|
float
|
Interpolation weight |
0.7
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
N-gram interpolation (trigrams backed off to bigrams). The score of
('the', 'big', 'cat') is 0.7 * (3/5) + 0.3 * (5/10), and an
unseen trigram backs off to 0.3 * (5/10):
>>> trigrams = {("the", "big", "cat"): 3, ("a", "big", "dog"): 2}
>>> bigrams = {("big", "cat"): 5, ("big", "dog"): 3, ("small", "cat"): 2}
>>> interp = Interpolated(trigrams, bigrams, lambda_weight=0.7, logprob=False)
>>> round(interp(("the", "big", "cat")), 3)
0.57
>>> round(interp(("unseen", "big", "cat")), 3)
0.15
Same-type interpolation between two string distributions. The score of
"word1" is 0.6 * (10/15) + 0.4 * (3/10):
>>> model1 = {"word1": 10, "word2": 5}
>>> model2 = {"word1": 3, "word3": 7}
>>> interp = Interpolated(model1, model2, lambda_weight=0.6, logprob=False)
>>> round(interp("word1"), 3)
0.52
>>> round(interp("word2"), 3)
0.2
>>> round(interp("word3"), 3)
0.28
Note
The mode is inferred from the key types, so mixed tuple lengths within a
single distribution raise an error. Unseen high-order n-grams back off
to the low-order model, and all probabilities are floored at 1e-10
for numerical stability. The weight lambda_weight is best tuned on
held-out data.
Initialize Interpolated smoothing.
JelinekMercer ¶
JelinekMercer(high_order_dist: FrequencyDistribution, low_order_dist: FrequencyDistribution, held_out_dist: FrequencyDistribution | None = None, lambda_weight: float = 0.5, em_iterations: int = 10, logprob: bool = True)
Bases: Interpolated
Jelinek-Mercer smoothing with an EM-estimated interpolation weight.
Jelinek-Mercer smoothing linearly interpolates a higher-order model with a
lower-order one, exactly as Interpolated does, but chooses the
interpolation weight lambda by deleted interpolation: given a held-out
distribution, the weight is fitted with the Expectation-Maximization
algorithm to maximize the likelihood of that held-out data. Without held-out
data it behaves as fixed-weight interpolation using lambda_weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
high_order_dist
|
FrequencyDistribution
|
Higher-order frequency distribution (e.g. trigrams). |
required |
low_order_dist
|
FrequencyDistribution
|
Lower-order frequency distribution (e.g. bigrams). |
required |
held_out_dist
|
FrequencyDistribution | None
|
Optional held-out frequency distribution used to fit
|
None
|
lambda_weight
|
float
|
Interpolation weight |
0.5
|
em_iterations
|
int
|
Number of EM iterations when fitting |
10
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
estimated_lambda |
The interpolation weight actually used — either the
EM-fitted value or |
Examples:
With no held-out data the estimated weight is exactly lambda_weight,
and scoring matches fixed-weight interpolation:
>>> trigrams = {("the", "big", "cat"): 3, ("a", "big", "dog"): 2}
>>> bigrams = {("big", "cat"): 5, ("big", "dog"): 3}
>>> jm = JelinekMercer(trigrams, bigrams, lambda_weight=0.6, logprob=False)
>>> round(jm.estimated_lambda, 2)
0.6
>>> round(jm(("the", "big", "cat")), 3) # 0.6 * (3/5) + 0.4 * (5/8)
0.61
Held-out data that the high-order model predicts well pulls the weight up:
>>> held_out = {("the", "big", "cat"): 8, ("a", "big", "dog"): 6}
>>> jm = JelinekMercer(trigrams, bigrams, held_out_dist=held_out, logprob=False)
>>> jm.estimated_lambda > 0.5
True
Note
EM fits a single global lambda (not the per-context bucketed weights
of the original Jelinek-Mercer scheme). The held-out data should be
disjoint from the training data for the estimate to be meaningful.
Initialize Jelinek-Mercer smoothing, fitting lambda if held-out data is given.
Certainty-degree probability estimation.
CertaintyDegree ¶
CertaintyDegree(freqdist: FrequencyDistribution, bins: int | None = None, unobs_prob: Probability = 0.0, logprob: bool = True)
Bases: ScoringMethod
Certainty-degree smoothing.
Reserves probability mass for unseen elements based on the degree of certainty that no unobserved samples remain, derived from the number of observations relative to the support size. As more of the possible bins are observed, the reserved mass shrinks; the remaining mass rescales the Maximum-Likelihood estimate of each observed element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Mapping of elements to observed counts. |
required |
bins
|
int | None
|
Optional total number of possible sample bins for the experiment.
If |
None
|
unobs_prob
|
Probability
|
Reserved probability mass for unobserved states
( |
0.0
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Examples:
Observed elements are rescaled by the computed certainty mass, and the remainder is reserved for unseen elements:
>>> from freqprob import CertaintyDegree
>>> freqdist = {"apple": 8, "banana": 4, "cherry": 2, "date": 1}
>>> cd = CertaintyDegree(freqdist, logprob=False)
>>> round(cd("apple"), 3)
0.515
>>> round(cd("date"), 3)
0.064
>>> round(cd("kiwi"), 3) # unobserved
0.035
Note
This is an experimental distribution under development by Tiago Tresoldi; it should not be used as the sole or main distribution yet.
Initialize Certainty Degree estimation.