-
Notifications
You must be signed in to change notification settings - Fork 2
/
17-sentiment.Rmd
669 lines (547 loc) · 25.9 KB
/
17-sentiment.Rmd
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
# Sentiment Analysis
```{r include=FALSE}
library(tidyverse)
```
Create a topic model with `stm::stm()`. Parameter `K` specifies the number of topics. Here are models with 5 - 50 topics. This process can take a while, but the **furrr** package and `future_map()` function leverage parallel processing to make it quicker.
```{r, eval=FALSE}
heldout <- make.heldout(sawyer_dfm)
k_result <- sawyer_stm_mdls %>%
mutate(exclusivity = map(mdl, exclusivity),
semantic_coherence = map(mdl, semanticCoherence, sawyer_dfm),
eval_heldout = map(mdl, eval.heldout, heldout$missing),
residual = map(mdl, checkResiduals, sawyer_dfm),
bound = map_dbl(mdl, ~max(.$convergence$bound)),
lfact = map_dbl(mdl, ~lfactorial(.$settings$dim$K)),
lbound = bound + lfact,
iterations = map_dbl(mdl, ~length(.$convergence$bound)))
k_result %>%
transmute(K,
`Lower bound` = lbound,
Residuals = map_dbl(residual, "dispersion"),
`Semantic coherence` = map_dbl(semantic_coherence, mean),
`Held-out likelihood` = map_dbl(eval_heldout, "expected.heldout")) %>%
gather(Metric, Value, -K) %>%
ggplot(aes(K, Value, color = Metric)) +
geom_line(size = 1.5, alpha = 0.7, show.legend = FALSE) +
facet_wrap(~Metric, scales = "free_y") +
labs(x = "K (number of topics)",
y = NULL,
title = "Model diagnostics by number of topics",
subtitle = "These diagnostics indicate that a good number of topics would be around 60")
```
The held-out likelihood is highest between 30 and 50, and the residuals are lowest at 20, so 30 might be the right number. Semantic coherence is maximized when the most probable words in a given topic frequently co-occur together. Coherence tends to fall as exclusivity increases. You'll want the topic size that balances the trade-off.
```{r, eval=FALSE}
k_result %>%
select(K, exclusivity, semantic_coherence) %>%
filter(K %in% c(20, 25, 30)) %>%
unnest(cols = c(exclusivity, semantic_coherence)) %>%
mutate(K = as.factor(K)) %>%
ggplot(aes(semantic_coherence, exclusivity, color = K)) +
geom_point(size = 2, alpha = 0.7) +
labs(x = "Semantic coherence",
y = "Exclusivity",
title = "Comparing exclusivity and semantic coherence",
subtitle = "Models with fewer topics have higher semantic coherence for more topics, but lower exclusivity")
```
It looks like *k* = 30 may be optimal.
```{r, eval=FALSE}
sawyer_stm <- sawyer_stm_mdls %>%
filter(K == 30) %>%
pull(mdl) %>%
pluck(1)
```
Like `LDA()`, `stm()` returns two outputs: a "beta" matrix of probabilities of terms belonging to topics; a "gamma" matrix of probabilities of topics contributing to documents. The tidytext package provides a `tidy()` method for extracting these matrices.
```{r, eval=FALSE}
sawyer_stm_beta <- tidy(sawyer_stm, matrix = "beta")
sawyer_stm_gamma <- tidy(sawyer_stm, matrix = "gamma", document_names = rownames(sawyer_dfm))
```
I have 30 topics here, so it would be hard to show the top words per topic, but here are the first six topics.
```{r, eval=FALSE}
sawyer_stm_beta %>%
filter(topic <= 6) %>%
group_by(topic) %>%
slice_max(order_by = beta, n = 10, with_ties = FALSE) %>%
mutate(term = reorder_within(term, beta, topic)) %>%
ggplot(aes(x = term, y = beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
scale_fill_manual(values = RColorBrewer::brewer.pal(n = 6, name = "Set2"), name = "Topic") +
scale_x_reordered() +
coord_flip() +
facet_wrap(~ topic, scales = "free") +
labs(title = "STM Beta Matrix for first six topics",
subtitle = "Showing top 10 word probabilities")
```
Here is a Word cloud representation.
```{r results='hide', eval=FALSE}
colors6 <- RColorBrewer::brewer.pal(n = 6, name = "Set2")
x <- map(c(1:2), ~ with(sawyer_stm_beta %>% filter(topic == .x),
wordcloud::wordcloud(term, beta, max.words = 20,
colors = colors6[.x])))
```
And here are the most prevalent topics across chapters.
```{r, eval=FALSE}
top_terms <- sawyer_stm_beta %>%
group_by(topic) %>%
slice_max(order_by = beta, n = 7) %>%
summarise(.groups = "drop", terms = list(term)) %>%
mutate(terms = map(terms, paste, collapse = ", ")) %>%
unnest(terms)
sawyer_stm_gamma %>%
group_by(topic) %>%
summarize(.groups = "drop", gamma = mean(gamma)) %>%
left_join(top_terms, by = "topic") %>%
mutate(topic = paste("topic", topic),
topic = fct_reorder(topic, gamma)) %>%
slice_max(order_by = gamma, n = 10) %>%
ggplot(aes(x = topic, y = gamma, label = terms)) +
geom_col(fill = "#D8A7B1", show.legend = FALSE) +
geom_text(hjust = 0, nudge_y = 0.0005, size = 3) +
coord_flip() +
scale_y_continuous(expand = c(0,0),
limits = c(0, 0.09),
labels = scales::percent_format()) +
theme_minimal() +
theme(panel.grid = element_blank()) +
labs(x = NULL, y = expression(gamma),
title = "Top 10 STM topics by prevalence in The Adentures of Tom Sawyer",
subtitle = "With top words in each topic")
```
Another way to look at the betas is to identify terms that had the greatest difference in beta between the first and second most probable topic. A good way to do this is with their log ratio, $log_2(\beta_2 / \beta_1)$. Filter for relatively common words having a beta greater than 1/100 in at least one topic.
```{r, eval=FALSE}
sawyer_stm_beta %>%
mutate(topic = paste0("topic", topic)) %>%
group_by(term) %>%
slice_max(order_by = beta, n = 2) %>%
summarize(.groups = "drop", min_beta = min(beta)+.001, max_beta = max(beta)+.001) %>%
filter(max_beta > 0.01) %>%
mutate(log_ratio = log2(max_beta / min_beta)) %>%
top_n(n = 20, w = abs(log_ratio)) %>%
arrange(-log_ratio) %>%
ggplot(aes(x = fct_rev(fct_inorder(term)), y = log_ratio)) +
geom_col(fill = "#D8A7B1") +
theme_minimal() +
coord_flip() +
labs(title = "STM beta matrix log ratios",
subtitle = "showing greatest differences in beta values",
x = "", y = "log(beta ratio)")
```
A typical sentiment analysis involves unnesting tokens with `unnest_tokens()`, assigning sentiments with `inner_join(sentiments)`, counting tokens with `count()`, and summarizing and visualizing.
The tidytext package contains four sentiment lexicons, all based on unigrams.
* **nrc**. binary “yes”/“no” for categories positive, negative, anger, anticipation, disgust, fear, joy, sadness, surprise, and trust.
* **bing**. “positive”/“negative” classification.
* **AFINN**. score between -5 (most negative) and 5 (most positive).
* **loughran**. "positive"/"negative"/"litigious"/"uncertainty"/"constraining"/"superflous" classification.
You can view the sentiment assignments with `get_sentiments(lexicon = c("afinn", "bing", nrc", "laughlin"))`
```{r, eval=FALSE}
x1 <- get_sentiments(lexicon = "nrc") %>%
count(sentiment) %>%
mutate(lexicon = "nrc")
x2 <- get_sentiments(lexicon = "bing") %>%
count(sentiment) %>%
mutate(lexicon = "bing")
x3 <- get_sentiments(lexicon = "afinn") %>%
count(value) %>%
mutate(lexicon = "afinn") %>%
mutate(sentiment = as.character(value)) %>%
select(-value)
x4 <- get_sentiments(lexicon = "loughran") %>%
count(sentiment) %>%
mutate(lexicon = "loughran")
x <- bind_rows(x1, x2, x3, x4)
ggplot(x, aes(x = fct_reorder(sentiment, n), y = n, fill = lexicon)) +
geom_col(show.legend = FALSE) +
coord_flip() +
labs(title = "Sentiment Counts", x = "", y = "") +
facet_wrap(~ lexicon, scales = "free")
```
Here is a sentiment analysis of sections of 80 lines of Jane Austin's books. *(Small sections may not have enough words to get a good estimate of sentiment, and large sections can wash out the narrative structure. 80 lines seems about right.)*
```{r, eval=FALSE}
# austin_tidy %>%
# inner_join(get_sentiments("bing")) %>%
# count(book, index = linenumber %/% 80, sentiment) %>%
# pivot_wider(names_from = sentiment, values_from = n, values_fill = list(n = 0)) %>%
# mutate(sentiment = positive - negative) %>%
# ggplot(aes(x = index, y = sentiment, fill = book)) +
# geom_col(show.legend = FALSE) +
# facet_wrap(~book, ncol = 2, scales = "free_x")
```
Fair to say Jane Austin novels tend to have a happy ending? The three sentiment lexicons provide different views of THE data. Here is a comparison of the lexicons using one of Jane Austin's novels, "Pride and Prejudice".
```{r, eval=FALSE}
# # AFINN lexicon measures sentiment with a numeric score between -5 and 5.
# afinn <- austin_tidy %>%
# filter(book == "Pride & Prejudice") %>%
# inner_join(get_sentiments("afinn"), by = "word") %>%
# group_by(index = linenumber %/% 80) %>%
# summarise(sentiment = sum(value)) %>%
# mutate(method = "AFINN")
#
# # Bing and nrc categorize words in a binary fashion, either positive or negative.
# bing <- austin_tidy %>%
# filter(book == "Pride & Prejudice") %>%
# inner_join(get_sentiments("bing"), by = "word") %>%
# count(index = linenumber %/% 80, sentiment) %>%
# pivot_wider(names_from = sentiment, values_from = n, values_fill = list(n = 0)) %>%
# mutate(sentiment = positive - negative) %>%
# mutate(method = "Bing") %>%
# select(index, sentiment, method)
#
# nrc <- austin_tidy %>%
# filter(book == "Pride & Prejudice") %>%
# inner_join(get_sentiments("nrc") %>% filter(sentiment %in% c("positive", "negative")), by = "word") %>%
# count(index = linenumber %/% 80, sentiment) %>%
# pivot_wider(names_from = sentiment, values_from = n, values_fill = list(n = 0)) %>%
# mutate(sentiment = positive - negative) %>%
# mutate(method = "NRC") %>%
# select(index, sentiment, method)
#
# bind_rows(afinn, bing, nrc) %>%
# ggplot(aes(index, sentiment, fill = method)) +
# geom_col(show.legend = FALSE) +
# facet_wrap(~method, ncol = 1, scales = "free_y")
```
In this example, and in general, **NRC** sentiment tends to be high, **AFINN** sentiment has more variance, and **Bing** sentiment finds longer stretches of similar text. However, all three agree roughly on the overall trends in the sentiment through a narrative arc.
What are the top-10 positive and negative words? Using the Bing lexicon, get the counts, then `group_by(sentiment)` and `top_n()` to the top 10 in each category.
```{r, eval=FALSE}
# austin_tidy %>%
# filter(book == "Pride & Prejudice") %>%
# inner_join(get_sentiments("bing"), by = "word") %>%
# count(word, sentiment, sort = TRUE) %>%
# group_by(sentiment) %>%
# top_n(n = 10, wt = n) %>%
# ggplot(aes(x = fct_reorder(word, n), y = n, fill = sentiment)) +
# geom_col(show.legend = FALSE) +
# facet_wrap(~sentiment, scales = "free_y") +
# coord_flip() +
# labs(y = "Contribution to Sentiment",
# x = "")
```
Uh oh, "miss" is a red-herring - in Jane Austin novels it often refers to an unmarried woman. Drop it from the analysis by appending it to the stop-words list.
```{r}
# austin_tidy %>%
# anti_join(bind_rows(stop_words,
# tibble(word = c("miss"), lexicon = c("custom")))) %>%
# filter(book == "Pride & Prejudice") %>%
# inner_join(get_sentiments("bing")) %>%
# count(word, sentiment, sort = TRUE) %>%
# group_by(sentiment) %>%
# top_n(n = 10, wt = n) %>%
# ggplot(aes(x = fct_reorder(word, n), y = n, fill = sentiment)) +
# geom_col(show.legend = FALSE) +
# facet_wrap(~sentiment, scales = "free_y") +
# coord_flip() +
# labs(y = "Contribution to Sentiment",
# x = "")
```
Better!
A common way to visualize sentiments is with a word cloud.
```{r}
# austin_tidy %>%
# anti_join(bind_rows(stop_words,
# tibble(word = c("miss"), lexicon = c("custom")))) %>%
# filter(book == "Pride & Prejudice") %>%
# count(word) %>%
# with(wordcloud(word, n, max.words = 100))
```
`comparison.cloud` is another implementation of a word cloud. It takes a matrix input.
```{r}
# x <- austin_tidy %>%
# anti_join(bind_rows(stop_words,
# tibble(word = c("miss"), lexicon = c("custom")))) %>%
# inner_join(get_sentiments("bing")) %>%
# filter(book == "Pride & Prejudice") %>%
# count(word, sentiment, sort = TRUE) %>%
# pivot_wider(names_from = sentiment, values_from = n, values_fill = list(n = 0)) %>%
# as.data.frame()
# rownames(x) <- x[,1]
# comparison.cloud(x[, 2:3])
# rm(x)
```
Sometimes it makes more sense to analyze entire sentences. Specify `unnest_tokens(..., token = "sentences")` to override the default `token = "word"`.
```{r}
# austen_books() %>%
# group_by(book) %>%
# mutate(linenumber = row_number(),
# chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
# ignore_case = TRUE)))) %>%
# ungroup() %>%
# unnest_tokens(output = word, input = text, token = "sentences")
```
### N-Grams
Create n-grams by specifying `unnest_tokens(..., token = "ngrams", n)` where `n = 2` is a bigram, etc. To remove the stop words, `separate` the n-grams, then filter on the `stop_words` data set.
```{r}
# austin.2gram <- austen_books() %>%
# group_by(book) %>%
# mutate(linenumber = row_number(),
# chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
# ignore_case = TRUE)))) %>%
# ungroup() %>%
# unnest_tokens(output = bigram, input = text, token = "ngrams", n = 2)
#
# austin.2gram <- austin.2gram %>%
# separate(bigram, c("word1", "word2"), sep = " ") %>%
# filter(!word1 %in% stop_words$word &
# !word2 %in% stop_words$word &
# !is.na(word1) & !is.na(word2)) %>%
# unite(bigram, word1, word2, sep = " ")
#
# austin.2gram %>%
# count(book, bigram, sort = TRUE)
```
Here are the most commonly mentioned streets in Austin's novels.
```{r}
# austin.2gram %>%
# separate(bigram, c("word1", "word2"), sep = " ") %>%
# filter(word2 == "street") %>%
# count(book, word1, sort = TRUE)
```
Use the TF-IDF statistic to compare words among documents. Calculate the cosine similarity, the angle in multidimensional space between two vectors ($cos(\theta) = (A \cdot B) / ||A||||B||)$), to determine how similar two items are. Use `widyr::pairwise_similarity()` to calculate the cosine similarity of all pairs of items in a tidy table.
```{r}
# austen %>%
# unnest_tokens(output = "word", input = "text", token = "words") %>%
# anti_join(stop_words, by = "word") %>%
# count(book, word) %>%
# bind_tf_idf(term = word, document = book, n = n) %>%
# pairwise_similarity(item = book, feature = word, value = tf_idf) %>%
# arrange(desc(similarity))
```
```{r}
# austen_books() %>%
# group_by(book) %>%
# mutate(linenumber = row_number(),
# chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
# ignore_case = TRUE)))) %>%
# ungroup() %>%
# unnest_tokens(output = bigram, input = text, token = "ngrams", n = 2) %>%
# separate(bigram, c("word1", "word2"), sep = " ") %>%
# filter(!word1 %in% stop_words$word &
# !word2 %in% stop_words$word &
# !is.na(word1) & !is.na(word2)) %>%
# unite(bigram, word1, word2, sep = " ")
# austin.2gram %>%
# count(book, bigram) %>%
# bind_tf_idf(bigram, book, n) %>%
# group_by(book) %>%
# top_n(n = 10, wt = tf_idf) %>%
# ggplot(aes(x = fct_reorder(bigram, n), y = tf_idf, fill = book)) +
# geom_col(show.legend = FALSE) +
# facet_wrap(~book, scales = "free_y", ncol = 2) +
# labs(y = "tf-idf of bigram to novel") +
# coord_flip()
```
A good way to visualize bigrams is with a network graph. Packages `igraph` and `ggraph` provides tools for this purpose.
```{r}
# set.seed(2016)
#
# austen_books() %>%
# group_by(book) %>%
# mutate(linenumber = row_number(),
# chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
# ignore_case = TRUE)))) %>%
# ungroup() %>%
# unnest_tokens(output = bigram, input = text, token = "ngrams", n = 2) %>%
# separate(bigram, c("word1", "word2"), sep = " ") %>%
# filter(!word1 %in% stop_words$word &
# !word2 %in% stop_words$word &
# !is.na(word1) & !is.na(word2)) %>%
# count(word1, word2) %>%
# filter(n > 20) %>%
# graph_from_data_frame() %>% # creates unformatted "graph"
# ggraph(layout = "fr") +
# geom_edge_link(aes(edge_alpha = n),
# show.legend = FALSE,
# arrow = grid::arrow(type = "closed",
# length = unit(.15, "inches")),
# end_cap = circle(.07, 'inches')) +
# geom_node_point(color = "lightblue",
# size = 5) +
# geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
# theme_void()
```
If you want to count the number of times that two words appear within the same document, or to see how correlated they are, widen the data with the `widyr` package.
```{r}
# austen_books() %>%
# filter(book == "Pride & Prejudice") %>%
# mutate(section = row_number() %/% 10) %>%
# filter(section > 0) %>%
# unnest_tokens(word, text) %>%
# filter(!word %in% stop_words$word) %>%
# pairwise_count(word, section, sort = TRUE)
```
The correlation among words is how often they appear together relative to how often they appear separately. The phi coefficient is defined
$$\phi = \frac{n_{11}n_{00} - n_{10}n_{01}}{\sqrt{n_{1.}n_{0.}n_{.1}n_{.0}}}$$
where $n_{10}$ means number of times section has word x, but not word y, and $n_{1.}$ means total times section has word x. This lets us pick particular interesting words and find the other words most associated with them.
```{r}
# austen_books() %>%
# filter(book == "Pride & Prejudice") %>%
# mutate(section = row_number() %/% 10) %>%
# filter(section > 0) %>%
# unnest_tokens(word, text) %>%
# filter(!word %in% stop_words$word) %>%
# pairwise_cor(word, section, sort = TRUE) %>%
# filter(item1 %in% c("elizabeth", "pounds", "married", "pride")) %>%
# group_by(item1) %>%
# top_n(n = 4) %>%
# ungroup() %>%
# mutate(item2 = reorder(item2, correlation)) %>%
# ggplot(aes(x = item2, y = correlation)) +
# geom_bar(stat = "identity") +
# facet_wrap(~ item1, scales = "free") +
# coord_flip()
```
You can use the correlation to set a threshold for a graph.
```{r eval=FALSE, include=FALSE}
set.seed(2016)
austen_books() %>%
filter(book == "Pride & Prejudice") %>%
mutate(section = row_number() %/% 10) %>%
filter(section > 0) %>%
unnest_tokens(word, text) %>%
filter(!word %in% stop_words$word) %>%
# filter to relatively common words
group_by(word) %>%
filter(n() > 20) %>%
pairwise_cor(word, section, sort = TRUE) %>%
filter(correlation > .15) %>% # relatively correlated words
graph_from_data_frame() %>%
ggraph(layout = "fr") +
geom_edge_link(aes(edge_alpha = correlation), show.legend = FALSE) +
geom_node_point(color = "lightblue", size = 5) +
geom_node_text(aes(label = name), repel = TRUE) +
theme_void()
```
## Text Classification Modeling
The `tweets` data set contains politically charged tweets. Can you train a model to predict the `account_type` (Left or Right) from the tweet text?
Prepare the data by filtering to just the relevant tweets, tokenizing, and creatiing a document-term matrix with TFIDF weighting. If resources are an issue, experiment with values of parameter `sparse` in `dt::removeSparseTerms()` to get less terms. Below, `sparse = 0.9999` finally gets a respectable term count 14% the size of the orginal count.
```{r eval=FALSE, include=FALSE}
tweets_words <- tweets[1:500, ] %>%
unnest_tokens(output = "word", input = content, token = "words") %>%
anti_join(stop_words, by = "word") %>%
mutate(word = SnowballC::wordStem(word))
tweets_dtm <- tweets_words %>%
count(tweet_id, word) %>%
cast_dtm(document = tweet_id, term = word, value = n, weighting = tm::weightTfIdf) %>%
tm::removeSparseTerms(sparse = 0.999)
print(tweets_dtm)
```
Split the data into an 80:20 train:test split and fit a random forest model.
```{r eval=FALSE, include=FALSE}
set.seed(1012)
train_ind <- sample(nrow(tweets_dtm), floor(0.75*nrow(tweets_dtm)))
tweets_train <- tweets_dtm[train_ind, ]
tweets_test <- tweets_dtm[-train_ind, ]
rfc <- randomForest::randomForest(x = as.data.frame(as.matrix(tweets_train)),
y = as.numeric(tweets_train$dimnames$Docs),
nTree = 50)
rfc
plot(caret::varImp(rfc), main="Variable Importance with Random Forest")
```
## Named Entity Recognition
The **qdap** package provides parsing tools for preparing transcript data.
```{r warning=FALSE, message=FALSE, eval=FALSE}
library(qdap)
```
For example, `freq_terms()` parses text and counts the terms.
```{r eval=FALSE, include=FALSE}
freq_terms(DATA$state, top = 5)
```
You can also plot the terms.
```{r eval=FALSE, include=FALSE}
plot(freq_terms(DATA$state, top = 5))
```
There are two kinds of the corpus data types, the permanent corpus, **PCorpus**, and the volatile corpus, **VCorpus**. The volatile corpus is held in RAM rather than saved to disk. Create a volatile corpus with `tm::vCorpous()`. vCorpous() takes either a text source created with `tm::VectorSource()` or a dataframe source created with `Dataframe Source()` where the input dataframe has cols `doc_id`, `text_id` and zero or more metadata columns.
```{r eval=FALSE, include=FALSE}
tweets <- read_csv(file = "https://assets.datacamp.com/production/repositories/19/datasets/27a2a8587eff17add54f4ba288e770e235ea3325/coffee.csv")
coffee_tweets <- tweets$text
coffee_source <- VectorSource(coffee_tweets)
coffee_corpus <- VCorpus(coffee_source)
# Text of first tweet
coffee_corpus[[1]][1]
```
In bag of words text mining, cleaning helps aggregate terms, especially words with common stems like "miner" and "mining". There are several functions useful for preprocessing: `tolower()`, `tm::removePunctuation()`, `tm::removeNumbers()`, `tm::stripWhiteSpace()`, and `removeWords()`. Apply these functions to the documents in a `VCorpus` object with `tm_map()`. If the function is not one of the pre-defined functions, wrap it in `content_transformer()`. Another preprocessing function is `stemDocument()`.
```{r eval=FALSE, include=FALSE}
# Create the object: text
text <- "<b>She</b> woke up at 6 A.M. It\'s so early! She was only 10% awake and began drinking coffee in front of her computer."
tolower(text)
removePunctuation(text)
removeNumbers(text)
stripWhitespace(text)
```
The **qdap** package offers other preprocessing functions.
```{r eval=FALSE, include=FALSE}
text <- "<b>She</b> woke up at 6 A.M. It\'s so early! She was only 10% awake and began drinking coffee in front of her computer."
bracketX(text)
replace_number(text)
replace_abbreviation(text)
replace_contraction(text)
replace_symbol(text)
```
`tm::stopwords("en")` returns a vector of stop words. You can add to the list with concatenation.
```{r eval=FALSE, include=FALSE}
new_stops <- c("coffee", "bean", stopwords("en"))
removeWords(text, new_stops)
```
`tm::stemDocument()` and `tm::stemCompletion()` reduce the variation in terms.
```{r eval=FALSE, include=FALSE}
complicate <- c("complicated", "complication", "complicatedly")
stem_doc <- stemDocument(complicate)
comp_dict <- c("complicate")
complete_text <- stemCompletion(stem_doc, comp_dict)
complete_text
```
```{r eval=FALSE, include=FALSE}
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, words = c(stopwords("en"), "coffee", "mug"))
corpus <- tm_map(corpus, stripWhitespace)
return(corpus)
}
clean_corp <- clean_corpus(coffee_corpus)
content(clean_corp[[1]])
# compare to original
content(coffee_corpus[[1]])
```
To perform the analysis of the tweets, convert the corpus into either a document term matrix (DTM, documents as rows, terms as cols), or a term document matrix (TDM, terms as rows, documents as cols).
```{r eval=FALSE, include=FALSE}
coffee_tdm <- TermDocumentMatrix(clean_corp)
# Print coffee_tdm data
coffee_tdm
# Convert coffee_tdm to a matrix
coffee_m <- as.matrix(coffee_tdm)
# Print the dimensions of the matrix
dim(coffee_m)
# Review a portion of the matrix
coffee_m[c("star", "starbucks"), 25:35]
```
## Appendix: tm
The Text Mining package **tm** is a text mining framework for importing data, handling a corpus, and creating term-document matrices.
The main structure document structure is a corpus, implemented either as an in-memory *volatile corpus* `VCorpus()` or on-disk *permanent corpus* `Pcorpus()`. Create a corpus from a directory of text documents
```{r eval=FALSE}
my_rmd_corpus <- VCorpus(DirSource(pattern = "*.Rmd"))
```
or from a data frame using helper function `VectorSource()`.
```{r eval=FALSE, include=FALSE}
docs <- c("This is a text.", "This another one.")
my_vctr_corpus <- VCorpus(VectorSource(docs))
```
A corpus is a list of document objects, each containing `meta` data and `content`. Here is the first document of the one I just created.
```{r eval=FALSE, include=FALSE}
my_vctr_corpus[[1]]$meta
my_vctr_corpus[[1]]$content
```
You can perform transformations on your `tm` object, including removing extra whitespace `tm_map(x, stripWhitespace)`, converting to lowercase `tm_map(x, content_transformer(tolower))`, removing stopwords `tm_map(x, removeWords, stopwords("english"))`, and stemming `tm_map(x stemDocument)`.
Some packages (e.g., **topicmodels**) operate on a "bag of words" representation called a *document term matrix*. A bag of words is a frequency count of words. Convert the *tm* object into a matrix with `TermDocumentMatrix()` or `DocumentTermMatrix()` (the first presents terms as rows and documents as columns).
```{r eval=FALSE, include=FALSE}
dtm <- DocumentTermMatrix(my_vctr_corpus)
inspect(dtm)
```
Here is a quick analysis of the Russian Tweets data loaded at the beginning of the chapter.
```{r eval=FALSE, include=FALSE}
tweets_dtm <- VCorpus(VectorSource(tweets$content))
tweets_dtm[[1]]$meta
inspect(tweets_dtm[[1]]) # first "document"
# Add the following and followers cols as metadata
meta(tweets_dtm, 'following') <- tweets$following
meta(tweets_dtm, 'followers') <- tweets$followers
head(meta(tweets_dtm))
```