Skip to content

Association metrics

bic

bic(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute the Bayes factor BIC for contingency table data.

Discounts the log-likelihood ratio by a penalty that grows with the corpus size, so the threshold a word has to clear rises as the corpora get bigger. In a corpus of a hundred million words almost every difference is significant by \(G^2\); BIC asks instead how much the evidence outweighs the number of observations it rests on.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the BIC values for each variable pair.

Notes

BIC is calculated as:

\[ \text{BIC} = |G^2| - \log n \]

where \(G^2\) is the log-likelihood ratio and the penalty is \(d\log n\) for the \(d = 1\) degree of freedom of a 2×2 table. Wilson reads the result as degrees of evidence: 0-2 is not worth more than a bare mention, 2-6 is positive, 6-10 is strong, and above 10 is very strong.

Wilson writes \(G^2\) unsigned. loglik here carries the sign of the deviation instead, so BIC takes its magnitude and, like chisq, says how strong the evidence is without saying which way it points. Pair it with logratio or pctdiff for the direction.

References
  • Wilson, A. 2013. Embracing Bayes factors for key item analysis in corpus linguistics. In M. Bieswanger and A. Koll-Stobbe (eds.), New Approaches to the Study of Linguistic Variability, 3-11. Frankfurt: Peter Lang.
Source code in python/polars_corpus/assoc.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def bic(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    r"""
    Compute the Bayes factor BIC for contingency table data.

    Discounts the log-likelihood ratio by a penalty that grows with the corpus
    size, so the threshold a word has to clear rises as the corpora get bigger.
    In a corpus of a hundred million words almost every difference is
    significant by $G^2$; BIC asks instead how much the evidence outweighs the
    number of observations it rests on.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the BIC values for each variable
        pair.

    Notes
    -----
    BIC is calculated as:

    $$
    \text{BIC} = |G^2| - \log n
    $$

    where $G^2$ is the log-likelihood ratio and the penalty is $d\log n$ for
    the $d = 1$ degree of freedom of a 2×2 table. Wilson reads the result as
    degrees of evidence: 0-2 is not worth more than a bare mention, 2-6 is
    positive, 6-10 is strong, and above 10 is very strong.

    Wilson writes $G^2$ unsigned. `loglik` here carries the sign of the
    deviation instead, so BIC takes its magnitude and, like `chisq`, says how
    strong the evidence is without saying which way it points. Pair it with
    `logratio` or `pctdiff` for the direction.

    References
    ----------
    - Wilson, A. 2013. Embracing Bayes factors for key item analysis in corpus
      linguistics. In M. Bieswanger and A. Koll-Stobbe (eds.), *New Approaches
      to the Study of Linguistic Variability*, 3-11. Frankfurt: Peter Lang.
    """
    _, _, _, size = _as_freqs(f12, f1, f2, n)
    return loglik(f12, f1, f2, n).abs() - size.log()

chisq

chisq(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    yates: bool = False,
) -> pl.Expr

Compute Pearson's chi-squared (χ²) statistic for contingency table data.

Calculates the chi-squared statistic measuring the association strength between two categorical variables by comparing observed frequencies to those expected under statistical independence, using the closed-form expression for a 2×2 table.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

  • yates (bool, default: False ) –

    Whether to apply Yates' continuity correction. When True, matches the default behaviour of :func:scipy.stats.chi2_contingency for 2×2 tables.

Returns:

  • Expr –

    A Polars expression that computes the chi-squared values for each variable pair.

Notes

For a 2×2 contingency table the statistic reduces to:

\[ \chi^2 = \frac{n\,(|n\,f_{12} - f_1\,f_2| - c)^2} {f_1\,f_2\,(n - f_1)\,(n - f_2)} \]

where the continuity-correction term is \(c = n/2\) when yates is True and \(c = 0\) otherwise.

Source code in python/polars_corpus/assoc.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def chisq(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    yates: bool = False,
) -> pl.Expr:
    """
    Compute Pearson's chi-squared (χ²) statistic for contingency table data.

    Calculates the chi-squared statistic measuring the association strength
    between two categorical variables by comparing observed frequencies to
    those expected under statistical independence, using the closed-form
    expression for a 2×2 table.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.
    yates : bool, default False
        Whether to apply Yates' continuity correction. When True, matches the
        default behaviour of :func:`scipy.stats.chi2_contingency` for 2×2 tables.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the chi-squared values for each
        variable pair.

    Notes
    -----
    For a 2×2 contingency table the statistic reduces to:

    $$
    \\chi^2 = \\frac{n\\,(|n\\,f_{12} - f_1\\,f_2| - c)^2}
                  {f_1\\,f_2\\,(n - f_1)\\,(n - f_2)}
    $$

    where the continuity-correction term is $c = n/2$ when `yates` is True
    and $c = 0$ otherwise.
    """

    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)

    o11 = f12
    o12 = f1 - f12
    o21 = f2 - f12
    o22 = n - f1 - f2 + f12

    det = o11 * o22 - o12 * o21
    if yates:
        det = det.abs() - n / 2
    return n * det.pow(2) / (f1 * f2 * (n - f1) * (n - f2))

crosstab

crosstab(
    corpus: T_Frame, x: IntoExprColumn, y: IntoExprColumn
) -> T_Frame

Create a cross-tabulation (contingency table) from two categorical variables.

Computes a contingency table showing the joint frequency distribution of two categorical variables, along with marginal totals and grand total. Null values in either variable are automatically excluded from the analysis.

Parameters:

  • corpus (T_Frame) –

    Input data as a Polars DataFrame or LazyFrame containing the variables.

  • x (IntoExprColumn) –

    Column name, expression or Series giving the first categorical variable (row variable).

  • y (IntoExprColumn) –

    Column name, expression or Series giving the second categorical variable (column variable).

Returns:

  • T_Frame –

    The contingency table with the following columns:

    • x : Levels/categories of the first variable
    • y : Levels/categories of the second variable
    • freqs : Struct with fields {f12, f1, f2, n} where:
      • f12: joint frequency (count of x,y pairs)
      • f1: row marginal (total count for this x value)
      • f2: column marginal (total count for this y value)
      • n: grand total

Raises:

  • ValueError –

    If corpus is not a Polars DataFrame or LazyFrame, or is empty; or if x or y does not name a column.

Source code in python/polars_corpus/assoc.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def crosstab(corpus: T_Frame, x: IntoExprColumn, y: IntoExprColumn) -> T_Frame:
    """
    Create a cross-tabulation (contingency table) from two categorical variables.

    Computes a contingency table showing the joint frequency distribution
    of two categorical variables, along with marginal totals and grand total.
    Null values in either variable are automatically excluded from the analysis.

    Parameters
    ----------
    corpus : T_Frame
        Input data as a Polars DataFrame or LazyFrame containing the variables.
    x : IntoExprColumn
        Column name, expression or Series giving the first categorical
        variable (row variable).
    y : IntoExprColumn
        Column name, expression or Series giving the second categorical
        variable (column variable).

    Returns
    -------
    T_Frame
        The contingency table with the following columns:

        - x : Levels/categories of the first variable
        - y : Levels/categories of the second variable
        - freqs : Struct with fields {f12, f1, f2, n} where:
            - f12: joint frequency (count of x,y pairs)
            - f1: row marginal (total count for this x value)
            - f2: column marginal (total count for this y value)
            - n: grand total

    Raises
    ------
    ValueError
        If `corpus` is not a Polars DataFrame or LazyFrame, or is empty; or if
        `x` or `y` does not name a column.
    """
    lf = as_corpus(corpus)

    x_name = (
        x.name
        if isinstance(x, pl.Series)
        else check_expr(lf, as_expr(x, "x"), param="x")
    )
    y_name = (
        y.name
        if isinstance(y, pl.Series)
        else check_expr(lf, as_expr(y, "y"), param="y")
    )

    counts = lf.select(x, y).drop_nulls()
    result = (
        counts.group_by(x_name, y_name)
        .agg(pl.len().cast(pl.UInt64).alias("f12"))
        .with_columns(
            pl.struct(
                pl.col("f12"),
                pl.col("f12").sum().over(x_name).alias("f1"),
                pl.col("f12").sum().over(y_name).alias("f2"),
                pl.col("f12").sum().alias("n"),
            ).alias("freqs")
        )
        .drop("f12")
    )
    return collect_like(result, corpus)

logdice

logdice(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute the log-Dice association measure for contingency table data.

A logarithmic form of the Dice coefficient, which weighs the joint frequency against the two marginals rather than against the corpus size. This is the default collocation score in Sketch Engine and #LancsBox.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Accepted for a uniform signature with the other measures, but not used.

Returns:

  • Expr –

    A Polars expression that computes the log-Dice values for each variable pair.

Notes

Log-Dice is calculated as:

\[ \text{logDice}(x,y) = 14 + \log_2\frac{2\,f_{12}}{f_1 + f_2} \]

The base-2 logarithm and the constant 14 go together: they place the maximum at 14, where every occurrence of one word is an occurrence of the pair, and each further point down the scale halves the Dice coefficient. Values below 0 are conventionally treated as no association.

References
  • Rychlý, P. 2008. A lexicographer-friendly association score. In Proceedings of Recent Advances in Slavonic Natural Language Processing (RASLAN), 6-9. Brno: Masaryk University.
Source code in python/polars_corpus/assoc.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def logdice(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute the log-Dice association measure for contingency table data.

    A logarithmic form of the Dice coefficient, which weighs the joint
    frequency against the two marginals rather than against the corpus size. This
    is the default collocation score in Sketch Engine and #LancsBox.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Accepted for a uniform
        signature with the other measures, but not used.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the log-Dice values for each
        variable pair.

    Notes
    -----
    Log-Dice is calculated as:

    $$
    \\text{logDice}(x,y) = 14 + \\log_2\\frac{2\\,f_{12}}{f_1 + f_2}
    $$

    The base-2 logarithm and the constant 14 go together: they place the
    maximum at 14, where every occurrence of one word is an occurrence of the
    pair, and each further point down the scale halves the Dice coefficient.
    Values below 0 are conventionally treated as no association.

    References
    ----------
    - Rychlý, P. 2008. A lexicographer-friendly association score. In
      *Proceedings of Recent Advances in Slavonic Natural Language Processing
      (RASLAN)*, 6-9. Brno: Masaryk University.
    """
    f12, f1, f2, _ = _as_freqs(f12, f1, f2, n)
    return 14 + (2 * f12 / (f1 + f2)).log(2)

loglik

loglik(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute log-likelihood ratio (G²) statistic for contingency table data.

Calculates the log-likelihood ratio statistic (also known as G² or G-squared) which measures the association strength between two categorical variables by comparing observed frequencies to those expected under statistical independence.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the log-likelihood ratio values for each variable pair.

Notes

The log-likelihood ratio statistic (G²) is calculated as:

\[ \begin{align*} G^2 = 2 \Bigl( &f_{12} \log\frac{f_{12}}{e_{12}} + (f_1 - f_{12}) \log\frac{f_1 - f_{12}}{f_1 - e_{12}}\\ &+ (f_2 - f_{12}) \log\frac{f_2 - f_{12}}{f_2 - e_{12}} + (n - f_1 - f_2 + f_{12}) \log\frac{n - f_1 - f_2 + f_{12}}{n - f_1 - f_2 + e_{12}} \Bigr) \end{align*} \]

where the four terms are the cells of the 2×2 table and \(e_{12} = f_1\,f_2 / n\) is the joint frequency expected under independence.

References
  • Dunning, T. 1993. Accurate methods for the statistics of surprise and coincidence. Computational Linguistics 19:61–74.
Source code in python/polars_corpus/assoc.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def loglik(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute log-likelihood ratio (G²) statistic for contingency table data.

    Calculates the log-likelihood ratio statistic (also known as G² or
    G-squared) which measures the association strength between two categorical
    variables by comparing observed frequencies to those expected under
    statistical independence.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the log-likelihood ratio values
        for each variable pair.

    Notes
    -----
    The log-likelihood ratio statistic (G²) is calculated as:

    $$
    \\begin{align*}
    G^2 = 2 \\Bigl(
      &f_{12} \\log\\frac{f_{12}}{e_{12}}
      + (f_1 - f_{12}) \\log\\frac{f_1 - f_{12}}{f_1 - e_{12}}\\\\
      &+ (f_2 - f_{12}) \\log\\frac{f_2 - f_{12}}{f_2 - e_{12}}
      + (n - f_1 - f_2 + f_{12})
        \\log\\frac{n - f_1 - f_2 + f_{12}}{n - f_1 - f_2 + e_{12}}
    \\Bigr)
    \\end{align*}
    $$

    where the four terms are the cells of the 2×2 table and
    $e_{12} = f_1\\,f_2 / n$ is the joint frequency expected under
    independence.

    References
    ----------
    - Dunning, T. 1993. Accurate methods for the statistics of surprise and
    coincidence. *Computational Linguistics* 19:61–74.
    """
    return register_plugin_function(
        plugin_path=LIB,
        args=list(_as_freqs(f12, f1, f2, n)),
        function_name="py_loglik",
        is_elementwise=True,
    )

logratio

logratio(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr

Compute Hardie's log ratio for keyword contingency table data.

Compares how common a word is in the target corpus with how common it is in the reference, on a base-2 log scale: 1 means twice as common in the target, 2 means four times, and a negative value means it is rarer there. This is an effect size rather than a test. It says how large the difference is, not how strong the evidence for it is, and it does not grow with the corpus.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

  • discount (float, default: 0.5 ) –

    Count to stand in for a frequency of zero, so that a word missing from one corpus gets a large log ratio rather than an infinite one. Set it to 0 to leave the infinities in place.

Returns:

  • Expr –

    A Polars expression that computes the log ratio for each variable pair.

Notes

Log ratio is calculated as:

\[ \text{LR}(x,y) = \log_2\frac{f_{12} / f_2}{(f_1 - f_{12}) / (n - f_2)} \]

Unlike the other measures here this one is not symmetric in its two margins. It reads them as crosstab lays them out for a word by corpus part table, which is what keywords passes it: \(f_{12}\) is the word's frequency in the target corpus and \(f_2\) the size of that corpus, while \(f_1\) is the word's frequency in both corpora together and \(n\) their combined size. The reference corpus frequency is therefore \(f_1 - f_{12}\) and its size \(n - f_2\).

A word absent from the reference corpus has no ratio, and discount replaces that zero frequency. Such a word is then ranked by the constant as much as by its own frequency, so the top of a log ratio list is worth reading with min_target_freq set.

References
  • Hardie, A. 2014. Log Ratio: an informal introduction. ESRC Centre for Corpus Approaches to Social Science (CASS), Lancaster University.
Source code in python/polars_corpus/assoc.py
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def logratio(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr:
    r"""
    Compute Hardie's log ratio for keyword contingency table data.

    Compares how common a word is in the target corpus with how common it is in
    the reference, on a base-2 log scale: 1 means twice as common in the target,
    2 means four times, and a negative value means it is rarer there. This is an
    effect size rather than a test. It says how large the difference is, not how
    strong the evidence for it is, and it does not grow with the corpus.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.
    discount : float, default 0.5
        Count to stand in for a frequency of zero, so that a word missing from
        one corpus gets a large log ratio rather than an infinite one. Set it to
        0 to leave the infinities in place.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the log ratio for each variable pair.

    Notes
    -----
    Log ratio is calculated as:

    $$
    \text{LR}(x,y) = \log_2\frac{f_{12} / f_2}{(f_1 - f_{12}) / (n - f_2)}
    $$

    Unlike the other measures here this one is not symmetric in its two
    margins. It reads them as `crosstab` lays them out for a word by corpus
    part table, which is what `keywords` passes it: $f_{12}$ is the word's
    frequency in the target corpus and $f_2$ the size of that corpus, while
    $f_1$ is the word's frequency in both corpora together and $n$ their
    combined size. The reference corpus frequency is therefore $f_1 - f_{12}$
    and its size $n - f_2$.

    A word absent from the reference corpus has no ratio, and `discount`
    replaces that zero frequency. Such a word is then ranked by the constant as
    much as by its own frequency, so the top of a log ratio list is worth
    reading with `min_target_freq` set.

    References
    ----------
    - Hardie, A. 2014. Log Ratio: an informal introduction. *ESRC Centre for
      Corpus Approaches to Social Science (CASS)*, Lancaster University.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    target, reference = _rel_freqs(f12, f1, f2, n, discount)
    return (target / reference).log(2)

mi3

mi3(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute the MI3 association measure for contingency table data.

Cubes the joint frequency before comparing it to what independence predicts, which pulls the ranking away from the rare pairs that dominate pmi and towards pairs that are both frequent and strongly associated.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the MI3 values for each variable pair.

Notes

MI3 is calculated as:

\[ \text{MI3}(x,y) = \log\frac{f_{12}^3}{e_{12}} = \log\frac{f_{12}^3\,n}{f_1\,f_2} \]

where \(e_{12} = f_1\,f_2 / n\) is the joint frequency expected under independence. Like pmi, this uses natural logarithms, so the two are on the same scale and differ by exactly \(2 \log f_{12}\).

References
  • Daille, B. 1994. Approche mixte pour l’extraction automatique de terminologie: statistiques lexicales et filtres linguistiques. Ph.D. thesis, Université Paris 7.
Source code in python/polars_corpus/assoc.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def mi3(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute the MI3 association measure for contingency table data.

    Cubes the joint frequency before comparing it to what independence
    predicts, which pulls the ranking away from the rare pairs that dominate
    `pmi` and towards pairs that are both frequent and strongly associated.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the MI3 values for each variable pair.

    Notes
    -----
    MI3 is calculated as:

    $$
    \\text{MI3}(x,y) = \\log\\frac{f_{12}^3}{e_{12}}
                     = \\log\\frac{f_{12}^3\\,n}{f_1\\,f_2}
    $$

    where $e_{12} = f_1\\,f_2 / n$ is the joint frequency expected under
    independence. Like `pmi`, this uses natural logarithms, so the two are on
    the same scale and differ by exactly $2 \\log f_{12}$.

    References
    ----------
    - Daille, B. 1994. *Approche mixte pour l’extraction automatique de
      terminologie: statistiques lexicales et filtres linguistiques.* Ph.D. thesis,
      Université Paris 7.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    return (f12.pow(3) * n / (f1 * f2)).log()

minsens

minsens(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute minimum sensitivity values for contingency table data.

Calculates the minimum sensitivity (minimum of precision and recall) as an association measure between two categorical variables. This metric represents the smaller of the two conditional probabilities: P(y|x) and P(x|y).

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the minimum sensitivity values for each variable pair.

Notes

Minimum sensitivity is calculated as:

\[ \begin{align*} \text{minsens}(x,y) &= \min(P(y|x), P(x|y))\\ &= \min\left(\frac{f_{12}}{f_1}, \frac{f_{12}}{f_2}\right) \end{align*} \]
References
  • Wiechmann, D. 2008. On the computation of collostruction strength: Testing measures of association as expressions of lexical bias. Corpus Linguistics and Linguistic Theory 4(2): 253–290.
Source code in python/polars_corpus/assoc.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
def minsens(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute minimum sensitivity values for contingency table data.

    Calculates the minimum sensitivity (minimum of precision and recall)
    as an association measure between two categorical variables. This metric
    represents the smaller of the two conditional probabilities: P(y|x) and P(x|y).

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the minimum sensitivity values
        for each variable pair.

    Notes
    -----
    Minimum sensitivity is calculated as:

    $$
    \\begin{align*}
    \\text{minsens}(x,y) &= \\min(P(y|x), P(x|y))\\\\
    &= \\min\\left(\\frac{f_{12}}{f_1}, \\frac{f_{12}}{f_2}\\right)
    \\end{align*}
    $$

    References
    ----------
    - Wiechmann, D. 2008. On the computation of collostruction strength: Testing measures of
      association as expressions of lexical bias. *Corpus Linguistics and Linguistic
      Theory* 4(2): 253–290.
    """
    f12, f1, f2, _ = _as_freqs(f12, f1, f2, n)
    precision, recall = f12 / f1, f12 / f2
    # min_horizontal skips nulls, which would leave the other ratio standing in
    # for the minimum; the measure propagates them like every other one here.
    return (
        pl.when(precision.is_null() | recall.is_null())
        .then(None)
        .otherwise(pl.min_horizontal(precision, recall))
    )

oddsratio

oddsratio(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr

Compute the odds ratio for contingency table data.

Divides the odds that a token of the target corpus is this word by the same odds in the reference corpus. 1 means the word is no more likely in one than the other, 2 means the odds are twice as high in the target. Like logratio it measures the size of the difference rather than the evidence for it.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

  • discount (float, default: 0.5 ) –

    Count to stand in for a cell of zero, so that a word missing from one corpus gets a large odds ratio rather than an infinite one. Set it to 0 to leave the infinities in place.

Returns:

  • Expr –

    A Polars expression that computes the odds ratio for each variable pair.

Notes

For a 2×2 contingency table the odds ratio is:

\[ \text{OR} = \frac{o_{11}\,o_{22}}{o_{12}\,o_{21}} = \frac{f_{12}\,(n - f_1 - f_2 + f_{12})} {(f_1 - f_{12})\,(f_2 - f_{12})} \]

Swapping the two margins leaves this unchanged, so unlike logratio it does not care which of them is the corpus part. Values run from 0 to infinity with 1 at independence, which is an awkward scale to average or plot. Take the logarithm for one that is symmetric about 0.

Odds and relative frequency are close for anything that is a small share of a corpus, so for most words the odds ratio comes out near \(2^{\text{LR}}\). It rises above that for a word frequent enough that removing its own tokens changes the corpus it is measured against.

Replacing a zero cell with discount is the usual 0.5 correction for an odds ratio with an empty cell.

References
  • Pojanapunya, P. and R. Watson Todd. 2018. Log-likelihood and odds ratio: Keyness statistics for different purposes of keyword analysis. Corpus Linguistics and Linguistic Theory 14(1): 133-167.
Source code in python/polars_corpus/assoc.py
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
def oddsratio(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr:
    r"""
    Compute the odds ratio for contingency table data.

    Divides the odds that a token of the target corpus is this word by the same
    odds in the reference corpus. 1 means the word is no more likely in one than
    the other, 2 means the odds are twice as high in the target. Like `logratio`
    it measures the size of the difference rather than the evidence for it.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.
    discount : float, default 0.5
        Count to stand in for a cell of zero, so that a word missing from one
        corpus gets a large odds ratio rather than an infinite one. Set it to 0
        to leave the infinities in place.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the odds ratio for each variable pair.

    Notes
    -----
    For a 2×2 contingency table the odds ratio is:

    $$
    \text{OR} = \frac{o_{11}\,o_{22}}{o_{12}\,o_{21}}
              = \frac{f_{12}\,(n - f_1 - f_2 + f_{12})}
                     {(f_1 - f_{12})\,(f_2 - f_{12})}
    $$

    Swapping the two margins leaves this unchanged, so unlike `logratio` it does
    not care which of them is the corpus part. Values run from 0 to infinity
    with 1 at independence, which is an awkward scale to average or plot. Take
    the logarithm for one that is symmetric about 0.

    Odds and relative frequency are close for anything that is a small share of
    a corpus, so for most words the odds ratio comes out near
    $2^{\text{LR}}$. It rises above that for a word frequent enough that
    removing its own tokens changes the corpus it is measured against.

    Replacing a zero cell with `discount` is the usual 0.5 correction for an
    odds ratio with an empty cell.

    References
    ----------
    - Pojanapunya, P. and R. Watson Todd. 2018. Log-likelihood and odds ratio:
      Keyness statistics for different purposes of keyword analysis. *Corpus
      Linguistics and Linguistic Theory* 14(1): 133-167.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    o11 = _discounted(f12, discount)
    o12 = _discounted(f1 - f12, discount)
    o21 = _discounted(f2 - f12, discount)
    o22 = _discounted(n - f1 - f2 + f12, discount)
    return (o11 * o22) / (o12 * o21)

pctdiff

pctdiff(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr

Compute %DIFF for keyword contingency table data.

Gives the difference between a word's relative frequency in the target corpus and in the reference as a percentage of the reference figure: 100 means twice as common in the target, -50 means half as common. It ranks words exactly as logratio does, on a percentage scale rather than a logarithmic one.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

  • discount (float, default: 0.5 ) –

    Count to stand in for a frequency of zero, so that a word missing from one corpus gets a large percentage rather than an infinite one. Set it to 0 to leave the infinities in place.

Returns:

  • Expr –

    A Polars expression that computes %DIFF for each variable pair.

Notes

%DIFF is calculated as:

\[ \%\text{DIFF}(x,y) = 100\, \frac{f_{12} / f_2 - (f_1 - f_{12}) / (n - f_2)} {(f_1 - f_{12}) / (n - f_2)} \]

It reads the two margins as logratio does, and the two are the same ranking on different scales: \(\%\text{DIFF} = 100\,(2^{\text{LR}} - 1)\).

References
  • Gabrielatos, C. and A. Marchi. 2011. Keyness: Matching metrics to definitions. Paper given at Corpus Linguistics in the South 1, University of Portsmouth.
Source code in python/polars_corpus/assoc.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def pctdiff(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    discount: float = 0.5,
) -> pl.Expr:
    r"""
    Compute %DIFF for keyword contingency table data.

    Gives the difference between a word's relative frequency in the target
    corpus and in the reference as a percentage of the reference figure: 100
    means twice as common in the target, -50 means half as common. It ranks
    words exactly as `logratio` does, on a percentage scale rather than a
    logarithmic one.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.
    discount : float, default 0.5
        Count to stand in for a frequency of zero, so that a word missing from
        one corpus gets a large percentage rather than an infinite one. Set it
        to 0 to leave the infinities in place.

    Returns
    -------
    pl.Expr
        A Polars expression that computes %DIFF for each variable pair.

    Notes
    -----
    %DIFF is calculated as:

    $$
    \%\text{DIFF}(x,y) = 100\,
        \frac{f_{12} / f_2 - (f_1 - f_{12}) / (n - f_2)}
             {(f_1 - f_{12}) / (n - f_2)}
    $$

    It reads the two margins as `logratio` does, and the two are the same
    ranking on different scales:
    $\%\text{DIFF} = 100\,(2^{\text{LR}} - 1)$.

    References
    ----------
    - Gabrielatos, C. and A. Marchi. 2011. Keyness: Matching metrics to
      definitions. Paper given at *Corpus Linguistics in the South 1*,
      University of Portsmouth.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    target, reference = _rel_freqs(f12, f1, f2, n, discount)
    # The scaling trails the difference so the expression is named for `f12`
    # rather than for the leading literal; see `_discounted`.
    return (target - reference) / reference * 100

pmi

pmi(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute Pointwise Mutual Information (PMI) for contingency table data.

Calculates PMI values measuring the association strength between two categorical variables based on their observed vs. expected co-occurrence frequencies. PMI quantifies how much more (or less) frequently two events co-occur compared to what would be expected under statistical independence.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the PMI values for each variable pair.

Notes

PMI is calculated as:

\[ \text{PMI}(x,y) = \log\frac{P(x,y)}{P(x)\,P(y)} = \log\frac{n\,f_{12}}{f_1\,f_2} \]
References
  • Church, K. W. and P. Hanks. 1990. Word association norms, mutual information, and lexicography. Computational Linguistics 16(1): 22-29.
Source code in python/polars_corpus/assoc.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def pmi(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute Pointwise Mutual Information (PMI) for contingency table data.

    Calculates PMI values measuring the association strength between two
    categorical variables based on their observed vs. expected co-occurrence
    frequencies. PMI quantifies how much more (or less) frequently two events
    co-occur compared to what would be expected under statistical independence.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the PMI values for each variable pair.

    Notes
    -----
    PMI is calculated as:

    $$
    \\text{PMI}(x,y) = \\log\\frac{P(x,y)}{P(x)\\,P(y)}
                    = \\log\\frac{n\\,f_{12}}{f_1\\,f_2}
    $$

    References
    ----------
    - Church, K. W. and P. Hanks. 1990. Word association norms, mutual information, and
      lexicography. *Computational Linguistics* 16(1): 22-29.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    return ((f12 * n) / (f1 * f2)).log()

smp

smp(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    k: float,
) -> pl.Expr

Compute Kilgarriff's "simple maths" parameter for contingency table data.

Calculates the ratio of a word's frequency in the target corpus to its frequency in the reference corpus, with a smoothing constant k added to both frequencies to avoid division by zero and to reduce the effect of rare words.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

  • k (float) –

    Smoothing constant added to both the target and reference frequencies.

Returns:

  • Expr –

    A Polars expression that computes the simple maths values for each variable pair.

Notes

Simple maths is calculated as:

\[ \text{smp}(x,y) = \frac{f_{12} + k}{(f_1 - f_{12}) + k} \]

where \(f_1-f_{12}\) is the frequency of the word in the reference corpus.

References
  • Kilgarriff, A. 2009. Simple maths for keywords. In Proceedings of the Corpus Linguistics Conference. Liverpool, UK.
Source code in python/polars_corpus/assoc.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
def smp(
    f12: IntoExpr,
    f1: IntoExpr,
    f2: IntoExpr,
    n: IntoExpr,
    k: float,
) -> pl.Expr:
    """
    Compute Kilgarriff's "simple maths" parameter for contingency table data.

    Calculates the ratio of a word's frequency in the target corpus to its
    frequency in the reference corpus, with a smoothing constant `k` added to
    both frequencies to avoid division by zero and to reduce the effect of rare
    words.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.
    k : float
        Smoothing constant added to both the target and reference frequencies.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the simple maths values for each
        variable pair.

    Notes
    -----
    Simple maths is calculated as:

    $$
    \\text{smp}(x,y) = \\frac{f_{12} + k}{(f_1 - f_{12}) + k}
    $$

    where $f_1-f_{12}$ is the frequency of the word in the reference
    corpus.

    References
    ----------
    - Kilgarriff, A. 2009. Simple maths for keywords. In *Proceedings of
      the Corpus Linguistics Conference.* Liverpool, UK.
    """
    f12, f1, _, _ = _as_freqs(f12, f1, f2, n)
    return (f12 + k) / (f1 - f12 + k)

tscore

tscore(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute the t-score association measure for contingency table data.

Scales the gap between the observed joint frequency and the one expected under independence by the square root of the observed frequency. Dividing by the observed rather than the expected count holds rare pairs down, so the ranking favors frequent, dependable pairings -- the complement to what pmi reports.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the t-score values for each variable pair.

Notes

The t-score is calculated as:

\[ t(x,y) = \frac{f_{12} - e_{12}}{\sqrt{f_{12}}} \]

where \(e_{12} = f_1\,f_2 / n\) is the joint frequency expected under independence. It is not a t statistic in the distributional sense -- the normality it would need does not hold for word counts -- and is best read as a ranking, not a test.

References
  • Church, K. W., W. Gale, P. Hanks, and D. Hindle. 1991. Using statistics in lexical analysis. In U. Zernik (ed.), Lexical Acquisition: Exploiting On-Line Resources to Build a Lexicon, 115-164. Hillsdale: Erlbaum.
Source code in python/polars_corpus/assoc.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def tscore(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute the t-score association measure for contingency table data.

    Scales the gap between the observed joint frequency and the one expected
    under independence by the square root of the observed frequency. Dividing
    by the observed rather than the expected count holds rare pairs down, so
    the ranking favors frequent, dependable pairings -- the complement to what
    `pmi` reports.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the t-score values for each variable
        pair.

    Notes
    -----
    The t-score is calculated as:

    $$
    t(x,y) = \\frac{f_{12} - e_{12}}{\\sqrt{f_{12}}}
    $$

    where $e_{12} = f_1\\,f_2 / n$ is the joint frequency expected under
    independence. It is not a t statistic in the distributional sense -- the
    normality it would need does not hold for word counts -- and is best read
    as a ranking, not a test.

    References
    ----------
    - Church, K. W., W. Gale, P. Hanks, and D. Hindle. 1991. Using statistics
      in lexical analysis. In U. Zernik (ed.), *Lexical Acquisition: Exploiting
      On-Line Resources to Build a Lexicon*, 115-164. Hillsdale: Erlbaum.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    return (f12 - f1 * f2 / n) / f12.sqrt()

welchs_t

welchs_t(
    x1: IntoExprColumn,
    x2: IntoExprColumn,
    alt: str = "twosided",
) -> pl.Expr

Perform Welch's t-test for equality of two independent samples with unequal variances.

Welch's t-test is a variation of Student's t-test that does not assume equal population variances. It compares the means of two independent samples to determine if they are statistically different from each other.

Parameters:

  • x1 (IntoExprColumn) –

    First sample data. Can be a column name (str) or Polars expression. Nulls are left out of the sample rather than counted in its size.

  • x2 (IntoExprColumn) –

    Second sample data. Can be a column name (str) or Polars expression. Nulls are left out of the sample rather than counted in its size.

  • alt (('twosided', 'greater', 'less'), default: 'twosided' ) –

    Alternative hypothesis to test:

    • 'twosided' : the means are unequal (two-tailed test)
    • 'greater' : the mean of x1 is greater than the mean of x2 (one-tailed)
    • 'less' : the mean of x1 is less than the mean of x2 (one-tailed)

Returns:

  • Expr –

    A Polars expression that returns a struct with the following fields:

    • 't' : float The t-statistic of the test
    • 'p' : float The p-value of the test
    • 'df' : float The degrees of freedom used in the test
    • 'g' : float Hedges' g, a measure of effect size

    Returns null values for all fields if the test cannot be performed (e.g., insufficient data or zero variance in both samples).

Raises:

  • ValueError –

    If alt is not one of 'twosided', 'greater', or 'less'.

Notes

The test statistic is calculated as:

\[ t = \frac{\bar{x}_1 - \bar{x}_2} {\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}} \]

where \(\bar{x}_i\), \(s_i^2\), and \(n_i\) are the sample mean, sample variance, and sample size of the \(i\)-th sample.

The degrees of freedom are approximated using the Welch-Satterthwaite equation:

\[ df = \frac{\left(\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}\right)^2} {\frac{(s_1^2/n_1)^2}{n_1 - 1} + \frac{(s_2^2/n_2)^2}{n_2 - 1}} \]

The effect size is Hedges' g: Cohen's d recovered from the t-statistic, then scaled by the small-sample bias correction \(J\):

\[ d = t\,\sqrt{\frac{2\left(\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}\right)} {s_1^2 + s_2^2}} \qquad g = J\,d, \quad J = 1 - \frac{3}{4\,df - 1} \]
Source code in python/polars_corpus/assoc.py
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
def welchs_t(x1: IntoExprColumn, x2: IntoExprColumn, alt: str = "twosided") -> pl.Expr:
    """
    Perform Welch's t-test for equality of two independent samples with unequal variances.

    Welch's t-test is a variation of Student's t-test that does not assume equal
    population variances. It compares the means of two independent samples to
    determine if they are statistically different from each other.

    Parameters
    ----------
    x1 : IntoExprColumn
        First sample data. Can be a column name (str) or Polars expression.
        Nulls are left out of the sample rather than counted in its size.
    x2 : IntoExprColumn
        Second sample data. Can be a column name (str) or Polars expression.
        Nulls are left out of the sample rather than counted in its size.
    alt : {'twosided', 'greater', 'less'}, default 'twosided'
        Alternative hypothesis to test:

        - 'twosided' : the means are unequal (two-tailed test)
        - 'greater' : the mean of x1 is greater than the mean of x2 (one-tailed)
        - 'less' : the mean of x1 is less than the mean of x2 (one-tailed)

    Returns
    -------
    pl.Expr
        A Polars expression that returns a struct with the following fields:

        - 't' : float
            The t-statistic of the test
        - 'p' : float
            The p-value of the test
        - 'df' : float
            The degrees of freedom used in the test
        - 'g' : float
            Hedges' g, a measure of effect size

        Returns null values for all fields if the test cannot be performed
        (e.g., insufficient data or zero variance in both samples).

    Raises
    ------
    ValueError
        If `alt` is not one of 'twosided', 'greater', or 'less'.

    Notes
    -----
    The test statistic is calculated as:

    $$
    t = \\frac{\\bar{x}_1 - \\bar{x}_2}
             {\\sqrt{\\frac{s_1^2}{n_1} + \\frac{s_2^2}{n_2}}}
    $$

    where $\\bar{x}_i$, $s_i^2$, and $n_i$ are the sample mean, sample
    variance, and sample size of the $i$-th sample.

    The degrees of freedom are approximated using the Welch-Satterthwaite equation:

    $$
    df = \\frac{\\left(\\frac{s_1^2}{n_1} + \\frac{s_2^2}{n_2}\\right)^2}
              {\\frac{(s_1^2/n_1)^2}{n_1 - 1} + \\frac{(s_2^2/n_2)^2}{n_2 - 1}}
    $$

    The effect size is Hedges' g: Cohen's d recovered from the t-statistic, then
    scaled by the small-sample bias correction $J$:

    $$
    d = t\\,\\sqrt{\\frac{2\\left(\\frac{s_1^2}{n_1} + \\frac{s_2^2}{n_2}\\right)}
                      {s_1^2 + s_2^2}}
    \\qquad
    g = J\\,d, \\quad J = 1 - \\frac{3}{4\\,df - 1}
    $$
    """
    alt = check_choice(alt, ALTERNATIVES, param="alt")
    return register_plugin_function(
        plugin_path=LIB,
        args=[x1, x2],
        function_name="py_welchs_t",
        is_elementwise=False,
        returns_scalar=True,
        kwargs={"alt": alt},
    ).alias("t_test")

welchs_t_from_stats

welchs_t_from_stats(
    s1: IntoExprColumn,
    ss1: IntoExprColumn,
    n1: IntoExprColumn,
    s2: IntoExprColumn,
    ss2: IntoExprColumn,
    n2: IntoExprColumn,
    alt: str = "twosided",
) -> pl.Expr

Perform Welch's t-test using pre-computed summary statistics.

This function performs Welch's t-test for equality of two independent samples using pre-computed means, sums of squares, and sample sizes rather than raw data.

Parameters:

  • s1 (IntoExprColumn) –

    Sum (or mean × n) of the first sample. Can be a column name (str) or Polars expression.

  • ss1 (IntoExprColumn) –

    Sum of squares of the first sample. Can be a column name (str) or Polars expression.

  • n1 (IntoExprColumn) –

    Sample size of the first sample. Can be a column name (str) or Polars expression.

  • s2 (IntoExprColumn) –

    Sum (or mean × n) of the second sample. Can be a column name (str) or Polars expression.

  • ss2 (IntoExprColumn) –

    Sum of squares of the second sample. Can be a column name (str) or Polars expression.

  • n2 (IntoExprColumn) –

    Sample size of the second sample. Can be a column name (str) or Polars expression.

  • alt (('twosided', 'greater', 'less'), default: 'twosided' ) –

    Alternative hypothesis to test:

    • 'twosided' : the means are unequal (two-tailed test)
    • 'greater' : the mean of the first sample is greater than the second (one-tailed)
    • 'less' : the mean of the first sample is less than the second (one-tailed)

Returns:

  • Expr –

    A Polars expression that returns a struct with the following fields:

    • 't' : float The t-statistic of the test
    • 'p' : float The p-value of the test
    • 'df' : float The degrees of freedom used in the test
    • 'g' : float Hedges' g, the difference in means in standard deviations

    Returns null values for all fields if the test cannot be performed (e.g., insufficient data or zero variance in both samples).

Raises:

  • ValueError –

    If alt is not one of 'twosided', 'greater', or 'less'.

Notes

The sample means and variances are computed from the summary statistics as:

\[ \bar{x}_i = \frac{s_i}{n_i} \qquad \text{var}_i = \frac{ss_i - s_i^2 / n_i}{n_i - 1} \]

The test statistic, degrees of freedom, and effect size are then calculated using the same formulas as in welchs_t, with \(\text{var}_i\) in place of \(s_i^2\).

Source code in python/polars_corpus/assoc.py
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
def welchs_t_from_stats(
    s1: IntoExprColumn,
    ss1: IntoExprColumn,
    n1: IntoExprColumn,
    s2: IntoExprColumn,
    ss2: IntoExprColumn,
    n2: IntoExprColumn,
    alt: str = "twosided",
) -> pl.Expr:
    """
    Perform Welch's t-test using pre-computed summary statistics.

    This function performs Welch's t-test for equality of two independent samples
    using pre-computed means, sums of squares, and sample sizes rather than raw data.

    Parameters
    ----------
    s1 : IntoExprColumn
        Sum (or mean × n) of the first sample. Can be a column name (str) or
        Polars expression.
    ss1 : IntoExprColumn
        Sum of squares of the first sample. Can be a column name (str) or
        Polars expression.
    n1 : IntoExprColumn
        Sample size of the first sample. Can be a column name (str) or
        Polars expression.
    s2 : IntoExprColumn
        Sum (or mean × n) of the second sample. Can be a column name (str) or
        Polars expression.
    ss2 : IntoExprColumn
        Sum of squares of the second sample. Can be a column name (str) or
        Polars expression.
    n2 : IntoExprColumn
        Sample size of the second sample. Can be a column name (str) or
        Polars expression.
    alt : {'twosided', 'greater', 'less'}, default 'twosided'
        Alternative hypothesis to test:

        - 'twosided' : the means are unequal (two-tailed test)
        - 'greater' : the mean of the first sample is greater than the second (one-tailed)
        - 'less' : the mean of the first sample is less than the second (one-tailed)

    Returns
    -------
    pl.Expr
        A Polars expression that returns a struct with the following fields:

        - 't' : float
            The t-statistic of the test
        - 'p' : float
            The p-value of the test
        - 'df' : float
            The degrees of freedom used in the test
        - 'g' : float
            Hedges' g, the difference in means in standard deviations

        Returns null values for all fields if the test cannot be performed
        (e.g., insufficient data or zero variance in both samples).

    Raises
    ------
    ValueError
        If `alt` is not one of 'twosided', 'greater', or 'less'.

    Notes
    -----
    The sample means and variances are computed from the summary statistics as:

    $$
    \\bar{x}_i = \\frac{s_i}{n_i}
    \\qquad
    \\text{var}_i = \\frac{ss_i - s_i^2 / n_i}{n_i - 1}
    $$

    The test statistic, degrees of freedom, and effect size are then calculated
    using the same formulas as in `welchs_t`, with $\\text{var}_i$ in place of
    $s_i^2$.
    """
    alt = check_choice(alt, ALTERNATIVES, param="alt")
    return register_plugin_function(
        plugin_path=LIB,
        args=[s1, ss1, n1, s2, ss2, n2],
        function_name="py_welchs_t_from_stats",
        is_elementwise=True,
        returns_scalar=False,
        kwargs={"alt": alt},
    ).alias("t_test")

zscore

zscore(
    f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr
) -> pl.Expr

Compute the z-score association measure for contingency table data.

Scales the gap between the observed joint frequency and the one expected under independence by the square root of the expected frequency. Dividing by the expected count makes it more forgiving of rare pairs than tscore, and less so than pmi.

Parameters:

  • f12 (IntoExpr) –

    Joint frequencies of variable pairs. Can be a column name (str) or Polars expression.

  • f1 (IntoExpr) –

    Marginal frequencies of first variable. Can be a column name (str) or Polars expression.

  • f2 (IntoExpr) –

    Marginal frequencies of second variable. Can be a column name (str) or Polars expression.

  • n (IntoExpr) –

    Grand total (total number of observations). Can be a column name (str) or Polars expression.

Returns:

  • Expr –

    A Polars expression that computes the z-score values for each variable pair.

Notes

The z-score is calculated as:

\[ z(x,y) = \frac{f_{12} - e_{12}}{\sqrt{e_{12}}} \]

where \(e_{12} = f_1\,f_2 / n\) is the joint frequency expected under independence. This is the Poisson form, which takes the variance of the count to be its mean.

References
  • Berry-Rogghe, G. L. M. 1973. The computation of collocations and their relevance in lexical studies. In A. J. Aitken, R. W. Bailey, and N. Hamilton-Smith (eds.), The Computer and Literary Studies, 103-112. Edinburgh University Press.
Source code in python/polars_corpus/assoc.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def zscore(f12: IntoExpr, f1: IntoExpr, f2: IntoExpr, n: IntoExpr) -> pl.Expr:
    """
    Compute the z-score association measure for contingency table data.

    Scales the gap between the observed joint frequency and the one expected
    under independence by the square root of the expected frequency. Dividing
    by the expected count makes it more forgiving of rare pairs than `tscore`,
    and less so than `pmi`.

    Parameters
    ----------
    f12 : IntoExpr
        Joint frequencies of variable pairs. Can be a column name (str) or
        Polars expression.
    f1 : IntoExpr
        Marginal frequencies of first variable. Can be a column name (str) or
        Polars expression.
    f2 : IntoExpr
        Marginal frequencies of second variable. Can be a column name (str) or
        Polars expression.
    n : IntoExpr
        Grand total (total number of observations). Can be a column name (str) or
        Polars expression.

    Returns
    -------
    pl.Expr
        A Polars expression that computes the z-score values for each variable
        pair.

    Notes
    -----
    The z-score is calculated as:

    $$
    z(x,y) = \\frac{f_{12} - e_{12}}{\\sqrt{e_{12}}}
    $$

    where $e_{12} = f_1\\,f_2 / n$ is the joint frequency expected under
    independence. This is the Poisson form, which takes the variance of the
    count to be its mean.

    References
    ----------
    - Berry-Rogghe, G. L. M. 1973. The computation of collocations and their
      relevance in lexical studies. In A. J. Aitken, R. W. Bailey, and
      N. Hamilton-Smith (eds.), *The Computer and Literary Studies*, 103-112.
      Edinburgh University Press.
    """
    f12, f1, f2, n = _as_freqs(f12, f1, f2, n)
    expected = f1 * f2 / n
    return (f12 - expected) / expected.sqrt()