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
targetis compared against. -
expr(IntoExpr) –Column name or expression identifying the word/type to compute keyness for (e.g., token or lemma). Note that
expris 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.
methodcan also be aCallablewhich takes the four countsf12,f1,f2andndescribed underReturns. 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
methodis '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
targetis 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 columnst,p,df, andg. The test statistictand the p-valuepindicate the strength of evidence for an association, while Hedges'gis the effect size. Note thatdfhere is the test's degrees of freedom; a word's range is reported astarget_range.
Raises:
-
ValueError–If
targetorreferenceis not a Polars DataFrame or LazyFrame, is empty, or is missing a columnkeywordsneeds; ifexpris not a column name or expression; ifmethodis 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 ifmethodis 'smp' andkis 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 | |
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 iftop_kisNoneor non-positive. -
descending(bool, default:True) –Plot the first row of
keyword_dfat 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_dfis not a Polars DataFrame or LazyFrame, is empty, or cannot evaluateterm_exprorkeyness_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 | |