Skip to content

Performance

Alternatives to the default estimators for large or streaming data; see Scale to large data. Profiling tools live in freqprob.performance.profiling and are not re-exported.

Streaming

Streaming and incremental frequency distribution updates.

This module provides efficient streaming support for frequency distributions, allowing incremental updates and online learning scenarios with minimal memory overhead.

StreamingFrequencyDistribution

StreamingFrequencyDistribution(max_vocabulary_size: int | None = None, min_count_threshold: int = 1, decay_factor: float | None = None, compression_threshold: int = 10000)

Memory-efficient streaming frequency distribution with incremental updates.

This class supports real-time updates to frequency distributions while maintaining memory efficiency through various optimization strategies.

Parameters:

Name Type Description Default
max_vocabulary_size int | None

Maximum support size to maintain, or None for unlimited. Defaults to None.

None
min_count_threshold int

Minimum count for elements to be retained. Defaults to 1.

1
decay_factor float | None

Exponential decay factor for aging old observations, or None for no decay. Defaults to None.

None
compression_threshold int

Number of updates between compression operations. Defaults to 10000.

10000

Examples:

Counts accumulate across single and batch updates:

>>> stream_dist = StreamingFrequencyDistribution(max_vocabulary_size=1000)
>>> stream_dist.update("word1")
>>> stream_dist.update("word1", count=5)
>>> stream_dist.update_batch(["word2", "word3", "word1"])
>>> stream_dist.get_count("word1")
7.0
>>> len(stream_dist)
3
>>> stream_dist.get_total_count()
9.0
>>> round(stream_dist.get_frequency("word1"), 4)
0.7778

Initialize streaming frequency distribution.

Parameters:

Name Type Description Default
max_vocabulary_size int | None

Maximum support size, or None for unlimited.

None
min_count_threshold int

Minimum count threshold for retention.

1
decay_factor float | None

Decay factor for time-based forgetting (0 < decay < 1), or None for no decay.

None
compression_threshold int

Number of updates before triggering compression.

10000

update

update(element: Element, count: int = 1) -> None

Update count for a single element.

Parameters:

Name Type Description Default
element Element

Element to update.

required
count int

Count increment. Defaults to 1.

1

update_batch

update_batch(elements: list[Element], counts: list[int] | None = None) -> None

Update counts for multiple elements efficiently.

Parameters:

Name Type Description Default
elements list[Element]

Elements to update.

required
counts list[int] | None

Count for each element, or None to use 1 for all.

None

get_count

get_count(element: Element) -> float

Get count for an element.

Parameters:

Name Type Description Default
element Element

Element to query.

required

Returns:

Type Description
float

Count for the element.

get_frequency

get_frequency(element: Element) -> float

Get relative frequency for an element.

Parameters:

Name Type Description Default
element Element

Element to query.

required

Returns:

Type Description
float

Relative frequency (count / total_count).

get_total_count

get_total_count() -> float

Get total count across all elements.

get_vocabulary_size

get_vocabulary_size() -> int

Get current support size.

items

items() -> Iterator[tuple[Element, float]]

Iterate over (element, count) pairs.

keys

keys() -> Iterator[Element]

Iterate over elements.

values

values() -> Iterator[float]

Iterate over counts.

to_dict

to_dict() -> dict[Element, int]

Convert to regular dictionary with integer counts.

Returns:

Type Description
dict[Element, int]

Dictionary representation with integer counts.

get_statistics

get_statistics() -> dict[str, Any]

Get statistics about the streaming distribution.

Returns:

Type Description
dict[str, Any]

Statistics dictionary with vocabulary size, total count, update

dict[str, Any]

count, and configuration parameters.

StreamingMLE

StreamingMLE(initial_freqdist: dict[Element, int] | None = None, max_vocabulary_size: int | None = None, unobs_prob: float | None = None, logprob: bool = True)

Bases: ScoringMethod, IncrementalScoringMethod

Streaming Maximum Likelihood Estimation with incremental updates.

This implementation maintains a streaming frequency distribution and updates probability estimates incrementally as new data arrives.

Parameters:

Name Type Description Default
initial_freqdist dict[Element, int] | None

Initial frequency distribution, or None to start empty. Defaults to None.

None
max_vocabulary_size int | None

Maximum support size to maintain, or None for unlimited. Defaults to None.

None
unobs_prob float | None

Reserved probability mass for unobserved elements, or None. Defaults to None.

None
logprob bool

Return log-probabilities if True (the default), otherwise plain probabilities.

True

Examples:

Probabilities are updated incrementally as observations arrive:

>>> streaming_mle = StreamingMLE(logprob=False)
>>> streaming_mle.update_single("word1", 5)
>>> streaming_mle.update_batch(["word2", "word3"])
>>> round(streaming_mle("word1"), 4)
0.7143
>>> streaming_mle.get_update_count()
3

Initialize streaming MLE scorer.

update_single

update_single(element: Element, count: int = 1) -> None

Update with a single element observation.

update_batch

update_batch(elements: list[Element], counts: list[int] | None = None) -> None

Update with multiple element observations.

get_update_count

get_update_count() -> int

Get the number of updates performed.

get_streaming_statistics

get_streaming_statistics() -> dict[str, Any]

Get statistics about the streaming distribution.

save_state

save_state(filepath: str) -> None

Save the current state to disk.

Parameters:

Name Type Description Default
filepath str

Path to save the state.

required

load_state classmethod

load_state(filepath: str) -> StreamingMLE

Load state from disk.

Parameters:

Name Type Description Default
filepath str

Path to load the state from.

required

Returns:

Type Description
StreamingMLE

The loaded streaming MLE instance.

StreamingLaplace

StreamingLaplace(initial_freqdist: dict[Element, int] | None = None, max_vocabulary_size: int | None = None, bins: int | None = None, logprob: bool = True)

Bases: StreamingMLE

Streaming Laplace smoothing with incremental updates.

Extends StreamingMLE to provide Laplace (add-one) smoothing in a streaming context.

Parameters:

Name Type Description Default
initial_freqdist dict[Element, int] | None

Initial frequency distribution, or None to start empty. Defaults to None.

None
max_vocabulary_size int | None

Maximum support size to maintain, or None for unlimited. Defaults to None.

None
bins int | None

Total number of possible bins, or None to use the observed vocabulary size. Defaults to None.

None
logprob bool

Return log-probabilities if True (the default), otherwise plain probabilities.

True

Examples:

Unobserved elements receive smoothed probability mass:

>>> laplace = StreamingLaplace(
...     initial_freqdist={"a": 3, "b": 1}, logprob=False
... )
>>> round(laplace("a"), 4)
0.6667
>>> round(laplace("unseen"), 4)
0.1667

Initialize streaming Laplace scorer.

Vectorized scoring

Vectorized operations for efficient batch processing.

This module provides numpy-based implementations for batch scoring operations, allowing efficient processing of large datasets without Python loops.

VectorizedScorer

VectorizedScorer(scorer: ScoringMethod)

Wrapper class that adds vectorized operations to any scoring method.

This class wraps existing scoring methods to provide efficient batch operations using numpy arrays and vectorized computations.

Parameters:

Name Type Description Default
scorer ScoringMethod

The underlying scoring method to wrap.

required

Examples:

Score many elements at once, returning a numpy array:

>>> from freqprob import MLE
>>> scorer = MLE({"a": 3, "b": 2, "c": 1}, logprob=False)
>>> vectorized = VectorizedScorer(scorer)
>>> scores = vectorized.score_batch(["a", "b", "c", "d"])
>>> scores.shape
(4,)
>>> [round(float(x), 4) for x in scores]
[0.5, 0.3333, 0.1667, 0.0]

Initialize vectorized scorer wrapper.

Parameters:

Name Type Description Default
scorer ScoringMethod

Scoring method to wrap with vectorized operations.

required

score_batch

score_batch(elements: Sequence[Element] | ndarray[Any, Any]) -> np.ndarray[Any, Any]

Score a batch of elements efficiently using vectorized operations.

Parameters:

Name Type Description Default
elements Sequence[Element] | ndarray[Any, Any]

Elements to score, as a sequence or numpy array.

required

Returns:

Type Description
ndarray[Any, Any]

Array of scores for the elements, in the same order as the input.

Examples:

>>> from freqprob import MLE
>>> scorer = MLE({"a": 3, "b": 2}, logprob=False)
>>> vectorized = VectorizedScorer(scorer)
>>> scores = vectorized.score_batch(["a", "b", "unknown"])
>>> [round(float(x), 4) for x in scores]
[0.6, 0.4, 0.0]

score_matrix

score_matrix(elements_2d: Sequence[Sequence[Element]]) -> np.ndarray[Any, Any]

Score a 2D array of elements, returning a matrix of scores.

Parameters:

Name Type Description Default
elements_2d Sequence[Sequence[Element]]

2D list of elements to score.

required

Returns:

Type Description
ndarray[Any, Any]

2D array of scores with shape

ndarray[Any, Any]

(len(elements_2d), max_row_length); shorter rows are padded

ndarray[Any, Any]

with the default probability.

top_k_elements

top_k_elements(k: int) -> tuple[Sequence[Element], np.ndarray[Any, Any]]

Get the top-k highest scoring elements.

Parameters:

Name Type Description Default
k int

Number of top elements to return.

required

Returns:

Type Description
Sequence[Element]

A tuple of (elements, scores) for the top-k elements, ordered

ndarray[Any, Any]

from highest to lowest score.

percentile_scores

percentile_scores(elements: Sequence[Element], percentiles: list[float]) -> np.ndarray[Any, Any]

Compute percentile ranks for element scores.

Parameters:

Name Type Description Default
elements Sequence[Element]

Elements to compute percentile ranks for.

required
percentiles list[float]

Percentiles to compute (0-100).

required

Returns:

Type Description
ndarray[Any, Any]

Percentile rank for each element.

BatchScorer

BatchScorer(scorers: dict[str, ScoringMethod])

Efficient batch scoring using multiple scoring methods.

This class allows scoring elements using multiple methods simultaneously, with optimized operations for processing large batches of data.

Parameters:

Name Type Description Default
scorers dict[str, ScoringMethod]

Mapping of scorer names to scoring methods.

required

Examples:

Score the same elements with several methods at once:

>>> from freqprob import MLE, Laplace
>>> scorers = {
...     "mle": MLE({"a": 3, "b": 2}, logprob=False),
...     "laplace": Laplace({"a": 3, "b": 2}, logprob=False),
... }
>>> batch_scorer = BatchScorer(scorers)
>>> results = batch_scorer.score_batch(["a", "b", "c"])
>>> [round(float(x), 4) for x in results["mle"]]
[0.6, 0.4, 0.0]
>>> [round(float(x), 4) for x in results["laplace"]]
[0.5714, 0.4286, 0.1429]

Initialize batch scorer with multiple scoring methods.

Parameters:

Name Type Description Default
scorers dict[str, ScoringMethod]

Mapping of scorer names to scoring methods.

required

score_batch

score_batch(elements: Sequence[Element]) -> dict[str, np.ndarray[Any, Any]]

Score elements using all configured scoring methods.

Parameters:

Name Type Description Default
elements Sequence[Element]

Elements to score.

required

Returns:

Type Description
dict[str, ndarray[Any, Any]]

Mapping of scorer names to score arrays.

score_and_compare

score_and_compare(elements: Sequence[Element]) -> dict[str, Any]

Score elements and provide comparison statistics.

Parameters:

Name Type Description Default
elements Sequence[Element]

Elements to score.

required

Returns:

Type Description
dict[str, Any]

Dictionary with per-method scores plus aggregate statistics

dict[str, Any]

(mean, std, min, max) and per-method rankings.

benchmark_methods

benchmark_methods(elements: Sequence[Element], num_iterations: int = 100) -> dict[str, float]

Benchmark the performance of different scoring methods.

Parameters:

Name Type Description Default
elements Sequence[Element]

Elements to use for benchmarking.

required
num_iterations int

Number of iterations for timing. Defaults to 100.

100

Returns:

Type Description
dict[str, float]

Mapping of method names to average execution time in seconds.

Lazy evaluation

Lazy evaluation support for efficient probability calculations.

This module provides lazy evaluation mechanisms that defer expensive computations until they are actually needed, improving performance when only a subset of probabilities are accessed.

create_lazy_mle

create_lazy_mle(freqdist: FrequencyDistribution, unobs_prob: float | None = None, logprob: bool = True) -> LazyScoringMethod

Create a lazy Maximum Likelihood Estimation scorer.

Builds a LazyScoringMethod that computes MLE probabilities on demand, fitted to the given distribution.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required
unobs_prob float | None

Reserved probability mass for unobserved elements, or None for plain MLE. Defaults to None.

None
logprob bool

Return log-probabilities if True (the default), otherwise plain probabilities.

True

Returns:

Type Description
LazyScoringMethod

A fitted lazy MLE scorer.

Examples:

>>> scorer = create_lazy_mle({"a": 3, "b": 2, "c": 1}, logprob=False)
>>> scorer("a")
0.5
>>> scorer("c")
0.16666666666666666
>>> scorer("unseen")
0.0

create_lazy_laplace

create_lazy_laplace(freqdist: FrequencyDistribution, bins: int | None = None, logprob: bool = True) -> LazyScoringMethod

Create a lazy Laplace (add-one) smoothing scorer.

Builds a LazyScoringMethod that computes Laplace-smoothed probabilities on demand, fitted to the given distribution.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required
bins int | None

Total number of possible elements (vocabulary size). When None (the default), the number of observed elements is used.

None
logprob bool

Return log-probabilities if True (the default), otherwise plain probabilities.

True

Returns:

Type Description
LazyScoringMethod

A fitted lazy Laplace scorer.

Examples:

>>> scorer = create_lazy_laplace({"a": 3, "b": 2, "c": 1}, logprob=False)
>>> scorer("a")
0.4444444444444444
>>> scorer("unseen")
0.1111111111111111

Compact storage

Memory-efficient representations for large vocabularies.

This module provides compressed and memory-optimized data structures for handling large-scale frequency distributions and probability models.

CompressedFrequencyDistribution

CompressedFrequencyDistribution(quantization_levels: int | None = None, use_compression: bool = True, intern_strings: bool = True)

Memory-efficient compressed frequency distribution.

This class uses various compression techniques to reduce memory usage for large vocabularies while maintaining fast access patterns.

Techniques used:

  • Integer compression for counts.
  • String interning for element storage.
  • Sparse representation for zero counts.
  • Optional quantization for approximate counts.

Parameters:

Name Type Description Default
quantization_levels int | None

Number of quantization levels for count compression, or None for exact counts. Defaults to None.

None
use_compression bool

Whether to use data compression when serializing. Defaults to True.

True
intern_strings bool

Whether to intern string elements for memory efficiency. Defaults to True.

True

Examples:

Exact counts are preserved when quantization is disabled:

>>> compressed_dist = CompressedFrequencyDistribution()
>>> compressed_dist.update({"word1": 1000, "word2": 500, "word3": 1})
>>> compressed_dist.get_count("word1")
1000
>>> compressed_dist.get_vocabulary_size()
3
>>> compressed_dist.get_total_count()
1501
>>> sorted(compressed_dist.to_dict().items())
[('word1', 1000), ('word2', 500), ('word3', 1)]

Initialize compressed frequency distribution.

from_counts classmethod

from_counts(freqdist: FrequencyDistribution, quantization_levels: int = 65536, use_compression: bool = True) -> CompressedFrequencyDistribution

Build a compressed distribution from a mapping of counts.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required
quantization_levels int

Number of distinct count levels to keep.

65536
use_compression bool

Whether to compress the stored element names.

True

Returns:

Type Description
CompressedFrequencyDistribution

A compressed distribution holding those counts.

Examples:

>>> dist = CompressedFrequencyDistribution.from_counts({"a": 10, "b": 5})
>>> dist.get_count("a")
10
>>> dist.get_vocabulary_size()
2

update

update(freqdist: FrequencyDistribution) -> None

Update with a frequency distribution.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Frequency distribution to add.

required

get_count

get_count(element: Element) -> int

Get count for an element.

Parameters:

Name Type Description Default
element Element

Element to query.

required

Returns:

Type Description
int

Count for the element (dequantized if quantization is used).

get_total_count

get_total_count() -> int

Get total count across all elements.

get_vocabulary_size

get_vocabulary_size() -> int

Get support size.

items

items() -> Iterator[tuple[Element, int]]

Iterate over (element, count) pairs.

keys

keys() -> Iterator[Element]

Iterate over elements with non-zero counts.

values

values() -> Iterator[int]

Iterate over non-zero counts.

to_dict

to_dict() -> dict[Element, int]

Convert to regular dictionary.

get_memory_usage

get_memory_usage() -> dict[str, int]

Get detailed memory usage information.

Returns:

Type Description
dict[str, int]

Memory usage breakdown in bytes, keyed by component, including a

dict[str, int]

"total" entry.

compress_to_bytes

compress_to_bytes() -> bytes

Compress the entire distribution to bytes.

Returns:

Type Description
bytes

Serialized (and optionally gzip-compressed) representation.

decompress_from_bytes classmethod

decompress_from_bytes(compressed_data: bytes, use_compression: bool = True) -> CompressedFrequencyDistribution

Decompress distribution from bytes.

Parameters:

Name Type Description Default
compressed_data bytes

Compressed data to restore.

required
use_compression bool

Whether the data was gzip-compressed. Defaults to True.

True

Returns:

Type Description
CompressedFrequencyDistribution

The reconstructed distribution.

SparseFrequencyDistribution

SparseFrequencyDistribution(default_count: int = 0, use_sorted_storage: bool = True)

Sparse representation for frequency distributions with many zero counts.

This class is optimized for distributions where most elements have zero counts, using sparse data structures for memory efficiency.

Parameters:

Name Type Description Default
default_count int

Default count for unobserved elements. Defaults to 0.

0
use_sorted_storage bool

Whether to keep elements sorted by frequency for faster top-k access. Defaults to True.

True

Examples:

Only non-default counts are stored; missing elements return the default:

>>> sparse_dist = SparseFrequencyDistribution()
>>> sparse_dist.update({"rare_word": 1, "common_word": 1000})
>>> sparse_dist.get_count("rare_word")
1
>>> sparse_dist.get_count("unseen")
0
>>> sparse_dist.get_vocabulary_size()
2
>>> sparse_dist.get_top_k(2)
[('common_word', 1000), ('rare_word', 1)]

Initialize sparse frequency distribution.

from_counts classmethod

from_counts(freqdist: FrequencyDistribution, default_count: int = 0) -> SparseFrequencyDistribution

Build a sparse distribution from a mapping of counts.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Mapping of elements to observed counts.

required
default_count int

Count reported for an element that is not stored.

0

Returns:

Type Description
SparseFrequencyDistribution

A sparse distribution holding those counts.

Examples:

>>> dist = SparseFrequencyDistribution.from_counts({"a": 10, "b": 5})
>>> dist.get_count("a")
10
>>> dist.get_count("unseen")
0

update

update(freqdist: FrequencyDistribution) -> None

Update with a frequency distribution.

Parameters:

Name Type Description Default
freqdist FrequencyDistribution

Frequency distribution to add.

required

increment

increment(element: Element, count: int = 1) -> None

Increment count for a single element.

Parameters:

Name Type Description Default
element Element

Element to increment.

required
count int

Count increment. Defaults to 1.

1

get_count

get_count(element: Element) -> int

Get count for an element.

Parameters:

Name Type Description Default
element Element

Element to query.

required

Returns:

Type Description
int

Count for the element, or the default count if not present.

get_total_count

get_total_count() -> int

Get total count across all elements.

get_vocabulary_size

get_vocabulary_size() -> int

Get number of elements with non-default counts.

get_top_k

get_top_k(k: int) -> list[tuple[Element, int]]

Get top-k most frequent elements.

Parameters:

Name Type Description Default
k int

Number of top elements to return.

required

Returns:

Type Description
list[tuple[Element, int]]

List of (element, count) pairs, highest count first.

get_elements_with_count_range

get_elements_with_count_range(min_count: int, max_count: int) -> list[Element]

Get elements with counts in a specific range.

Parameters:

Name Type Description Default
min_count int

Minimum count (inclusive).

required
max_count int

Maximum count (inclusive).

required

Returns:

Type Description
list[Element]

Elements whose counts fall within the specified range.

get_count_histogram

get_count_histogram() -> dict[int, int]

Get histogram of counts (count -> frequency of that count).

Returns:

Type Description
dict[int, int]

Histogram mapping each count value to how many elements have it.

items

items() -> Iterator[tuple[Element, int]]

Iterate over (element, count) pairs for non-default elements.

keys

keys() -> Iterator[Element]

Iterate over elements with non-default counts.

values

values() -> Iterator[int]

Iterate over non-default counts.

to_dict

to_dict() -> dict[Element, int]

Convert to regular dictionary.

get_memory_usage

get_memory_usage() -> dict[str, int]

Get memory usage information.

Returns:

Type Description
dict[str, int]

Memory usage breakdown in bytes, including a "total" entry.

QuantizedProbabilityTable

QuantizedProbabilityTable(num_quantization_levels: int = 65536, log_space: bool = True)

Quantized probability table for memory-efficient probability storage.

This class stores probabilities using quantization to reduce memory usage while maintaining reasonable precision for most applications.

Parameters:

Name Type Description Default
num_quantization_levels int

Number of quantization levels, which determines precision. Defaults to 65536.

65536
log_space bool

Whether to quantize in log space for better precision. Defaults to True.

True

Examples:

Stored probabilities are approximate; higher level counts are more precise:

>>> prob_table = QuantizedProbabilityTable(num_quantization_levels=1024)
>>> prob_table.set_probabilities(
...     {"word1": 0.5, "word2": 0.3, "word3": 0.2}
... )
>>> round(prob_table.get_probability("word1"), 2)
0.49
>>> sorted(prob_table.get_elements())
['word1', 'word2', 'word3']

Initialize quantized probability table.

set_probabilities

set_probabilities(probabilities: dict[Element, float]) -> None

Set probabilities for multiple elements.

Parameters:

Name Type Description Default
probabilities dict[Element, float]

Mapping of elements to their probabilities.

required

set_probability

set_probability(element: Element, probability: float) -> None

Set probability for a single element.

Parameters:

Name Type Description Default
element Element

Element to set probability for.

required
probability float

Probability value.

required

get_probability

get_probability(element: Element) -> float

Get probability for an element.

Parameters:

Name Type Description Default
element Element

Element to query.

required

Returns:

Type Description
float

Dequantized probability for the element (or the default).

set_default_probability

set_default_probability(default_prob: float) -> None

Set default probability for unobserved elements.

Parameters:

Name Type Description Default
default_prob float

Default probability for unobserved elements.

required

get_elements

get_elements() -> list[Element]

Get all elements with stored probabilities.

get_memory_usage

get_memory_usage() -> dict[str, int]

Get memory usage information.

Returns:

Type Description
dict[str, int]

Memory usage breakdown in bytes, including a "total" entry.

get_quantization_error_stats

get_quantization_error_stats(original_probs: dict[Element, float]) -> dict[str, float]

Analyze quantization error compared to original probabilities.

Parameters:

Name Type Description Default
original_probs dict[Element, float]

Original probabilities to compare against.

required

Returns:

Type Description
dict[str, float]

Error statistics including mean/max absolute and relative errors.

Caches

Caching and memoization utilities for computational efficiency.

This module provides caching mechanisms to speed up expensive calculations in probability smoothing methods, particularly for computationally intensive methods like Simple Good-Turing.

get_cache_stats

get_cache_stats() -> dict[str, int]

Get statistics about global cache usage.

Reports the current number of entries held in each global cache.

Returns:

Type Description
dict[str, int]

A mapping with the keys "sgt_cache_size" and "general_cache_size",

dict[str, int]

each giving the number of cached entries in the corresponding cache.

Examples:

>>> from freqprob import clear_all_caches, get_cache_stats
>>> clear_all_caches()
>>> stats = get_cache_stats()
>>> "sgt_cache_size" in stats
True
>>> stats["general_cache_size"]
0

clear_all_caches

clear_all_caches() -> None

Clear all global computation caches.

Empties both the Simple Good-Turing cache and the general-purpose cache used to memoize expensive smoothing computations. Useful for freeing memory or forcing recomputation.

Examples:

>>> from freqprob import clear_all_caches, get_cache_stats
>>> clear_all_caches()
>>> get_cache_stats()["sgt_cache_size"]
0