-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.Rmd
executable file
·499 lines (374 loc) · 9.35 KB
/
index.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
---
title: "Text Analysis in R"
subtitle: "Special Christmas Edition"
author: "Emil Hvitfeldt"
date: "2018-10-29"
output:
xaringan::moon_reader:
css: ["default", "theme.css"]
lib_dir: libs
nature:
beforeInit: "macros.js"
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
titleSlideClass: [center, middle]
---
```{r include=FALSE}
library(knitr)
hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
lines <- options$output.lines
if (is.null(lines)) {
return(hook_output(x, options)) # pass to default hook
}
x <- unlist(strsplit(x, "\n"))
more <- "..."
if (length(lines) == 1) { # first n lines
if (length(x) > lines) {
# truncate the output, but add ....
x <- c(head(x, lines), more)
}
} else {
x <- c(more, x[lines], more)
}
# paste these lines together
x <- paste(c(x, ""), collapse = "\n")
hook_output(x, options)
})
library(tidyr)
```
# What is Natural Language Processing (NLP)
Using computers to extract insights and make decision based on human languages.
- Information extraction
- Machine translation
- Speech processing
- Image understanding
???
https://www.ling.upenn.edu/~beatrice/humor/headlines.html
Not Computational linguistics which is using computers to reason about human langauges
---
# Plan of Action
## Text mining
We will be doing text mining as exploratory data analysis
## Modeling
Apply some simple models to make decisions only based on text
---
background-image: url("http://3.bp.blogspot.com/-FDjkfNyHOCA/UNNVcB9eBsI/AAAAAAAABp4/fivfG6senDU/s1600/fir-tree1.jpg")
background-position: 90% 35%
background-size: 20% 30%
# The Data
## Text mining
The Fir Tree
H.C. Andersen
21 December 1844
EK (**e**ventyr**k**ode / fairly tale code) = 26
Fairly early, one of first works displaying pessimism.
???
Types of data
- Strings
- Document term matrix
- Corpus
---
# The Data
## Modeling
Movie reviews from [IMDb.com](IMDb.com)
2 Movies
---
.pull-left[

]
.pull-right[

]
---
# Finding gold
.medium[
```{r}
#devtools::install_github("emilhvitfeldt/hcandersenr")
library(hcandersenr)
```
]
Includes most of H.C. Andersens 157 fairly tales in 5 languages (Danish, German, English, Spanish, French).
--
.medium[
```{r}
library(dplyr)
library(tidyr)
tree <- hcandersen_en %>%
filter(book == "The fir tree") %>%
select(text)
```
]
---
# The Text
.smallish[
```{r}
tree
```
]
---
.pull-left[
```{r}
library(tidytext)
unnest_tokens(tree, word, text) #<<
```
]
.pull-right[
Observational unit:
- Document
- Sentence
- Word
- Letter
]
---
.pull-left[
```{r}
library(tidytext)
unnest_tokens(tree, word, text) #<<
```
]
.pull-right[
Observational unit:
- ~~Document~~
- ~~Sentence~~
- **Word**
- ~~Letter~~
Word tokens are default in `unnest_tokens()`
]
---
```{r}
library(tidytext)
unnest_tokens(tree, word, text) %>%
count(word, sort = TRUE) #<<
```
---
```{r, highlight.output=c(4, 5, 7, 8, 9, 10, 11, 12, 13)}
library(tidytext)
unnest_tokens(tree, word, text) %>%
count(word, sort = TRUE) #<<
```
--
These words don't give us much context
---
# Stop words
Stop words or "non-context" words are words that doens't add much to the text (filler that make sentences work).
```{r, output.lines = 9}
stop_words$word
```
---
# Stop words
Stop words or "non-context" words are words that doens't add much to the text (filler that make sentences work).
Don't remove stop words willy nilly!
Pre-constructed word list might not work in your domain
Creating your own word list is hard...
???
Lean
computer
old
---
```{r}
unnest_tokens(tree, word, text) %>%
inner_join(stop_words, by = "word") %>% #<<
count(word, sort = TRUE) %>%
top_n(50, n) %>%
pull(word)
```
Look at the words you remove (easy)
or know you stop word by heart (hard!!!)
---
```{r}
unnest_tokens(tree, word, text) %>%
anti_join(stop_words, by = "word") %>% #<<
count(word, sort = TRUE)
```
---
```{r, eval=FALSE}
library(ggplot2)
unnest_tokens(tree, word, text) %>%
anti_join(stop_words, by = "word") %>%
count(word, sort = TRUE) %>%
top_n(10, n) %>%
ggplot(aes(reorder(word, n), n)) +
geom_col() +
coord_flip() +
theme_light() +
labs(x = "Times",
y = "Word",
title = "Word frequency in 'The Fur Tree'")
```
---
```{r echo=FALSE, fig.asp=0.618, fig.width=5, dpi=300, out.width='100%'}
library(ggplot2)
unnest_tokens(tree, word, text) %>%
anti_join(stop_words, by = "word") %>%
count(word, sort = TRUE) %>%
top_n(10, n) %>%
ggplot(aes(reorder(word, n), n)) +
geom_col() +
coord_flip() +
theme_light() +
labs(x = "Times",
y = "Word",
title = "Word frequency in 'The Fur Tree'")
```
---
```{r, eval=FALSE}
unnest_tokens(tree, word, text) %>%
mutate(pos = row_number(),
place = word == "story") %>%
filter(place) %>%
ggplot(aes(pos, place)) +
geom_point() +
theme_light() +
labs(x = "Position",
y = "",
title = "Occurence plot of word 'story'")
```
---
```{r, echo=FALSE, out.width = '90%', fig.asp=0.618, fig.width=4, dpi=300}
unnest_tokens(tree, word, text) %>%
mutate(pos = row_number(),
place = word == "story") %>%
filter(place) %>%
ggplot(aes(pos, place)) +
geom_point() +
theme_light() +
labs(x = "Position",
y = "",
title = "Occurence plot of word 'story'")
```
---
```{r, eval=FALSE}
unnest_tokens(tree, word, text) %>%
mutate(pos = row_number(),
place = case_when(word == "story" ~ "story",
word %in% c("tree", "trees") ~ "tree",
word == "mice" ~ "mice",
word == "children" ~ "children",
word == "forest" ~ "forest",
TRUE ~ NA_character_)) %>%
drop_na() %>%
ggplot(aes(pos, place, color = place)) +
geom_point() +
theme_light() +
guides(color = "none") +
labs(x = "Position",
y = "Word",
title = "Occurence plot of 'The Fur Tree'")
```
---
```{r, echo=FALSE, out.width = '90%', fig.asp=0.618, fig.width=4, dpi=300}
unnest_tokens(tree, word, text) %>%
mutate(pos = row_number(),
place = case_when(word == "story" ~ "story",
word %in% c("tree", "trees") ~ "tree",
word == "mice" ~ "mice",
word == "children" ~ "children",
word == "forest" ~ "forest",
TRUE ~ NA_character_)) %>%
drop_na() %>%
ggplot(aes(pos, place, color = place)) +
geom_jitter(width = 0, height = 0.2) +
theme_light() +
guides(color = "none") +
labs(x = "Position",
y = "Word",
title = "Occurence plot of 'The Fur Tree'")
```
---
## Going to the movies
Scraped review (scraping_reviews.Rmd)
```{r, message=FALSE}
library(readr)
library(tidyr)
reviews <- read_csv("review_data.csv") %>%
select(movie, rating, review) %>%
drop_na()
```
.smallish[
```{r, echo=FALSE}
reviews
```
]
---
```{r, out.width = '90%', fig.asp=0.618, fig.width=4, dpi=300}
ggplot(reviews, aes(as.factor(rating), 1, fill = movie)) +
geom_col() +
facet_grid(~ movie) +
theme_minimal() +
labs(x = "Rating",
y = "Count") +
guides(fill = "none")
```
---
## tidymodels
```{r}
library(tidymodels)
#devtools::install_github("tidymodels/textrecipes")
library(textrecipes)
```
`tidymodels` is a "meta-package" for modeling and statistical analysis that share the underlying design philosophy, grammar, and data structures of the tidyverse.
`textrecipes` is an addition to the recipes package providing text processing capabilities (coming to CRAN any day)
---
.medium[
```{r}
set.seed(2018)
split <- reviews %>%
mutate(good = factor(rating > 5, labels = c("bad", "good"))) %>%
select(good, text = review) %>%
initial_split(props = 7 / 10)
review_train <- training(split)
review_test <- testing(split)
```
]
Splitting data into training and testing set
Next we specify a preprocesing step using recipes
---
## What do we measure?

---
.medium[
```{r, eval=FALSE}
review_rec <- recipe(good ~ ., data = review_train) %>%
step_tokenize(text) %>%
step_tokenfilter(text, max_tokens = 500) %>%
step_tfidf(text) %>%
prep(training = review_train)
review_rec
```
]
```{r, echo=FALSE}
review_rec <- recipe(good ~ ., data = review_train) %>%
step_tokenize(text) %>%
step_tokenfilter(text, max_tokens = 500) %>%
step_tf(text) %>%
prep(training = review_train)
review_rec
```
---
```{r}
# Processed data
train_data <- juice(review_rec)
test_data <- bake(review_rec, review_test)
```
```{r}
train_data
```
---
```{r}
review_model <- logistic_reg() %>%
set_engine("glm")
```
```{r, message=FALSE, warning=FALSE}
review_fit <- review_model %>%
fit(good ~ ., data = train_data)
```
```{r}
test_results <- review_test %>%
bind_cols(
predict(review_fit, test_data)
)
test_results %>% accuracy(truth = good, estimate = .pred_class)
```
(This is not an example of finished classification. The Accuracy is not that good, but the general steps you would follow.)