Skip to content

Keyword analysis

Examples: Keyword analysis

keywords

keywords(
    target: T_Frame,
    reference: T_Frame,
    expr: IntoExpr,
    method: str | Measure,
    min_target_freq: int = 0,
    min_target_range: int = 0,
    k: Optional[float] = None,
    file_id_column: str = "file_id",
) -> T_Frame

Identify keywords by comparing frequencies in a target corpus against a reference corpus.

Parameters:

  • target (DataFrame | LazyFrame) –

    Target corpus (DataFrame or LazyFrame) whose keywords are being extracted.

  • reference (DataFrame | LazyFrame) –

    Reference corpus (DataFrame or LazyFrame) that target is compared against.

  • expr (IntoExpr) –

    Column name or expression identifying the word/type to compute keyness for (e.g., token or lemma). Note that expr is evaluated against the combined target+reference corpora.

  • method (str | callable) –

    Association metric used to rank keywords:

    • 'bic' : Bayes factor BIC, log-likelihood penalized by corpus size
    • 'chisq' : Pearson's chi-squared (χ²)
    • 'll' : Log-likelihood ratio (G²)
    • 'logratio' : Hardie's log ratio, the effect size (column LogRatio)
    • 'mi3' : MI3, which pulls the ranking back towards frequent words
    • 'minsens' : Minimum sensitivity
    • 'oddsratio' : Odds ratio, the effect size (column OddsRatio)
    • 'pctdiff' : %DIFF, the effect size in percent (column %DIFF)
    • 'pmi' : Pointwise Mutual Information, which favors rare words
    • 'smp' : Kilgarriff's simple maths parameter (requires k)
    • 'tscore' : t-score, which favors frequent words
    • 'ttest' : Welch's t-test on per-file relative frequencies
    • 'zscore' : z-score

    'll', 'chisq' and 'bic' measure the evidence that a word's two frequencies differ, which grows with the size of the corpora. 'logratio', 'oddsratio' and 'pctdiff' measure how large that difference is, which does not. The literature expects one of each, because a large corpus makes a tiny difference significant.

    method can also be a Callable which takes the four counts f12, f1, f2 and n described under Returns. It receives them as Polars expressions and returns one expression.

  • min_target_freq (int, default: 0 ) –

    Minimum frequency in the target corpus required for a word to be included in the results.

  • min_target_range (int, default: 0 ) –

    Minimum range in the target corpus -- the number of distinct files a word must occur in -- required for it to be included in the results.

  • k (Optional[float], default: None ) –

    Constant added to both frequencies in Kilgarriff's "simple maths parameter"; larger values favor more frequent words. Required when method is 'smp' and unused otherwise.

  • file_id_column (str, default: "file_id" ) –

    Column holding file ids, used for range counts and for the per-file relative frequencies underlying 'ttest'.

Returns:

  • DataFrame | LazyFrame –

    Keywords ranked by association strength, most target-specific first. Eager if target is a DataFrame, lazy if it is a LazyFrame.

    Every method but 'ttest' returns the frequency table with one column named for the measure. 'ttest' returns the words more frequent in the target, ranked by p-value ascending, with the target-corpus counts the thresholds are applied to (target_freq, target_range) and the columns t, p, df, and g. The test statistic t and the p-value p indicate the strength of evidence for an association, while Hedges' g is the effect size. Note that df here is the test's degrees of freedom; a word's range is reported as target_range.

Raises:

  • ValueError –

    If target or reference is not a Polars DataFrame or LazyFrame, is empty, or is missing a column keywords needs; if expr is not a column name or expression; if method is not one of the measures listed above or a function; if a measure of your own returns something that is not an expression, or has no name to give its column; or if method is 'smp' and k is missing or not positive.

Notes

Rows with null values in either expr or file_id_column are dropped.

'bic' and 'chisq' are unsigned, so a word much rarer in the target corpus than in the reference ranks alongside one much commoner. Every other measure is signed, and puts the words the target overuses at the top.

'logratio', 'oddsratio' and 'pctdiff' have no value for a word absent from the reference corpus, and stand a count of 0.5 in for that zero. The ranking among such words then rests on that constant as much as on the data, which min_target_freq is the way to keep in hand.

References
  • Hofland, K. and Johansson, S. 1982. Word frequencies in British and American English. Norwegian Computing Centre for the Humanities. Bergen.
  • Leech, G. and R. Fallon. 1992. Computer corpora – What do they tell us about culture? ICAME Journal 16: 29–50.
  • Lijffijt, J., T. Nevalainen, T. Säily, P. Papapetrou, K. Puolamäki, and H. Mannila. 2016. Significance testing of word frequencies in corpora. Digital Scholarship in the Humanities 31(2): 374-397.
  • Scott, M. 1997. PC analysis of key words—and key key words. System 25(2): 233-245.

Examples:

>>> import polars_corpus as plc
>>> plc.keywords(target, reference, "lemma", "ll", min_target_range=5)
>>> plc.keywords(target, reference, "token", "ttest", file_id_column="text_id")
>>> # An effect size beside the significance measure, on the same words:
>>> keys = plc.keywords(target, reference, "lemma", "ll", min_target_freq=10)
>>> keys.with_columns(pl.col("freqs").corpus.logratio().alias("LogRatio"))
>>> # A measure of your own -- Hofland and Johansson's difference coefficient:
>>> def diff_coefficient(f12, f1, f2, n):
...     target_rf, reference_rf = f12 / f2, (f1 - f12) / (n - f2)
...     return (target_rf - reference_rf) / (target_rf + reference_rf)
>>> plc.keywords(target, reference, "lemma", diff_coefficient, min_target_freq=10)
Source code in python/polars_corpus/keywords.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
237
def keywords(
    target: T_Frame,
    reference: T_Frame,
    expr: IntoExpr,
    method: str | Measure,
    min_target_freq: int = 0,
    min_target_range: int = 0,
    k: Optional[float] = None,
    file_id_column: str = "file_id",
) -> T_Frame:
    """
    Identify keywords by comparing frequencies in a target corpus against a reference corpus.

    Parameters
    ----------
    target : DataFrame | LazyFrame
        Target corpus (DataFrame or LazyFrame) whose keywords are being extracted.
    reference : DataFrame | LazyFrame
        Reference corpus (DataFrame or LazyFrame) that `target` is compared against.
    expr : IntoExpr
        Column name or expression identifying the word/type to compute keyness
        for (e.g., token or lemma). Note that `expr` is evaluated against the
        combined target+reference corpora.
    method : str | callable
        [Association metric](assoc.md) used to rank keywords:

         - 'bic' : Bayes factor BIC, log-likelihood penalized by corpus size
         - 'chisq' : Pearson's chi-squared (χ²)
         - 'll' : Log-likelihood ratio (G²)
         - 'logratio' : Hardie's log ratio, the effect size (column `LogRatio`)
         - 'mi3' : MI3, which pulls the ranking back towards frequent words
         - 'minsens' : Minimum sensitivity
         - 'oddsratio' : Odds ratio, the effect size (column `OddsRatio`)
         - 'pctdiff' : %DIFF, the effect size in percent (column `%DIFF`)
         - 'pmi' : Pointwise Mutual Information, which favors rare words
         - 'smp' : Kilgarriff's simple maths parameter (requires `k`)
         - 'tscore' : t-score, which favors frequent words
         - 'ttest' : Welch's t-test on per-file relative frequencies
         - 'zscore' : z-score

         'll', 'chisq' and 'bic' measure the evidence that a word's two
         frequencies differ, which grows with the size of the corpora.
         'logratio', 'oddsratio' and 'pctdiff' measure how large that
         difference is, which does not. The literature expects one of each,
         because a large corpus makes a tiny difference significant.

         `method` can also be a `Callable` which takes the four counts `f12`, `f1`, `f2`
         and `n` described under `Returns`. It receives them as Polars expressions
         and returns one expression.
    min_target_freq : int, default 0
        Minimum frequency in the target corpus required for a word to be
        included in the results.
    min_target_range : int, default 0
        Minimum range in the target corpus -- the number of distinct files a
        word must occur in -- required for it to be included in the results.
    k: float, default None
        Constant added to both frequencies in Kilgarriff's "simple maths
        parameter"; larger values favor more frequent words. Required when
        `method` is 'smp' and unused otherwise.
    file_id_column : str, default "file_id"
        Column holding file ids, used for range counts and for the
        per-file relative frequencies underlying 'ttest'.

    Returns
    -------
    DataFrame | LazyFrame
        Keywords ranked by association strength, most target-specific first.
        Eager if `target` is a DataFrame, lazy if it is a LazyFrame.

        Every method but 'ttest' returns the frequency table with one column
        named for the measure. 'ttest' returns the words more frequent in the
        target, ranked by p-value ascending, with the target-corpus counts the
        thresholds are applied to (`target_freq`, `target_range`) and the columns
        `t`, `p`, `df`, and `g`. The test statistic `t` and the p-value `p`
        indicate the strength of evidence for an association, while Hedges' `g`
        is the effect size. Note that `df` here is the test's degrees of
        freedom; a word's range is reported as `target_range`.

    Raises
    ------
    ValueError
        If `target` or `reference` is not a Polars DataFrame or LazyFrame, is
        empty, or is missing a column `keywords` needs; if `expr` is not a
        column name or expression; if `method` is not one of the measures
        listed above or a function; if a measure of your own returns something
        that is not an expression, or has no name to give its column; or if
        `method` is 'smp' and `k` is missing or not positive.

    Notes
    -----
    Rows with null values in either `expr` or `file_id_column` are dropped.

    'bic' and 'chisq' are unsigned, so a word much rarer in the target corpus
    than in the reference ranks alongside one much commoner. Every other
    measure is signed, and puts the words the target overuses at the top.

    'logratio', 'oddsratio' and 'pctdiff' have no value for a word absent from
    the reference corpus, and stand a count of 0.5 in for that zero. The
    ranking among such words then rests on that constant as much as on the
    data, which `min_target_freq` is the way to keep in hand.

    References
    ----------
    - Hofland, K. and Johansson, S. 1982. *Word frequencies in British and
      American English.* Norwegian Computing Centre for the Humanities. Bergen.
    - Leech, G. and R. Fallon. 1992. Computer corpora – What do they tell us about
      culture? *ICAME Journal* 16: 29–50.
    - Lijffijt, J., T. Nevalainen, T. Säily, P. Papapetrou, K. Puolamäki, and
      H. Mannila. 2016. Significance testing of word frequencies in corpora. *Digital
      Scholarship in the Humanities* 31(2): 374-397.
    - Scott, M. 1997. PC analysis of key words—and key key words. *System* 25(2): 233-245.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.keywords(target, reference, "lemma", "ll", min_target_range=5)
    >>> plc.keywords(target, reference, "token", "ttest", file_id_column="text_id")
    >>> # An effect size beside the significance measure, on the same words:
    >>> keys = plc.keywords(target, reference, "lemma", "ll", min_target_freq=10)
    >>> keys.with_columns(pl.col("freqs").corpus.logratio().alias("LogRatio"))
    >>> # A measure of your own -- Hofland and Johansson's difference coefficient:
    >>> def diff_coefficient(f12, f1, f2, n):
    ...     target_rf, reference_rf = f12 / f2, (f1 - f12) / (n - f2)
    ...     return (target_rf - reference_rf) / (target_rf + reference_rf)
    >>> plc.keywords(target, reference, "lemma", diff_coefficient, min_target_freq=10)
    """
    method = check_measure(method, METHODS)
    keyword_expr = as_expr(expr)
    if method == "smp":
        if k is None:
            raise ValueError(
                "method 'smp' needs a value for k: pass k=100 for Kilgarriff's "
                "default, or a larger value to favor more frequent words"
            )
        if k <= 0:
            raise ValueError(f"k must be a positive number, got {k}")
    elif k is not None:
        warnings.warn(
            f"k={k} is only used when method='smp'; ignoring it", stacklevel=2
        )

    target_lf = as_corpus(target, "target corpus")
    reference_lf = as_corpus(reference, "reference corpus")

    selected = []
    for part, corpus in (("target", target_lf), ("reference", reference_lf)):
        check_columns(
            corpus, [file_id_column], f"{part} corpus", param="file_id_column"
        )
        check_expr(corpus, keyword_expr, f"{part} corpus")
        rows = corpus.select(keyword_expr, file_id_column).drop_nulls()
        selected.append(rows.with_columns(pl.lit(part).alias(PART_FIELD)))
    combined = pl.concat(selected)

    keyword_name = combined.collect_schema().names()[0]

    if method == "ttest":
        result = _keywords_ttest(
            combined, keyword_name, min_target_freq, min_target_range, file_id_column
        )
    else:
        freq_table = crosstab(combined, keyword_name, PART_FIELD)
        target_range = (
            combined.filter(pl.col(PART_FIELD) == "target")
            .group_by(keyword_name)
            .agg(pl.col(file_id_column).n_unique().alias("target_range"))
        )
        freq_table = freq_table.join(target_range, on=keyword_name, how="left")
        result = _keywords_assoc(
            freq_table, method, min_target_freq, min_target_range, k
        )

    return collect_like(result, target)

keyword_plot

keyword_plot(
    keyword_df: T_Frame,
    term_expr: IntoExpr,
    keyness_expr: IntoExpr,
    ax: Axes | None = None,
    top_k: int | None = 10,
    descending: bool = True,
    reverse: bool = False,
    padding: int = 6,
    **kwargs,
) -> Axes

Plot ranked keywords as a horizontal lollipop/stem chart.

Each row of keyword_df becomes a stem, positioned by keyness_expr and labeled with term_expr.

Parameters:

  • keyword_df (DataFrame | LazyFrame) –

    Keywords to plot, e.g. the output of keywords.

  • term_expr (IntoExpr) –

    Column name or expression giving the label for each stem (e.g. token or lemma).

  • keyness_expr (IntoExpr) –

    Column name or expression giving the keyness/association score each stem is positioned at.

  • ax (Axes, default: None ) –

    Axes to draw on. A new figure and axes are created if not given.

  • top_k (int | None, default: 10 ) –

    Number of rows to plot, taken from the start of keyword_df. Plots every row if top_k is None or non-positive.

  • descending (bool, default: True ) –

    Plot the first row of keyword_df at the top rather than the bottom.

  • reverse (bool, default: False ) –

    Mirror the chart, so the stems run leftwards from the axis and the labels sit to the left of their markers. Useful for putting two keyword plots back to back.

  • padding (int, default: 6 ) –

    Offset in points between a stem's tip and its label.

  • **kwargs –

    Passed through to Axes.stem.

Returns:

  • Axes –

    The matplotlib axes the plot was drawn on.

Raises:

  • ValueError –

    If keyword_df is not a Polars DataFrame or LazyFrame, is empty, or cannot evaluate term_expr or keyness_expr; or if either of those is not a column name or expression.

Examples:

>>> import polars_corpus as plc
>>> male_keywords = plc.keywords(male_corpus, reference, "token", "ll")
>>> plc.keyword_plot(male_keywords, "token", "LogLik", top_k=15)
Source code in python/polars_corpus/visualizations.py
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
288
289
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
340
341
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
def keyword_plot(
    keyword_df: T_Frame,
    term_expr: IntoExpr,
    keyness_expr: IntoExpr,
    ax: Axes | None = None,
    top_k: int | None = 10,
    descending: bool = True,
    reverse: bool = False,
    padding: int = 6,
    **kwargs,
) -> Axes:
    """
    Plot ranked keywords as a horizontal lollipop/stem chart.

    Each row of `keyword_df` becomes a stem, positioned by `keyness_expr` and
    labeled with `term_expr`.

    Parameters
    ----------
    keyword_df : DataFrame | LazyFrame
        Keywords to plot, e.g. the output of `keywords`.
    term_expr : IntoExpr
        Column name or expression giving the label for each stem
        (e.g. token or lemma).
    keyness_expr : IntoExpr
        Column name or expression giving the keyness/association score each
        stem is positioned at.
    ax : Axes, optional
        Axes to draw on. A new figure and axes are created if not given.
    top_k : int | None, default 10
        Number of rows to plot, taken from the start of `keyword_df`.
        Plots every row if `top_k` is `None` or non-positive.
    descending : bool, default True
        Plot the first row of `keyword_df` at the top rather than the bottom.
    reverse : bool, default False
        Mirror the chart, so the stems run leftwards from the axis and the
        labels sit to the left of their markers. Useful for putting two
        keyword plots back to back.
    padding : int, default 6
        Offset in points between a stem's tip and its label.
    **kwargs
        Passed through to `Axes.stem`.

    Returns
    -------
    Axes
        The matplotlib axes the plot was drawn on.

    Raises
    ------
    ValueError
        If `keyword_df` is not a Polars DataFrame or LazyFrame, is empty, or
        cannot evaluate `term_expr` or `keyness_expr`; or if either of those is
        not a column name or expression.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> male_keywords = plc.keywords(male_corpus, reference, "token", "ll")
    >>> plc.keyword_plot(male_keywords, "token", "LogLik", top_k=15)
    """
    term = as_expr(term_expr, param="term_expr")
    keyness = as_expr(keyness_expr, param="keyness_expr")
    lf = as_corpus(keyword_df, name="keyword_df")
    term_name = check_expr(lf, term, name="keyword_df", param="term_expr")
    keyness_name = check_expr(lf, keyness, name="keyword_df", param="keyness_expr")

    if top_k is not None and top_k > 0:
        lf = lf.head(top_k)

    # Select the two expressions rather than collecting the frame whole: a
    # computed term or score exists only once evaluated, and a keyword table
    # carries columns (frequency structs, document counts) the plot never reads.
    keywords = lf.select(term, keyness).collect()

    if keywords.height == 0:
        raise ValueError("the keyword_df is empty, so there is nothing to plot")

    if descending:
        indices = range(len(keywords), 0, -1)
    else:
        indices = range(len(keywords))

    if ax is None:
        _, ax = plt.subplots()

    ax.stem(
        indices,
        keywords[keyness_name],
        linefmt="-",
        markerfmt="o",
        basefmt="lightgray",
        orientation="horizontal",
        **kwargs,
    )

    # Label the markers from the values they were drawn from, horizontal stems
    # putting the score on x and the row on y. A label sits at the stem's tip,
    # which a reversed axis puts on the other side of the marker.
    for x, y, label in zip(keywords[keyness_name], indices, keywords[term_name]):
        leftwards = (x < 0) != reverse
        ax.annotate(
            label,
            xy=(x, y),
            xytext=(-padding if leftwards else padding, 0),
            textcoords="offset points",
            ha="right" if leftwards else "left",
            va="center_baseline",
        )

    if reverse:
        ax.invert_xaxis()

    ax.set_yticks([])
    for spine in ax.spines.values():
        spine.set_visible(False)

    return ax