Skip to content

asymcat.scorer.CatScorer

Class for computing categorical co-occurrence scores.

Initialization function.

Parameters:

Name Type Description Default
cooccs List[Tuple[Any, Any]]

A list of co-occurrence tuples.

required
smoothing_method str

Smoothing method for probability estimation. Options: 'mle', 'laplace', 'lidstone'. Default is 'mle'.

'mle'
smoothing_alpha float

Additive constant for 'lidstone' smoothing (its gamma); 'laplace' always adds 1 and 'mle' adds nothing. Default is 1.0.

1.0
entropy_estimator str

Estimator for the entropies behind theil_u, cond_entropy, mutual_information and normalized_mutual_information. Options: 'plugin' (the maximum-likelihood estimate), 'chao_shen' and 'nsb' (bias-corrected estimators for undersampled data, from freqprob). Default is 'plugin'.

'plugin'

mle

mle() -> dict[tuple[Any, Any], tuple[float, float]]

Return an MLE scorer of conditional probabilities, computing it if necessary.

For every pair (x, y) the tuple is (P(y|x), P(x|y)): how well x predicts y, then how well y predicts x. This is the same X→Y, Y→X order as theil_u, cond_entropy and goodman_kruskal_lambda. With smoothing_method set to "laplace" or "lidstone", the probabilities are smoothed with freqprob.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (P(y|x), P(x|y)) tuples.

get_smoothed_probabilities

get_smoothed_probabilities() -> dict[str, dict[Any, float]]

Return smoothed probability estimates using the configured freqprob method.

The joint distribution over all pairs of observed symbols is smoothed with the scorer's smoothing_method, and the marginal and conditional distributions are derived from it, so that they are consistent with each other.

Returns:

Type Description
Dict[str, Dict[Any, float]]

Dictionary containing 'xy_given_y', 'yx_given_x' and 'joint', keyed by symbol pair, and 'marginal_x' and 'marginal_y', keyed by symbol.

pmi_smoothed

pmi_smoothed(normalized: bool = False) -> dict[tuple[Any, Any], tuple[float, float]]

Return a PMI scorer using freqprob smoothing for better numerical stability.

The probabilities come from get_smoothed_probabilities: the joint distribution smoothed with the scorer's smoothing_method, and the marginals derived from it. Use it with smoothing_method="laplace" or "lidstone"; with the default "mle", unobserved pairs get a near-zero probability and a very large negative score.

Parameters:

Name Type Description Default
normalized bool

Whether to return normalized PMI (NPMI) or standard PMI (default: False)

False

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

PMI scores for each pair (X→Y, Y→X)

pmi

pmi(normalized: bool = False) -> dict[tuple[Any, Any], tuple[float, float]]

Return a PMI scorer.

Parameters:

Name Type Description Default
normalized bool

Whether to return a normalized PMI or not (default: False)

False

chi2

chi2(square_ct: bool = True) -> dict[tuple[Any, Any], tuple[float, float]]

Return a Chi2 scorer.

Parameters:

Name Type Description Default
square_ct bool

Whether to return the score over the 2x2 contingency table (default: True). False, which uses a 2x3 table, is deprecated.

True

chi2_pvalue

chi2_pvalue(square_ct: bool = True) -> dict[tuple[Any, Any], tuple[float, float]]

Return the p-values of the chi-square test of independence.

This is the significance counterpart to chi2: for each pair it returns the p-value from scipy.stats.chi2_contingency (a small value indicates a statistically significant association). As with the other symmetric statistical tests, both tuple entries hold the same value.

Parameters:

Name Type Description Default
square_ct bool

Whether to compute the p-value over the 2x2 contingency table (default: True). False, which uses a 2x3 table, is deprecated.

True

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (p-value, p-value) tuples.

cramers_v

cramers_v(square_ct: bool = True) -> dict[tuple[Any, Any], tuple[float, float]]

Return a Cramér's V scorer.

Parameters:

Name Type Description Default
square_ct bool

Whether to return the score over the 2x2 contingency table (default: True). False, which uses a 2x3 table, is deprecated.

True

fisher

fisher() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Fisher Exact Odds Ratio scorer.

For each pair, this is the sample odds ratio (a * d) / (b * c) of the 2x2 contingency table, as returned by scipy.stats.fisher_exact. It is the unconditional maximum-likelihood estimate; R's fisher.test reports the conditional one, which differs slightly. A table with an empty cell gives an odds ratio of 0 or inf. Both tuple entries hold the same value; the p-values are given by fisher_pvalue.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (odds ratio, odds ratio) tuples.

fisher_pvalue

fisher_pvalue() -> dict[tuple[Any, Any], tuple[float, float]]

Return the p-values of Fisher's exact test.

This is the significance counterpart to fisher: for each pair it returns the (two-sided) p-value from scipy.stats.fisher_exact over the 2x2 contingency table. As with the other symmetric statistical tests, both tuple entries hold the same value.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (p-value, p-value) tuples.

theil_u

theil_u() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Theil's U uncertainty scorer.

For every pair (x, y) this computes Theil's U in both directions over the subset of co-occurrences where pair[0] == x or pair[1] == y, matching compute_theil_u(Y, X) and compute_theil_u(X, Y) on that subset. The underlying entropies are computed with a vectorized formulation (see _subset_entropy_components) that evaluates all pairs at once rather than re-filtering the co-occurrence list for each pair.

Entropies follow the scorer's entropy_estimator. Bias-corrected estimates are not confined to [0, 1]: a slightly negative value on a small subset means no detectable association.

cond_entropy

cond_entropy() -> dict[tuple[Any, Any], tuple[float, float]]

Return a corrected conditional entropy scorer.

For every pair (x, y) this computes the conditional entropy in both directions over the subset of co-occurrences where pair[0] == x or pair[1] == y, matching conditional_entropy(Y, X) and conditional_entropy(X, Y) on that subset. The entropies come from the same computation as theil_u (see _subset_entropy_components) and follow the scorer's entropy_estimator.

tresoldi

tresoldi() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Tresoldi scorer, the measure ASymCat provides for alignments.

For every pair (x, y) the tuple is (T(x→y), T(y→x)), with T(x→y) = sign(PMI) * |PMI(x, y)| ** (1 - P(y|x)): the PMI pulled towards ±1 as the conditional probability approaches 1. The conditional probabilities come from mle (so smoothing applies to them) and the PMI from pmi. See the documentation page "The Tresoldi measure" for its properties.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (T(x→y), T(y→x)) tuples.

mutual_information

mutual_information() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Mutual Information scorer.

Computes MI(X;Y) and MI(Y;X) for each symbol pair, measuring the overall statistical dependence between the symbols. Entropies follow the scorer's entropy_estimator; bias-corrected estimates can be slightly negative on small subsets.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (MI(X;Y), MI(Y;X)) tuples.

normalized_mutual_information

normalized_mutual_information() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Normalized Mutual Information scorer.

Computes NMI(X;Y) and NMI(Y;X) for each symbol pair, measuring the statistical dependence normalized by joint entropy (range [0,1] for the plug-in estimator). Entropies follow the scorer's entropy_estimator.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (NMI(X;Y), NMI(Y;X)) tuples.

jaccard_index

jaccard_index() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Jaccard Index scorer.

Computes the Jaccard similarity coefficient between the context sets of each symbol pair, measuring overlap in their distributions.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (J(contexts_x, contexts_y), J(contexts_y, contexts_x)) tuples.

goodman_kruskal_lambda

goodman_kruskal_lambda() -> dict[tuple[Any, Any], tuple[float, float]]

Return a Goodman-Kruskal Lambda scorer.

Computes λ(Y|X) and λ(X|Y) for each symbol pair, measuring the proportional reduction in error when predicting one variable from another. Like theil_u, it is computed on the subset of co-occurrences where pair[0] == x or pair[1] == y; when the predicted variable takes a single value in that subset, the score is 1.0, as for theil_u.

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (λ(Y|X), λ(X|Y)) tuples.

log_likelihood_ratio

log_likelihood_ratio(square_ct: bool = True) -> dict[tuple[Any, Any], tuple[float, float]]

Return a Log-Likelihood Ratio (G²) scorer.

Computes the G² statistic as an alternative to Chi-square that works better with small expected frequencies.

Parameters:

Name Type Description Default
square_ct bool

Whether to return the score over the 2x2 contingency table (default: True). False, which uses a 2x3 table, is deprecated.

True

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (G²(X,Y), G²(Y,X)) tuples.

log_likelihood_ratio_pvalue

log_likelihood_ratio_pvalue(square_ct: bool = True) -> dict[tuple[Any, Any], tuple[float, float]]

Return the p-values of the Log-Likelihood Ratio (G²) test.

This is the significance counterpart to log_likelihood_ratio: under the null hypothesis of independence, G² is asymptotically chi-square distributed, and this returns the corresponding p-value for each pair. As with the other symmetric statistical tests, both tuple entries hold the same value.

Parameters:

Name Type Description Default
square_ct bool

Whether to compute the p-value over the 2x2 contingency table (default: True). False, which uses a 2x3 table, is deprecated.

True

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (p-value, p-value) tuples.

permutation_pvalue

permutation_pvalue(measure: str, n_permutations: int = 1000, alternative: str = 'greater', seed: int | None = None) -> dict[tuple[Any, Any], tuple[float, float]]

Estimate permutation-based p-values for an association measure.

Unlike the parametric tests (chi2_pvalue, fisher_pvalue, log_likelihood_ratio_pvalue), this works for any per-pair association measure -- including the information-theoretic ones (PMI, mutual information, Theil's U, ...) that have no closed-form null distribution.

The null hypothesis is that the two variables are independent. A null distribution is built by repeatedly shuffling the pairing between the x and y elements of the co-occurrences (which preserves both marginal frequency distributions and the total count while destroying the joint association) and recomputing the measure. For each pair and direction, the p-value is the fraction of permutations whose score is at least as extreme as the observed one, using the (count + 1) / (n_permutations + 1) correction so the estimate is never exactly zero.

Because the co-occurrences are treated as exchangeable, sequences that expand into many correlated co-occurrences (e.g. n-gram collection) make this test slightly anti-conservative; interpret accordingly.

Parameters:

Name Type Description Default
measure str

Name of the association measure to test; must be one of RESAMPLABLE_MEASURES. It is computed with its default parameters.

required
n_permutations int

Number of random permutations forming the null distribution (default: 1000). Larger values give finer-grained p-values (the smallest reportable p-value is 1 / (n_permutations + 1)).

1000
alternative str

Which tail to test, matching SciPy's convention:

  • "greater" (default): significant when the observed score is unusually high -- appropriate for measures where a larger value means stronger association (PMI, mutual information, Theil's U, chi-square, ...).
  • "less": significant when the observed score is unusually low -- appropriate for measures where a smaller value means stronger association (e.g. cond_entropy).
  • "two-sided": significant in either tail.
'greater'
seed Optional[int]

Seed for the random number generator, for reproducible results (default: None, i.e. non-deterministic).

None

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[float, float]]

Dictionary mapping symbol pairs to (p_xy, p_yx) p-values, one per direction, aligned with the measure's own output.

Raises:

Type Description
ValueError

If measure is not supported, alternative is invalid, or n_permutations is not a positive integer.

bootstrap_ci

bootstrap_ci(measure: str, n_bootstrap: int = 1000, confidence_level: float = 0.95, seed: int | None = None) -> dict[tuple[Any, Any], tuple[tuple[float, float], tuple[float, float]]]

Estimate bootstrap confidence intervals for an association measure.

Whereas permutation_pvalue tests whether an association differs from independence, this quantifies the sampling uncertainty around the observed score. A bootstrap distribution is built by resampling the co-occurrences with replacement (n draws from the n observed pairs, preserving each pair's x/y link) and recomputing the measure; the confidence interval is taken as the percentile interval of that distribution, per pair and direction.

The point estimate itself is not returned -- obtain it from the measure method directly (e.g. scorer.theil_u()).

Because resampling can drop a rarely-seen symbol from a replicate, a pair may be absent from some replicates; such replicates simply do not contribute to that pair's interval. As with permutation_pvalue, co-occurrences are treated as exchangeable, so sequence data that expands into many correlated co-occurrences yields intervals that are somewhat too narrow.

Parameters:

Name Type Description Default
measure str

Name of the association measure; must be one of RESAMPLABLE_MEASURES. It is computed with its default parameters.

required
n_bootstrap int

Number of bootstrap replicates (default: 1000).

1000
confidence_level float

Confidence level in the open interval (0, 1) (default: 0.95 for a 95% interval, i.e. the 2.5th and 97.5th percentiles).

0.95
seed Optional[int]

Seed for the random number generator, for reproducible results (default: None, i.e. non-deterministic).

None

Returns:

Type Description
Dict[Tuple[Any, Any], Tuple[Tuple[float, float], Tuple[float, float]]]

Dictionary mapping symbol pairs to ((xy_low, xy_high), (yx_low, yx_high)) -- a lower/upper bound for each direction, aligned with the measure's own output.

Raises:

Type Description
ValueError

If measure is not supported, confidence_level is not in (0, 1), or n_bootstrap is not a positive integer.