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
|
min_count_threshold
|
int
|
Minimum count for elements to be retained.
Defaults to |
1
|
decay_factor
|
float | None
|
Exponential decay factor for aging old observations, or
|
None
|
compression_threshold
|
int
|
Number of updates between compression
operations. Defaults to |
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
|
min_count_threshold
|
int
|
Minimum count threshold for retention. |
1
|
decay_factor
|
float | None
|
Decay factor for time-based forgetting
( |
None
|
compression_threshold
|
int
|
Number of updates before triggering compression. |
10000
|
update ¶
Update count for a single element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
Element
|
Element to update. |
required |
count
|
int
|
Count increment. Defaults to |
1
|
update_batch ¶
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
|
get_count ¶
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 relative frequency for an element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
Element
|
Element to query. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Relative frequency ( |
to_dict ¶
Convert to regular dictionary with integer counts.
Returns:
| Type | Description |
|---|---|
dict[Element, int]
|
Dictionary representation with integer counts. |
get_statistics ¶
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
|
max_vocabulary_size
|
int | None
|
Maximum support size to maintain, or |
None
|
unobs_prob
|
float | None
|
Reserved probability mass for unobserved elements, or
|
None
|
logprob
|
bool
|
Return log-probabilities if |
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 with a single element observation.
update_batch ¶
Update with multiple element observations.
get_streaming_statistics ¶
Get statistics about the streaming distribution.
save_state ¶
Save the current state to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to save the state. |
required |
load_state
classmethod
¶
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
|
max_vocabulary_size
|
int | None
|
Maximum support size to maintain, or |
None
|
bins
|
int | None
|
Total number of possible bins, or |
None
|
logprob
|
bool
|
Return log-probabilities if |
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 ¶
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 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:
score_matrix ¶
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]
|
|
ndarray[Any, Any]
|
with the default probability. |
top_k_elements ¶
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 |
ndarray[Any, Any]
|
from highest to lowest score. |
percentile_scores ¶
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 ¶
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 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 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 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
|
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
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Returns:
| Type | Description |
|---|---|
LazyScoringMethod
|
A fitted lazy MLE scorer. |
Examples:
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
|
logprob
|
bool
|
Return log-probabilities if |
True
|
Returns:
| Type | Description |
|---|---|
LazyScoringMethod
|
A fitted lazy Laplace scorer. |
Examples:
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
|
use_compression
|
bool
|
Whether to use data compression when serializing.
Defaults to |
True
|
intern_strings
|
bool
|
Whether to intern string elements for memory
efficiency. Defaults to |
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:
update ¶
Update with a frequency distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution to add. |
required |
get_count ¶
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_memory_usage ¶
Get detailed memory usage information.
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Memory usage breakdown in bytes, keyed by component, including a |
dict[str, int]
|
|
compress_to_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
|
Returns:
| Type | Description |
|---|---|
CompressedFrequencyDistribution
|
The reconstructed distribution. |
SparseFrequencyDistribution ¶
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
|
use_sorted_storage
|
bool
|
Whether to keep elements sorted by frequency for
faster top-k access. Defaults to |
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
¶
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:
update ¶
Update with a frequency distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freqdist
|
FrequencyDistribution
|
Frequency distribution to add. |
required |
increment ¶
Increment count for a single element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
Element
|
Element to increment. |
required |
count
|
int
|
Count increment. Defaults to |
1
|
get_count ¶
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_top_k ¶
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 |
get_elements_with_count_range ¶
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 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 ¶
Iterate over (element, count) pairs for non-default elements.
get_memory_usage ¶
Get memory usage information.
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Memory usage breakdown in bytes, including a |
QuantizedProbabilityTable ¶
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
|
log_space
|
bool
|
Whether to quantize in log space for better precision.
Defaults to |
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 for multiple elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probabilities
|
dict[Element, float]
|
Mapping of elements to their probabilities. |
required |
set_probability ¶
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 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 for unobserved elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_prob
|
float
|
Default probability for unobserved elements. |
required |
get_memory_usage ¶
Get memory usage information.
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Memory usage breakdown in bytes, including a |
get_quantization_error_stats ¶
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 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 |
dict[str, int]
|
each giving the number of cached entries in the corresponding cache. |
Examples:
clear_all_caches ¶
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: