Text is an extreme example of categorical data (Chapter 10). 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 its features have low density compared to those of other documents.
The chapter starts by converting documents to numbers, and then finds anomalous documents from their features or from their surprisals under a language model. Finally, it asks whether a text was written by the author to whom it is attributed. That is also a question of anomaly detection: is the text surprising, given the author’s known work?
11.1 From text to numbers
Documents cannot be analysed using the methods of Chapter 10, because each contains many words (categorical values), and almost every document is unique. Instead, a document can be converted to numbers by counting how often each word occurs in it, treating it as a “bag of words” and ignoring their order. This loses much of the meaning of the text, but it is enough to find many kinds of anomalous documents.
The examples in this section and the next use the descriptions of the wines written by the tasters in the wine reviews (Section 1.4). Here are three of them.
[1] "This is ripe and fruity, a wine that is smooth while still structured. Firm tannins are filled out with juicy red berry fruits and freshened with acidity. It's already drinkable, although it will certainly be better from 2016."
[2] "Tart and snappy, the flavors of lime flesh and rind dominate. Some green pineapple pokes through, with crisp acidity underscoring the flavors. The wine was all stainless-steel fermented."
[3] "Pineapple rind, lemon pith and orange blossom start off the aromas. The palate is a bit more opulent, with notes of honey-drizzled guava and mango giving way to a slightly astringent, semidry finish."
Tokens and vocabulary
A token is a unit of text, usually a word, and splitting a text into tokens is called tokenisation. The unnest_tokens() function from the tidytext package (Silge & Robinson, 2017) converts the text to lower case, removes the punctuation, and returns one row for each token.
# A tibble: 4,613,142 × 3
id variety word
<int> <chr> <chr>
1 1 Portuguese Red this
2 1 Portuguese Red is
3 1 Portuguese Red ripe
4 1 Portuguese Red and
5 1 Portuguese Red fruity
6 1 Portuguese Red a
7 1 Portuguese Red wine
8 1 Portuguese Red that
9 1 Portuguese Red is
10 1 Portuguese Red smooth
# ℹ 4,613,132 more rows
# A tibble: 32,362 × 2
word n
<chr> <int>
1 and 302906
2 the 190817
3 a 154674
4 of 149861
5 with 104093
6 this 98009
7 is 81926
8 wine 64994
9 flavors 55620
10 in 55172
# ℹ 32,352 more rows
The 111,592 descriptions contain 4.6 million tokens, but only 32,362 distinct words, which together form the vocabulary. A few words are used very often: the ten most common words account for 27% of the tokens. At the other extreme, 38% of the vocabulary occurs only once. This follows the pattern found in almost every large collection of text, known as Zipf’s law(Zipf, 1949): 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 Section 10.1, 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 such lists, giving 1,149 words, and these account for 44% of the tokens in the descriptions. Removing them with anti_join() leaves the content words.
vocabulary |>anti_join(stop_words, by ="word")
# A tibble: 31,697 × 2
word n
<chr> <int>
1 wine 64994
2 flavors 55620
3 fruit 42616
4 aromas 34292
5 palate 33484
6 finish 30979
7 acidity 28932
8 tannins 25882
9 drink 25687
10 cherry 25584
# ℹ 31,687 more rows
Stop words are usually removed when the aim is to find what a document is about, but they are the most useful words for describing how it is written, as how often a writer uses them reflects the writer’s habits rather than the subject.
The document-term matrix
The word counts of a collection of documents form a document-term matrix, with one row for each document and one column for each word in the vocabulary. The entry in row d and column w is n_{dw}, the number of times word w occurs in document d, so each row is a numerical vector, and its sum is the length of the document, n_d = \sum_w n_{dw}. The cast_sparse() function builds the matrix from the word counts.
dtm <- wine_words |>count(id, word) |>cast_sparse(id, word, n)dim(dtm)
[1] 111592 32362
Each description is now a point in a space with 32,362 dimensions, but only 0.1% of the entries are non-zero, so the matrix is stored in a sparse form. The methods of Chapter 9 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” dominate any distance between rows. 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 d is the proportion of the document’s tokens that are that word, \text{tf}_{dw} = n_{dw}/n_d. If N is the number of documents, and N_w is the number of documents that contain word w, the inverse document frequency of word w is
\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 (Spärck Jones, 1972). The product \text{tf}_{dw} \times \text{idf}_w, called tf-idf, is large for words that are common in document d 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 (Section 10.2).
Figure 11.1 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(). The words in the names of the varieties (such as “pinot” and “noir”) are removed first, as they are trivially characteristic.
Code
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)
Figure 11.1: 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.
Most of the words are what a wine drinker would expect: the oak, butter, pineapple and toast 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, and the tasters’ abbreviations “zin” and “sb” survive the removal of the variety names.
11.2 Feature-based anomalies in text
Anomalous documents can be found by describing each document by a few interpretable features, and then applying the multivariate methods of earlier chapters to the 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 letters 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 6,786 positive and negative words compiled by Hu & Liu (2004);
punctuation: the number of punctuation marks for each word.
For the wine data, each description is a document, so the idf of a word depends on how many of the 111,592 descriptions contain it, rather than how many varieties, as in Figure 11.1.
The features are scaled with mvscale() (Section 3.7), and a Gaussian mixture model (Section 7.7) is fitted to the scaled features. Its surprisal probabilities are computed using the GPD approximation of Section 7.3, 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.
[88 points] Imported by JL Giguiere.
[86 points] Imported by Maisons Marques & Domaines USA.
[86 points] Imported by Lion Nathan USA.
[88 points] Imported by Kobrand.
[81 points] Smells raisiny, feels hot, tastes overripe.
[81 points] Review text not available at this time.
[87 points] Imported by Bluewater Wine Company.
[89 points] This homage to Chablis blends fruit from Bentrock (49%), Rita's
Crown (22%), Zotovich (14%), Kessler-Haak (8%), Clos Pepe (3%), Esperanza
(3%) and Radian (1%) vineyards, delivering tight aromas of yellow flowers and
grilled peach. It dances across the tongue with playful, squeezed lemon
acidity, showing crushed white rocks and baking soda minerality, and
finishing its high tones on a grapefruit pith bitterness.
[91 points] Dark, dusty, strongly scented with barrel toast, coffee grounds and
incense, this is the most substantial and complete version to date. Balancing
cherry and plum fruit against the pretty barrel-infused tannins, it glides
gracefully across the palate into a seamless finish. Saggi is the Long
Shadows collaboration with Tuscany's Ambrogio and Giovanni Folonari. the
blend in 2007 is 43% Sangiovese, 36% Cabernet Sauvignon and 21% Syrah. With
each new vintage, the percentage of Sangiovese climbs, putting more Tuscany
in this new world super-Tuscan wine. Dark, dusty, strongly scented with
barrel toast, coffee grounds and incense, this is the most substantial and
complete version to date. Balancing cherry and plum fruit against the pretty
barrel-infused tannins, it glides gracefully across the palate into a
seamless finish.
[82 points] Light, pale, tart, with generic, simple red berry flavors.
[91 points] The extraordinary package, created by fashion designer Jean-Paul
Gaultier, is so over-the-top that it is truly worth owning in and of itself.
A hand-stitched, red vinyl body suit, tailored to the bottle’s seductive
curves, has been laced, from bottom to top, onto the bottle, like an elegant,
racy woman’s boot. Given that this is an election year, I should confess I
have sinned in my heart looking at this bottle. Oh, and how’s the wine? Big,
bold, fruity, assertive, toasty and otherwise in-your-face flavorful.
[84 points] A “layered” blend of five different varieties, this starts off a
bit floral and lemony, then develops some earthier notes to go along with the
modest citrus flavors. Finishes short. Sémillon (37%), Muscat (20.5%),
Gewürztraminer (19.5%), Pinot Gris (19%) and Chardonnay (4%).
Eighty-two reviews have surprisal probabilities below 0.001. The least probable are not reviews at all: seven descriptions say only that the wine was “Imported by” a named company, or that the review is not available. They are very short, use rare words (the names of the importers), and have no sentiment. The text is missing rather than anomalous, but the points and price may still be genuine. Other flagged reviews are very terse, such as “Smells raisiny, feels hot, tastes overripe.”, or list the percentages of the vineyards or grape varieties in a blend, which gives them much more punctuation than usual. One review contains its own text twice, presumably a data-entry error, so it is unusually long. One flagged review describes not the wine but its packaging: a red vinyl body suit designed for the bottle by the fashion designer Jean-Paul Gaultier.
Code
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")
Figure 11.2: 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.
Figure 11.2 shows two of the six features. The descriptions that are not reviews are at the top left, with only a few words, all of them rare. Many of the other flagged reviews are very short or very long, and the rest are flagged because of their other features, or their combination of features.
Wording that disagrees with the points
The points awarded to a wine should agree with what the taster wrote about it. As in Section 10.3, this can be checked with a conditional model: a regression of the points on the text features, whose large residuals are reviews with more or fewer points than their wording would suggest.
The texts of the six reviews with the largest positive residuals, and of the six with the largest negative residuals, are printed below.
text_features |>slice_max(r, n =6) |>print_reviews()
[88 points] Imported by JL Giguiere.
[88 points] Imported by Kobrand.
[86 points] Imported by Lion Nathan USA.
[87 points] Imported by Bluewater Wine Company.
[97 points] A majestic, magisterial wine, powered by superripe fruit as well as
honey and a gorgeous ripeness. With years ahead of it, this will be superb.
[97 points] This hugely rich yet approachable wine shows power and boldness.
All the elements are there, linked by firm tannins and freshness from berry
acidity.
text_features |>slice_min(r, n =6) |>print_reviews()
[80 points] Crisp and exceptionally low in tannin, the Chancellor grape is
perhaps this continent's answer to the Gamay of Beaujolais. The brilliant
garnet hue of this example will force you to pick up the glass. Unfotunately,
what you find there won't hold your attention for very long. The aromas are
pleasant but diffuse and lead to a one-dimensional palate with only a few
faint notes of red fruits.
[80 points] Charming aromas of tobacco leaf and strawberries promise good
things to come but the palate does not follow through. While some boysenberry
flavors appeal, the wine is thin in the mouth. The tannins are a bit overly
gripping now but the wine does not have the fruit ripeness or concentration
to benefit from cellaring.
[80 points] The only thing that makes this a gran reserva is the label and the
winery's commitment to a big, extracted, heavily oaked wine. It's black as
ink but clumsy as can be. Smells and tastes like shoe polish, resin and oily
fruit. Not what we're looking for from Argentina, or anywhere for that
matter. Barely acceptable. Imported by Carolina Wine Brands USA.
[82 points] The ripasso technique consists of passing the already completed
“normal” Valpolicella back over the lees of the Amarone in the spring after
vinification of the latter is complete. This results in a minor
refermentation, adding extra alcohol and flavor. If the latter occurred in
this particular version, it is not very evident. There is a modest amount of
dry fruit present, but the mouth-searing acids and mouth-drying tannins hurt
this wine.
[80 points] A strong wine, both in terms of aromas and flavors. There’s a
delicacy and lightness to the body, but the intensity of its flavors is
assaultive; it’s a combination of peaches, warm cheese and a hint of
something very dry and citrusy. Roquefort notes indicate that there may be
some bacteriological problems.
[80 points] This wine falls short of its rather lofty ambitions with lavish new
French oak treatment resulting in a diminished fruit profile. Sawdust notes
dominate the nose while the faintest hint of cherry can be detected on the
palate. Finishes a bit tart. A good choice for those hankering for a vanilla
milkshake.
The text features explain 38% of the variation in the points, mostly through the length of the review: tasters write more about the wines they like, and the correlation between the points and the number of words is 0.54. The largest positive residuals include four of the “Imported by” descriptions, whose wines have 86–88 points but only a few words, and two short reviews of wines with 97 points, each of which describes the wine in just two sentences, as “majestic” or “hugely rich”. The largest negative residuals are long reviews of wines with 80–82 points, which describe at length what is wrong with the wine. None of them has a negative sentiment score, because the list of positive and negative words takes each word on its own. In “Charming aromas of tobacco leaf and strawberries promise good things to come but the palate does not follow through”, the words “charming”, “promise” and “good” all count as positive; in “Sawdust notes dominate the nose”, so does “dominate”; and the misspelt “Unfotunately” is not in the list at all.
This shows the main weakness of features: they detect only the kinds of anomaly that the analyst has thought to measure, and features such as word counts ignore the order and context of the words. A model of the language itself can take some of that context into account.
Hu, M, & Liu, B. (2004). Mining and summarizing customer reviews. Proceedings of the Tenth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 168–177.
Silge, J, & Robinson, D. (2017). Text mining with R: A tidy approach. O’Reilly Media.
Spärck Jones, K. (1972). A statistical interpretation of term specificity and its application in retrieval. Journal of Documentation, 28(1), 11–21.
Zipf, GK. (1949). Human behavior and the principle of least effort. Addison-Wesley.