Repository navigation
Expand file tree
/
Copy pathtext.qmd
More file actions
1534 lines (1312 loc) · 70.7 KB
/
Copy pathtext.qmd
File metadata and controls
1534 lines (1312 loc) · 70.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
238
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
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
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
394
395
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
448
449
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
513
514
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
576
577
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
635
636
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
692
693
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
750
751
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
821
822
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
888
889
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
964
965
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
# Textual data {#sec-text}
::: {.content-hidden}
PLAN (Oct 2026)
Keep the book's probabilistic framing throughout: anomalous documents have high surprisal under a language model, or low density in a feature space; authorship verification is a one-class problem (is this text surprising given the author's known work?).
1. From text to numbers (brief)
- Tokens, document-term matrix, tf-idf, function vs content words, using tidytext (Silge & Robinson, Text Mining with R).
2. Bag-of-words anomalies
- Document features: length, type-token ratio, word and sentence length, punctuation, sentiment, readability, out-of-vocabulary share.
Then HDR / stray / LOF on the feature matrix (parallels the ch13 features strategy).
- Example: wine review descriptions.
Needs the original `description` column (dropped by fetch_wine_reviews()) restored in the weird package, giving one data set with numerical, categorical and text variables.
Natural target: reviews whose wording disagrees with their points.
3. Language-model surprisals
- Unigram / n-gram models give each document a surprisal; perplexity = exp(mean surprisal).
Show which words drive a document's score.
- Topic models (LDA) for unusual topic mixtures; document embeddings + PCA (link to ch9).
- Example: wine review descriptions (same data as section 2).
- Discussion: detectors of machine-generated text (DetectGPT, Binoculars) flag text that is too predictable, i.e. unusually LOW surprisal.
4. Was this text written by someone else?
- Authorship verification as one-class anomaly detection; function-word rates per chunk; Burrows' Delta mentioned as the stylometric standard (Manhattan distance on z-scores, ignores correlations).
- Example: The Royal Book of Oz (1921), credited to L Frank Baum but written by Ruth Plumly Thompson (Binongo, 2003, Chance); fetch_oz_books() (14 Baum, 15 Thompson).
- Model of Baum's style: Normal distribution fitted to Baum's chunks (clean subset, as in BACON); surprisals = Mahalanobis (ch6); leave-one-book-out surprisals as the reference sample; rank approximation; book surprisal = sum of chunk surprisals (as tokens in section 3).
- Where the differences hide: Thompson's chunks differ along Baum's smallest-variance principal components (hidden anomalies, ch3); outlier map shows residual-space anomalies (ch9); explains why Delta and a 2-D projection do less well.
Data for the weird package (book must not download from Gutenberg at build time; gutenbergr only in data-raw):
- `description` column restored in wine_reviews
- fetch_oz_books(): paragraphs of 29 Oz books (Baum 14, Thompson 15)
New book dependencies: tidytext.
:::
```{r}
#| label: setup11
#| include: false
#| cache: false
source("before-each-chapter.R")
```
Text is an extreme example of categorical data (@sec-categorical-data).
Each word comes from a vocabulary of many thousands of words, most of which are rarely used, and a document is a sequence of words whose meaning depends on their order.
A document is anomalous if it is improbable under a model of the language in which it is written, or if it has features that are very different from other documents in a given corpus.
The chapter starts by converting documents to numbers, and then finds anomalous documents from their features or from their surprisals under a language model.
Then it explores whether a document is surprising given other documents thought to be from the same author; this can help in identifying misattributed authorship.
The first two approaches are illustrated using the tasters' descriptions in the wine reviews data, so that the anomalous descriptions can be compared with the other variables recorded for each wine.
The authorship example uses the Oz books of L. Frank Baum and Ruth Plumly Thompson, including one published under Baum's name after his death.
A fuller introduction to analysing text in R is given by @Silge2017.
## From text to numbers {#sec-text-numbers}
Documents cannot be analysed using the methods of @sec-categorical-data, because each contains many words (categorical values), and almost every document is unique.
One relatively simple approach to analysing textual data is to convert each document to a vector of numbers by counting how often each word occurs in it, treating it as a **bag of words** and ignoring the order of the words.
While this loses much of the meaning of the text, it is enough to find many kinds of anomalous documents.
The examples in this section and the next use the tasters' descriptions of the `r scales::comma(NROW(wine_reviews))` wines in the wine reviews data (@sec-data).
They form a large collection of short documents, each describing a wine.
Here are three of them.
```{r}
#| label: fetch-wine-reviews-text
#| eval: false
#| code-fold: false
wine_reviews <- fetch_wine_reviews()
```
```{r}
#| label: wine-descriptions
#| code-fold: false
#| class-output: wrap
wine_reviews |>
slice_head(n = 3) |>
pull(description)
```
Our task is to find reviews that are substantially different from the other reviews in the data set.
### Tokens and vocabulary
A **token** is a unit of text, and splitting a document into tokens is called **tokenisation**.
Depending on the analysis, the tokens might be single characters, words, pairs of adjacent words, or whole sentences, but in this chapter every token is a single word.
The `unnest_tokens()` function from the **`tidytext`** package\ [@Silge2017] splits text into words by default.
It converts the text to lower case, removes the punctuation, and returns one row for each token, here in a column called `word`.
To keep track of which document each token came from, an `id` column, giving the row number of each review, is added to the data first.
```{r}
#| label: tidytext
#| code-fold: false
#| cache: false
library(tidytext)
```
```{r}
#| label: wine-words
#| code-fold: false
#| dependson: wine-descriptions
wine_reviews <- wine_reviews |>
mutate(id = row_number(), .before = 1)
wine_words <- wine_reviews |>
select(id, variety, description) |>
unnest_tokens(word, description, token = "words")
wine_words
vocabulary <- wine_words |>
count(word, sort = TRUE)
vocabulary
```
```{r}
#| label: wine-words-check
#| include: false
#| dependson: wine-words
top10_share <- sum(vocabulary$n[1:10]) / sum(vocabulary$n)
once_share <- mean(vocabulary$n == 1)
stop_share <- mean(wine_words$word %in% stop_words$word)
# The prose describes the size of the vocabulary and the most common words
stopifnot(
NROW(wine_words) > 4.5e6,
between(NROW(vocabulary), 32000, 33000),
round(100 * once_share) == 38,
round(100 * top10_share) == 27,
all(vocabulary$word[1:7] == c("and", "the", "a", "of", "with", "this", "is")),
vocabulary$word[8] == "wine",
NROW(stop_words) == 1149,
round(100 * stop_share) == 44
)
```
The `r scales::comma(NROW(wine_reviews))` descriptions contain `r sprintf("%.1f", NROW(wine_words) / 1e6)` million tokens, but only `r scales::comma(NROW(vocabulary))` distinct words, which together form the **vocabulary**.
A few words are used very often: the ten most common words account for `r sprintf("%.0f", 100 * top10_share)`% of the tokens.
At the other extreme, `r sprintf("%.0f", 100 * once_share)`% of the vocabulary occurs only once.
This follows the pattern found in almost every large collection of text, known as **Zipf's law**\ [@Zipf1949]: the frequency of a word is roughly inversely proportional to its rank in the list of word frequencies.
Each token is therefore an observation of a categorical variable whose categories are the words of the vocabulary: tens of thousands of categories, most of them rare.
The probability of each word can be estimated from its frequency, as in @sec-categorical, but for most words this estimate rests on only a handful of occurrences, and many possible words don't occur at all.
### Function words and content words
The most common words are "and", "the", "a", "of", "with", "this" and "is".
These are **function words**, which give a sentence its grammatical structure, as distinct from **content words**, such as "wine", "cherry" and "tannins", which carry its meaning.
Lists of function words and other very common words are called **stop words**.
The `stop_words` data in **`tidytext`** combine three overlapping lists, giving `r scales::comma(n_distinct(stop_words$word))` distinct words that account for `r sprintf("%.0f", 100 * stop_share)`% of the tokens in the descriptions.
Stop words are usually removed when the aim is to find what a document is about, but they are useful words for describing *how* it is written.
Patterns in how a writer uses these little words can help to identify the writer.
Removing them with `anti_join()` leaves the content words.
```{r}
#| label: wine-content-words
#| code-fold: false
#| dependson: wine-words
vocabulary |>
anti_join(stop_words, by = "word")
```
### The document-term matrix
The word counts of a collection of $n$ documents form an $n \times m$ **document-term matrix**, with one row for each document and one column for each of the $m$ words in the vocabulary.
The entry in row $i$ and column $w$ is $t_{iw}$, the number of times word $w$ occurs in document $i$.
The sums of each row and column, and the numbers of non-zero entries in each row and column, provide simple summaries of the documents and the words:
- $t_{i \cdot} = \sum_w t_{iw}$, the sum of row $i$, is the number of tokens in document $i$;
- $t_{\cdot w} = \sum_i t_{iw}$, the sum of column $w$, is the number of times word $w$ occurs in the whole collection, which is the frequency used to rank the vocabulary above;
- $m_i$, the number of non-zero entries in row $i$, is the number of distinct words in document $i$, so $m_i \le t_{i \cdot}$ and $m_i \le m$;
- $n_w$, the number of non-zero entries in column $w$, is the number of documents that contain word $w$, called its **document frequency**, so $n_w \le n$.
The total of all the entries, $\sum_i t_{i \cdot} = \sum_w t_{\cdot w}$, is the number of tokens in the collection.
The `cast_sparse()` function builds the matrix from the word counts.
```{r}
#| label: wine-dtm
#| code-fold: false
#| dependson: wine-words
dtm <- wine_words |>
count(id, word) |>
cast_sparse(id, word, n)
dim(dtm)
```
```{r}
#| label: wine-dtm-check
#| include: false
#| dependson: wine-dtm
dtm_density <- Matrix::nnzero(dtm) / prod(dim(dtm))
stopifnot(
NROW(dtm) == NROW(wine_reviews),
NCOL(dtm) == NROW(vocabulary),
round(100 * dtm_density, 1) == 0.1
)
```
Each description is now a point in a space with $m =$ `r scales::comma(NCOL(dtm))` dimensions, but only `r sprintf("%.1f", 100 * dtm_density)`% of the entries are non-zero, so the matrix is stored in a sparse form.
The methods of @sec-highdim could in principle be applied to its rows, but most of the columns are almost entirely zero, and the counts of common words such as "the" contribute far more to any distance between rows than those of rarer words.
So the counts are usually reweighted, or reduced to a few features.
### Term frequency--inverse document frequency
The **term frequency** of word $w$ in document $i$ is the proportion of the document's tokens that are that word, $\text{tf}_{iw} = t_{iw}/t_{i \cdot}$.
The **inverse document frequency** of word $w$ depends on its document frequency $n_w$:
$$
\text{idf}_w = \log(n / n_w),
$$
which is zero for a word that occurs in every document, and largest for a word that occurs in only one\ [@SparckJones1972].
The product $\text{tf}_{iw} \times \text{idf}_w$, called **tf-idf**, is large for words that are common in document $i$ but rare in the other documents, so it picks out the words that distinguish a document from the rest.
Replacing the counts in the document-term matrix by their tf-idf values gives rare words more weight than common ones, much as MCA gives rare categories more weight (@sec-correspondence).
@fig-wine-tfidf shows the words that are most characteristic of six grape varieties, found by treating all the descriptions of each variety as a single document and computing the tf-idf of each word with `bind_tf_idf()`, using all the varieties in the data as the collection of documents.
The words in the names of the varieties (such as "pinot" and "noir") are removed first, as they are trivially characteristic.
```{r}
#| label: fig-wine-tfidf
#| dependson: wine-words
#| fig-cap: >-
#| The six words with the largest tf-idf in the descriptions of each of six grape varieties, treating all the descriptions of each variety as a single document.
#| fig-height: 4.5
variety_words <- wine_reviews |>
distinct(variety) |>
unnest_tokens(word, variety)
variety_tfidf <- wine_words |>
filter(!is.na(variety)) |>
anti_join(variety_words, by = "word") |>
count(variety, word) |>
bind_tf_idf(word, variety, n)
varieties <- c(
"Chardonnay",
"Pinot Noir",
"Riesling",
"Sauvignon Blanc",
"Syrah",
"Zinfandel"
)
variety_tfidf |>
filter(variety %in% varieties) |>
slice_max(tf_idf, n = 6, by = variety, with_ties = FALSE) |>
ggplot(aes(x = tf_idf, y = reorder_within(word, tf_idf, variety))) +
geom_col() +
facet_wrap(vars(variety), scales = "free_y") +
scale_y_reordered() +
labs(x = "tf-idf", y = NULL)
```
```{r}
#| label: wine-tfidf-check
#| include: false
#| dependson: fig-wine-tfidf
top_tfidf <- variety_tfidf |>
filter(variety %in% varieties) |>
slice_max(tf_idf, n = 6, by = variety, with_ties = FALSE)
has <- function(v, w) all(w %in% top_tfidf$word[top_tfidf$variety == v])
sweetness <- wine_reviews |>
filter(variety %in% varieties) |>
summarise(
dry = mean(grepl("\\b(dry|sweet)\\b", description, ignore.case = TRUE)),
.by = variety
)
# The prose describes the words in fig-wine-tfidf
stopifnot(
has("Chardonnay", c("oak", "buttered", "pineapple", "toast")),
has("Pinot Noir", c("cola", "raspberry", "cranberry")),
has("Riesling", c("lime", "peach", "tangerine", "dry", "off")),
has("Sauvignon Blanc", c("gooseberry", "grapefruit", "sb")),
has("Syrah", c("pepper", "meat")),
has("Zinfandel", c("alcohol", "zin")),
sweetness$variety[which.max(sweetness$dry)] == "Riesling"
)
```
Most of the words are what a wine drinker would expect: the oak, buttered toast and pineapple of Chardonnay, the cola, raspberry and cranberry of Pinot Noir, the lime, peach and tangerine of Riesling, the gooseberry and grapefruit of Sauvignon Blanc, the pepper and meat of Syrah, and the alcohol of Zinfandel.
The words "dry" and "off" (as in "off-dry") appear for Riesling, whose reviews often say how sweet the wine is.
The tasters' abbreviations "zin" and "sb" survive the removal of the variety names.
## Bag-of-words anomalies {#sec-text-bow}
Although a bag of words ignores the order of the words, the word counts can still reveal anomalous documents in two ways.
First, each document can be summarised by a few interpretable features, such as its length or its tone, and the multivariate methods of earlier chapters applied to find documents with unusual features.
Second, the other variables recorded with each document can be modelled conditionally on its word counts, to find documents whose words disagree with those variables.
### Reviews with unusual features
The features used here measure the length of a document, its style, its vocabulary and its tone:
- `words`: the number of words;
- `word_length`: the mean number of characters in each word;
- `function_words`: the proportion of the words that are stop words;
- `idf`: the mean of the inverse document frequencies of the words, which is large when a document uses words that are rare in the collection;
- `sentiment`: the number of positive words minus the number of negative words, divided by the number of words, using the list of `r scales::comma(n_distinct(get_sentiments()$word))` positive and negative words compiled by @Hu2004;
- `punctuation`: the number of punctuation marks for each word.
Apart from `punctuation`, the features are computed from the word counts of a document: `words` is their total, and the others are averages over the words of the document, weighted by their counts.
All but `idf` depend only on the document itself; `idf` also depends on the whole collection, through the number of documents containing each word.
Each of the `r scales::comma(NROW(wine_reviews))` descriptions is treated as a document, and the six features are computed for each one.
Because the documents are now descriptions rather than varieties, $n_w$ in `idf` is the number of descriptions containing word $w$, not the number of varieties as in @fig-wine-tfidf.
```{r}
#| label: wine-text-features
#| code-fold: false
#| dependson: wine-words
idf <- wine_words |>
distinct(id, word) |>
count(word) |>
mutate(idf = log(NROW(wine_reviews) / n)) |>
select(word, idf)
text_features <- wine_words |>
left_join(idf, by = "word") |>
left_join(get_sentiments() |> filter(n() == 1, .by = word), by = "word") |>
summarise(
words = n(),
word_length = mean(nchar(word)),
function_words = mean(word %in% stop_words$word),
idf = mean(idf),
sentiment = (sum(sentiment == "positive", na.rm = TRUE) -
sum(sentiment == "negative", na.rm = TRUE)) /
n(),
.by = id
) |>
left_join(
wine_reviews |> select(id, points, description),
by = "id"
) |>
mutate(
punctuation = stringr::str_count(description, "[[:punct:]]") / words,
.after = sentiment
)
text_features
```
The reviews are relatively short, with a median of `r median(text_features$words)` words, so the features will be noisy, especially for the shortest reviews.
The number of words is replaced by its logarithm, the features are converted to robust multivariate $z$-scores with `mvscale()` (@sec-scaling), and a Gaussian mixture model (@sec-gmm-surprisal) is fitted to the scaled features.
Its surprisal probabilities are computed using the GPD approximation of @sec-approximate-surprisal-prob, as the mixture model is unlikely to fit the tails of the distribution well.
With more than 100,000 reviews, fitting the mixture takes several minutes.
```{r}
#| label: mclust-text
#| message: false
#| code-fold: false
#| cache: false
library(mclust)
```
```{r}
#| label: wine-text-gmm-display
#| eval: false
#| code-fold: false
Z <- text_features |>
mutate(words = log(words)) |>
select(words:punctuation) |>
mvscale() |>
as.matrix()
set.seed(1967)
text_gmm <- Mclust(Z, verbose = FALSE) |>
dist_mclust()
```
```{r}
#| label: wine-text-gmm-fit
#| include: false
#| dependson: wine-text-features
Z <- text_features |>
mutate(words = log(words)) |>
select(words:punctuation) |>
mvscale() |>
as.matrix()
set.seed(1967)
text_gmm <- Mclust(Z, verbose = FALSE) |>
dist_mclust() |>
cache("wine_text_gmm")
```
```{r}
#| label: wine-text-gmm
#| code-fold: false
#| dependson: wine-text-gmm-fit
text_features <- text_features |>
mutate(
s = surprisals(Z, distribution = text_gmm),
p = surprisals_prob(Z, distribution = text_gmm, approximation = "gpd"),
flagged = p < 0.001
)
text_features |>
arrange(p) |>
select(points, words:punctuation, p, flagged)
```
The texts of the twelve least probable reviews are shown below.
```{r}
#| label: wine-text-top
#| code-fold: false
#| dependson: wine-text-gmm
#| class-output: wrap
text_features |> slice_min(p, n = 12) |> pull(description)
```
```{r}
#| label: wine-text-check
#| include: false
#| dependson: wine-text-top
flagged_text <- text_features |> filter(flagged)
top_text <- text_features |> arrange(p) |> head(12)
non_review <- grepl("^Imported by|not available", text_features$description)
flagged_non_review <- grepl(
"^Imported by|not available",
flagged_text$description
)
short_reviews <- flagged_text |> filter(words <= 10, !flagged_non_review)
percentages <- grepl("%", flagged_text$description)
punct_q99 <- quantile(text_features$punctuation, 0.99)
high_punct <- flagged_text$punctuation > punct_q99
gaultier <- text_features |> filter(grepl("Gaultier", description))
# The prose describes the reviews with the smallest surprisal probabilities
stopifnot(
NROW(get_sentiments()) == 6786,
sum(non_review) == 7,
all(text_features$p[non_review] < 0.001),
sum(grepl("^Imported by|not available", top_text$description[1:7])) == 6,
all(top_text$words[1:7] <= 7),
grepl("^Smells raisiny", top_text$description[7]),
all(top_text$words <= 12),
NROW(short_reviews) >= 10,
median(short_reviews$points) < quantile(text_features$points, 0.05),
sum(high_punct) >= 20,
sum(high_punct & flagged_text$words > 10) >= sum(flagged_text$words > 10) / 3,
sum(percentages) >= 5,
sum(percentages & high_punct) > sum(percentages) / 2,
NROW(gaultier) == 1,
gaultier$p < 0.001,
between(NROW(flagged_text), 60, 110),
sum(flagged_text$words <= 10) >= 15,
all(flagged_text$words < 100),
sum(flagged_text$words > 10) >= 25
)
```
`r english::Words(NROW(flagged_text))` reviews have surprisal probabilities below 0.001.
Seven of the eight least probable are not reviews at all, but say only that the wine was "Imported by" a named company, or that the review is not available.
The other reviews printed above are very terse, such as "Smells raisiny, feels hot, tastes overripe.", and dismiss the wine in a few words.
The flagged reviews with ten words or fewer have a median of `r median(short_reviews$points)` points, lower than 95% of all reviews.
Many of the longer flagged reviews have much more punctuation than usual: `r english::words(sum(high_punct))` of the flagged reviews have more punctuation marks per word than 99% of all reviews, including most of those that list the percentages of the vineyards or grape varieties in a blend.
Another flagged review is mostly about the packaging rather than the wine: a red vinyl body suit designed for the bottle by the fashion designer Jean-Paul Gaultier.
```{r}
#| label: fig-wine-text-features
#| dependson: wine-text-gmm
#| fig-cap: >-
#| Number of words and mean inverse document frequency of the wine review descriptions.
#| The reviews with surprisal probabilities below 0.001, under a Gaussian mixture model of the six text features, are shown in orange.
#| fig-height: 3.5
text_features |>
ggplot(aes(x = words, y = idf)) +
geom_jitter(
data = filter(text_features, p >= 0.001),
width = 0.01,
height = 0,
alpha = 0.05,
size = 0.3
) +
geom_jitter(
data = filter(text_features, p < 0.001),
width = 0.01,
height = 0,
colour = "#D55E00",
size = 1
) +
scale_x_log10() +
labs(x = "Number of words (log scale)", y = "Mean idf")
```
@fig-wine-text-features shows two of the six features.
The descriptions that are not reviews are at the top left, with only a few words, most of them rare.
Many of the other flagged reviews are very short, and the rest are flagged because of their other features, or their combination of features.
### Reviews that disagree with their points
A review can also be anomalous because its text does not fit its other variables.
The points awarded to a wine, on a scale of 80 to 100, should agree with what the taster wrote about it, so a review whose points are surprising given its wording is a **conditional anomaly**, even if neither its points nor its wording is unusual on its own.
As in @sec-mixed, such anomalies are found from the conditional surprisal, $-\log f(\text{points} \mid \text{text})$, here estimated by a linear regression with Normal errors (@sec-regression-log-scores).
The six features above are not much use as predictors, as only the sentiment score measures whether a review is favourable, and it uses a general list of words that knows nothing about wine.
The predictors used instead are the counts of the most common words (those used in at least 500 reviews), along with the logarithm of the number of words.
Each coefficient is then the change in the expected points for each use of that word, holding the other predictors fixed.
The seven descriptions that are not reviews are removed first: an import statement, or a note that the review is not available, says nothing about the wine, so it can neither agree nor disagree with the points.
```{r}
#| label: wine-text-reviews
#| code-fold: false
#| dependson: wine-text-gmm
reviews <- text_features |>
filter(!grepl("^Imported by|not available", description))
```
The regression model has more than 100,000 observations and nearly 1,000 predictors.
To save memory, `model = FALSE` stops `lm()` from storing another copy of the design matrix in its model frame.
Even so, the fitted model is large because it contains the QR decomposition of the design matrix, which `surprisals_prob()` needs for the leverages.
So only the coefficients, fitted values and surprisal probabilities are kept, and the fitted model and the design matrix are removed.
```{r}
#| label: wine-text-points-display
#| eval: false
#| code-fold: false
X <- as.matrix(dtm[reviews$id, Matrix::colSums(dtm > 0) >= 500])
fit <- lm(points ~ log(words) + X, data = reviews, model = FALSE)
fit_words <- list(
coef = coef(fit),
fitted = fitted(fit),
p = surprisals_prob(fit, approximation = "gpd")
)
rm(fit, X)
```
```{r}
#| label: wine-text-points-fit
#| include: false
#| dependson: [wine-dtm, wine-text-reviews]
fit_words <- local({
X <- as.matrix(dtm[reviews$id, Matrix::colSums(dtm > 0) >= 500])
fit <- lm(points ~ log(words) + X, data = reviews, model = FALSE)
list(
coef = coef(fit),
fitted = fitted(fit),
p = surprisals_prob(fit, approximation = "gpd")
)
}) |>
cache("wine_text_points")
```
```{r}
#| label: wine-text-points
#| code-fold: false
#| dependson: wine-text-points-fit
reviews <- reviews |>
mutate(fitted = fit_words$fitted, p = fit_words$p, flagged = p < 0.001)
coefs <- sort(fit_words$coef[-(1:2)])
names(coefs) <- sub("^X", "", names(coefs))
head(coefs, 10)
tail(coefs, 10)
```
```{r}
#| label: wine-text-points-check
#| include: false
#| dependson: wine-text-points
r2_words <- cor(reviews$points, reviews$fitted)^2
top_pos <- reviews |> filter(points > fitted) |> slice_min(p, n = 6)
top_neg <- reviews |> filter(points < fitted) |> slice_min(p, n = 6)
tonnelles <- top_pos |> filter(grepl("barnyard", description))
top_great <- top_pos |> filter(points >= 96)
# The prose describes the coefficients and the largest residuals in each direction
stopifnot(
NROW(text_features) - NROW(reviews) == 7,
length(coefs) == 979,
round(r2_words, 2) == 0.65,
all(
c("lacks", "thin", "flat", "sugary", "short", "simple") %in%
names(head(coefs, 10))
),
all(
c("gorgeous", "beautiful", "wonderful", "opulent") %in%
names(tail(coefs, 10))
),
sum(grepl("^20[0-9][0-9]$", names(tail(coefs, 10)))) == 3,
between(sum(reviews$flagged), 90, 110),
sum(top_pos$points >= 96) == 5,
NROW(tonnelles) == 1,
tonnelles$points == 92,
round(tonnelles$fitted) == 83,
all(sapply(
c(
"powerhouse",
"flat-out dazzling",
"knockout",
"almost medicinal intensity",
"memorable",
"^95-97"
),
\(x) any(grepl(x, top_great$description))
)),
all(abs(top_great$fitted - mean(reviews$points)) < 2.5),
!any(
c("powerhouse", "dazzling", "knockout", "memorable", "95", "97") %in%
names(coefs)
),
all(top_neg$points <= 83),
all(sapply(
c(
"asphalt",
"Band-Aid",
"Roquefort",
"attention for very long",
"brown around",
"elegance"
),
\(x) any(grepl(x, top_neg$description))
)),
!any(c("barnyard", "asphalt", "band", "roquefort") %in% names(coefs)),
coefs["flat"] < -1,
coefs["medicinal"] < -0.5,
coefs["rustic"] < -0.5,
coefs["long"] > 0.5,
coefs["elegance"] > 0.5
)
```
The model explains `r sprintf("%.0f", 100 * r2_words)`% of the variation in the points.
Doubling the length of a review adds `r sprintf("%.1f", log(2) * fit_words$coef[2])` points to its expected score if the extra words are all rare ones, leaving the counts of the common words unchanged.
The words with the most negative coefficients name faults, such as "lacks", "thin", "flat" and "sugary", or damn with faint praise, such as "simple" and "short".
Those with the most positive coefficients are superlatives, such as "gorgeous", "beautiful" and "wonderful", and years, which occur in advice on when to drink a wine (e.g., "Drink 2023--2035"), given mainly for wines worth keeping.
`r english::Words(sum(reviews$flagged))` reviews have surprisal probabilities below 0.001, `r english::words(sum(reviews$flagged & reviews$points > reviews$fitted))` of them with more points than predicted.
The six least probable reviews in that direction are printed below.
```{r}
#| label: wine-text-points-top
#| code-fold: false
#| dependson: wine-text-points
#| class-output: wrap
reviews |>
filter(points > fitted) |>
slice_min(p, n = 6) |>
with(paste(points, "points.", description))
```
Five of these are wines with 96--98 points, but the model predicts only `r round(min(top_great$fitted))`--`r round(max(top_great$fitted))` points for them, close to the average of `r round(mean(reviews$points))` points for all reviews.
Their reviews praise them in words too rare to be among the predictors, such as "powerhouse", "dazzling", "knockout" and "memorable", while some of their common words count against them.
"Flat-out dazzling" contains "flat", whose coefficient is `r sprintf("%.2f", coefs["flat"])`, and "an almost medicinal intensity" contains "medicinal", whose coefficient is `r sprintf("%.2f", coefs["medicinal"])`.
A bag of words gives a word the same weight whatever words surround it.
One review starts with "95-97.\ Barrel sample.", the taster's range of scores for a wine tasted before it was bottled.
The text states the score, but "95" and "97" are not among the predictors, so the model has to predict the points from the other words, which suggest a score close to the average.
The exception is the third, with `r tonnelles$points` points, whose review is critical: "A rustic wine, with definite barnyard flavors … the tannins and old wood tastes intrude too much."
The model predicts `r round(tonnelles$fitted)` points, and nothing in the text suggests a wine worth 92.
Perhaps the points were recorded against the wrong review; either way, this is the kind of anomaly a conditional model is meant to find.
The six least probable reviews with fewer points than predicted are printed below.
```{r}
#| label: wine-text-points-bottom
#| code-fold: false
#| dependson: wine-text-points
#| class-output: wrap
reviews |>
filter(points < fitted) |>
slice_min(p, n = 6) |>
with(paste(points, "points.", description))
```
These are wines with 80--83 points, whose reviews describe the faults in vivid words that are too rare to be among the predictors, such as "asphalt", "Band-Aid" and "Roquefort".
Others use favourable words to unfavourable effect: a wine that "won't hold your attention for very long", and "fading elegance" in a wine that is "brown around the edges".
The coefficients of "long" and "elegance" are `r sprintf("%.2f", coefs["long"])` and `r sprintf("%.2f", coefs["elegance"])`.
The conditional model has found two kinds of anomaly.
A few reviews, such as the third one above, really do disagree with their points.
The others printed above are reviews that a bag of words cannot read: the words that carry their meaning are too rare to be among the predictors, or a common word means something different in context, as in "flat-out dazzling" and "fading elegance".
A model of the language itself can take some of that context into account.
## Language-model surprisals {#sec-text-lm}
Language models are the engines behind chatbots such as ChatGPT and Claude.
A language model estimates the probability distribution of the next token in a sequence, given all the tokens that have come before it.
A chatbot treats the user's prompt as the start of a sequence, samples the next token from this distribution, appends it to the sequence, and repeats, so that its reply is generated one token at a time.
To find anomalies, we can use the same distribution the other way round.
Instead of generating new text, we give the model text that already exists, and ask how probable each token is, given the tokens before it.
A document made up of improbable tokens has a high surprisal, and is a candidate anomaly.
Let $x_{i1}, \dots, x_{iL_i}$ denote the $L_i$ tokens of document $i$.
The probability of the whole document is the product of the probabilities of each token, given the tokens before it, so the surprisal of the document is the sum of the surprisals of its tokens:
$$
s_i = -\log f(x_{i1}, \dots, x_{iL_i}) = \sum_{j=1}^{L_i} s_{ij},
\qquad
\text{where}\qquad s_{ij} = -\log f(x_{ij} \mid x_{i1}, \dots, x_{i,j-1}).
$$
Each token surprisal $s_{ij}$ depends on all the tokens that come before it, which is how a language model takes context into account.
For example, "edges" is not a common word in wine reviews, but after "Looking brown around the" it is almost certain.
A document with more tokens has more to predict, so its surprisal tends to be larger.
To compare documents of different lengths, we can use the mean surprisal per token,
$$
\bar{s}_i = \frac{s_i}{L_i} = \frac{1}{L_i} \sum_{j=1}^{L_i} s_{ij}.
$$
Suppose the model gave every token in a document a probability of $1/k$, as if it were picking each one at random from $k$ equally likely tokens.
Then every token surprisal would be $\log k$, and so would the mean.
The **perplexity** of a document reverses this: it is the number of equally likely tokens the model would have to be choosing between to be as surprised by the document as it actually is.
It equals $e^{\bar{s}_i}$, so a mean surprisal of 3 nats per token corresponds to a perplexity of about 20.
The bag of words of @sec-text-numbers is the simplest language model, in which each token is independent of the others, so that $f(x_{ij} \mid x_{i1}, \dots, x_{i,j-1}) = f(x_{ij})$, and context is ignored altogether.
At the other extreme are **large language models**, which are neural networks trained to predict each token from all the tokens before it.
They are called "large" because of their size: they have billions of parameters, and are trained on trillions of tokens of text.
That size lets them use the meaning of the whole of the preceding text, so they predict the next token far better than any model based on counting words.
### Token surprisals from OLMo 2
The model used here is the smallest version of OLMo 2\ [@OLMo2025], with about a billion parameters.
Unlike most large language models, it has been published along with the data used to train it.
A model that had seen these reviews during training would find them unduly predictable, so it is useful to be able to check whether it did.
A search of the training data\ [@Liu2024] for passages from a sample of about 200 of the reviews found almost none of them.
The tokens of a large language model are not words.
The text is split into pieces from a fixed vocabulary of about 100,000 tokens, so that common words are single tokens (each including the space before it), while rarer words are split into several pieces.
Each review is preceded by the prompt "Wine review:" on a line of its own, so that the model knows what kind of text follows.
Without it, the first few tokens of each review are much more surprising, because the model has no way of knowing that it is reading a wine review.
The model is run from R using the **`reticulate`** package, which calls the Python packages **`torch`** and **`transformers`**.
The first time the code is run, `py_require()` installs these packages (and Python itself if necessary), and `from_pretrained()` downloads the model, which is about 6 GB.
The function `token_surprisals()` computes the surprisal of every token in a batch of reviews.
Passing a batch through the model at once is much faster than passing the reviews one at a time, as the computations for the whole batch are done together as operations on large arrays.
However, every review in a batch must have the same number of tokens, so shorter reviews are padded to the length of the longest, and the computation on the padding is wasted.
Sorting the reviews by length, and putting 16 reviews of similar length in each batch, keeps the padding to a minimum.
The batches are kept small to limit the memory needed, as at every position of every review the model returns a score for each of the 100,000 tokens in its vocabulary.
Even with batching, computing the surprisals for all the reviews takes several hours on a desktop computer, and longer still without a graphics processing unit (GPU).
```{r}
#| label: wine-olmo-display
#| eval: false
#| code-fold: true
library(reticulate)
py_require(c("torch", "transformers"))
torch <- import("torch")
transformers <- import("transformers")
model_name <- "allenai/OLMo-2-0425-1B"
tokenizer <- transformers$AutoTokenizer$from_pretrained(model_name)
olmo <- transformers$AutoModelForCausalLM$from_pretrained(model_name)
# Surprisal of each token in a batch of texts, given the prompt and the tokens before it
token_surprisals <- function(texts, prompt = "Wine review:\n") {
input <- tokenizer(texts, return_tensors = "pt", padding = TRUE)
# Start each text with the beginning-of-text token and the prompt
start <- c(tokenizer$bos_token_id, unlist(tokenizer$encode(prompt)))
m <- length(start)
start <- torch$tensor(list(as.list(start)))$expand(length(texts), -1L)
ids <- torch$cat(list(start, input$input_ids), dim = 1L)
mask <- torch$cat(
list(torch$ones_like(start), input$attention_mask),
dim = 1L
)
logits <- with(torch$no_grad(), olmo(ids, attention_mask = mask)$logits)
# Log probabilities of each token of the texts, from the position before it
n <- ids$size(1L) - m
log_probs <- torch$log_softmax(logits$narrow(1L, m - 1L, n), dim = -1L)
next_ids <- ids$narrow(1L, m, n)
surprisal <- -log_probs$gather(-1L, next_ids$unsqueeze(-1L))$squeeze(-1L)
# Transpose so that the tokens of each text are consecutive, dropping padding
keep <- t(mask$narrow(1L, m, n)$numpy() == 1)
tibble(
text = col(keep)[keep],
token_id = as.integer(t(next_ids$numpy())[keep]),
surprisal = t(surprisal$numpy())[keep]
)
}
# Batches of 16 reviews of similar length, to reduce padding
by_length <- wine_reviews$id[order(nchar(wine_reviews$description))]
batches <- split(by_length, ceiling(seq_along(by_length) / 16))
wine_tokens <- lapply(batches, \(b) {
token_surprisals(wine_reviews$description[b]) |>
mutate(id = b[text], .before = 1)
}) |>
bind_rows() |>
select(-text) |>
arrange(id)
# Replace the token numbers by the text of the tokens
vocab <- unique(wine_tokens$token_id)
pieces <- vapply(vocab, \(i) tokenizer$decode(list(i)), "")
wine_tokens <- wine_tokens |>
mutate(token = pieces[match(token_id, vocab)], .after = id) |>
select(-token_id)
```
```{r}
#| label: wine-olmo
#| include: false
#| dependson: wine-words
wine_tokens <- local({
library(reticulate)
py_require(c("torch", "transformers"))
torch <- import("torch")
transformers <- import("transformers")
model_name <- "allenai/OLMo-2-0425-1B"
tokenizer <- transformers$AutoTokenizer$from_pretrained(model_name)
olmo <- transformers$AutoModelForCausalLM$from_pretrained(model_name)
token_surprisals <- function(texts, prompt = "Wine review:\n") {
input <- tokenizer(texts, return_tensors = "pt", padding = TRUE)
start <- c(tokenizer$bos_token_id, unlist(tokenizer$encode(prompt)))
m <- length(start)
start <- torch$tensor(list(as.list(start)))$expand(length(texts), -1L)
ids <- torch$cat(list(start, input$input_ids), dim = 1L)
mask <- torch$cat(
list(torch$ones_like(start), input$attention_mask),
dim = 1L
)
logits <- with(torch$no_grad(), olmo(ids, attention_mask = mask)$logits)
n <- ids$size(1L) - m
log_probs <- torch$log_softmax(logits$narrow(1L, m - 1L, n), dim = -1L)
next_ids <- ids$narrow(1L, m, n)
surprisal <- -log_probs$gather(-1L, next_ids$unsqueeze(-1L))$squeeze(-1L)
keep <- t(mask$narrow(1L, m, n)$numpy() == 1)
tibble(
text = col(keep)[keep],
token_id = as.integer(t(next_ids$numpy())[keep]),
surprisal = t(surprisal$numpy())[keep]
)
}
by_length <- wine_reviews$id[order(nchar(wine_reviews$description))]
batches <- split(by_length, ceiling(seq_along(by_length) / 16))
wine_tokens <- lapply(batches, \(b) {
token_surprisals(wine_reviews$description[b]) |>
mutate(id = b[text], .before = 1)
}) |>
bind_rows() |>
select(-text) |>
arrange(id)
vocab <- unique(wine_tokens$token_id)
pieces <- vapply(vocab, \(i) tokenizer$decode(list(i)), "")
wine_tokens |>
mutate(token = pieces[match(token_id, vocab)], .after = id) |>
select(-token_id)
}) |>
cache("wine_olmo")
```
The result has one row for each token, giving its surprisal in nats (@sec-surprisals).
As tokens are discrete, a token with a surprisal of $s$ nats is given probability $e^{-s}$ by the model.
Here are the first 20 tokens of the first review.
```{r}
#| label: wine-olmo-tokens
#| code-fold: false
#| dependson: wine-olmo
wine_tokens |>
filter(id == 1) |>
print(n = 20)
```
```{r}
#| label: wine-olmo-tannins
#| include: false
#| dependson: wine-olmo
first_review <- wine_tokens |> filter(id == 1)
tannins <- first_review$surprisal[18:19]
# The prose describes the tokens of the first review
stopifnot(
NROW(wine_tokens) == 6258097,
n_distinct(wine_tokens$id) == NROW(wine_reviews),
all(trimws(first_review$token[16:19]) == c("Firm", "t", "ann", "ins")),
all(tannins < 0.06)
)
```
"Tannins" is split into three tokens, `" t"`, `"ann"` and `"ins"`.
Once the model has seen `" t"` after "Firm", the rest of the word is almost certain, and the surprisals of "ann" and "ins" are only `r sprintf("%.2f", tannins[1])` and `r sprintf("%.2f", tannins[2])` nats.
To score each review, its token surprisals are combined.
The code below computes the number of tokens, the mean surprisal and the perplexity of each review.
```{r}
#| label: wine-lm-reviews
#| code-fold: false
#| dependson: wine-olmo
lm_reviews <- wine_tokens |>
summarise(tokens = n(), s = mean(surprisal), .by = id) |>
mutate(perplexity = exp(s)) |>
left_join(wine_reviews |> select(id, points, description), by = "id")
lm_reviews |>
arrange(desc(s))
```
```{r}
#| label: wine-lm-check
#| include: false
#| dependson: [wine-lm-reviews, wine-text-gmm]
lm_most <- lm_reviews |> slice_max(s, n = 12)
lm_most_reviews <- lm_most |> filter(!grepl("^Imported by", description))
lm_least <- lm_reviews |> slice_min(s, n = 6)
repeated <- lm_least |> slice_max(tokens, n = 1)
repeated_tokens <- wine_tokens |> filter(id == repeated$id)
half <- nchar(repeated$description) / 2
half_tokens <- floor(NROW(repeated_tokens) / 2)
repeated_s <- c(
mean(head(repeated_tokens$surprisal, half_tokens)),
mean(tail(repeated_tokens$surprisal, half_tokens))
)
by_length <- lm_reviews |>
mutate(short = tokens <= 40) |>
summarise(m = mean(s), sd = sd(s), .by = short)
feature_flags <- text_features$flagged[match(
lm_most_reviews$id,
text_features$id
)]
least_flags <- text_features$flagged[match(lm_least$id, text_features$id)]
# The prose describes the most and least surprising reviews
stopifnot(
round(median(lm_reviews$s), 2) == 3.33,
all(grepl("^Imported by", lm_most$description[1:3])),
NROW(lm_most_reviews) == 9,
all(lm_most$tokens < median(lm_reviews$tokens)),
sum(feature_flags) == 2,
round(cor(lm_reviews$s, lm_reviews$points), 2) == -0.06,
by_length$m[by_length$short] > by_length$m[!by_length$short],
by_length$sd[by_length$short] > by_length$sd[!by_length$short],
sum(grepl("%", lm_least$description)) == 5,
!any(least_flags),
which(lm_least$id == repeated$id) == 4,
substr(repeated$description, 1, half) ==
substr(repeated$description, half + 1, 2 * half),
round(repeated_s, 2) == c(3.31, 0.08)
)
```
### Reviews with surprising wording
@fig-wine-lm-length shows the mean surprisal of each review against its number of tokens, with the corresponding perplexity on the right-hand axis.
```{r}
#| label: fig-wine-lm-length
#| dependson: wine-lm-reviews
#| fig-cap: >-
#| Number of tokens and mean surprisal per token (left axis) or perplexity (right axis) of the wine review descriptions, under OLMo 2.
#| fig-height: 3.5
lm_reviews |>
ggplot(aes(x = tokens, y = s)) +
geom_jitter(width = 0.01, height = 0, alpha = 0.1, size = 0.3) +
scale_x_log10() +
scale_y_continuous(
sec.axis = sec_axis(
transform = exp,
name = "Perplexity",
breaks = c(5, 10, 20, 50, 100, 200, 500)
)
) +
labs(
x = "Number of tokens (log scale)",
y = "Mean surprisal (nats per token)"
)
```
The mean surprisals of short reviews are higher and more variable than those of long reviews.
A short review has fewer tokens to average over, and less context with which to predict each of them.
The texts of the twelve most surprising reviews are shown below.
```{r}
#| label: wine-lm-most
#| code-fold: false
#| dependson: wine-lm-reviews
#| class-output: wrap
lm_reviews |> slice_max(s, n = 12) |> pull(description)
```
The three most surprising are import statements, which were also among the least probable descriptions in @sec-text-bow.
The other nine are genuine reviews, all of them shorter than the median review, and written in an unusual style: acids that "become jumpy", aromas that are "horsey", a wine that "convinces with simple purity" and another that feels "a bit clampy".
Only two of the nine were flagged by the text features in @sec-text-bow.
The mean surprisals are almost unrelated to the points: their correlation is `r sprintf("%.2f", cor(lm_reviews$s, lm_reviews$points))`.
So the language model finds reviews whose wording is unusual, not reviews that disagree with their points.
The six least surprising reviews are shown below.
```{r}