-
Notifications
You must be signed in to change notification settings - Fork 0
/
10-prediction.Rmd
397 lines (268 loc) · 9.28 KB
/
10-prediction.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
# Prediction {#prediction-chapter}
```{r, child="_common.Rmd"}
```
<p style="font-weight:bold; color:red;">INCOMPLETE DRAFT</p>
> ...
```{block, type="rmdkey"}
The essential questions for this chapter are:
- ...
- ...
- ...
```
<!-- COURSE STRUCTURE
TUTORIALS:
- ...
SWIRL:
- ...
WORKED/ RECIPE:
- ...
PROJECT:
- ...
GOALS:
...
-->
<!-- IDEAS:
- English/ Spanish language detection (chapter)
- ACTIVES
- SUBTLEX_us
- /Users/francojc/Documents/Academic/Teaching/Courses/2018-2019 Spring/LIN 380/Course/Video lectures/Language
- SPAM (recipe)
- SMS messages
- tadr::sms
- Nativeness (chapter)
- CEDEL2 (Spanish)
- Wricle and Locness (English?)
- http://wricle.learnercorpora.com/
- /Users/francojc/Documents/Academic/Research/Data/Language/Corpora/LOCNESS
- Overall prediction native/ learner
- ?Genitive construction markers native/ learner
- ?Consider exploring the Mudpar approach
- Authorship (lab)
- /Users/francojc/Documents/Academic/Research/Data/Language/Corpora/Federalist papers
- /Users/francojc/Documents/Academic/Teaching/Courses/2018-2019 Spring/LIN 380/RStudio/Data/Federalist/Documents
- RateMyProfessor (from recipe 8)
- https://data.mendeley.com/datasets/fvtfjyvw7d/2
-->
```{r prediction-data-packages, include=FALSE}
# Packages
pacman::p_load(tidyverse, tidytext, caret, quanteda, quanteda.textstats, quanteda.textmodels)
```
In this chapter we will
Orientation to the question(s) and dataset(s) to be explored ...
```{r p-read-datasets}
wricle_df <- read_csv(file = "resources/10-prediction/data/derived/wricle_formal_curated.csv")
locness_df <- read_csv(file = "resources/10-prediction/data/derived/locness_curated.csv")
```
```{r}
learners_df <-
wricle_df %>%
filter(native_language == "Spanish") %>%
mutate(student = "Spanish") %>%
mutate(type = "Learner") %>%
select(essay_id = id, type, student, essay)
glimpse(learners_df)
```
```{r}
natives_df <-
locness_df %>%
unite(col = doc_id, c("file_id", "essay_id"), sep = "-") %>%
mutate(doc_id = str_replace(doc_id, "\\.txt", "")) %>%
mutate(type = "Native") %>%
select(essay_id = doc_id, type, student, essay)
glimpse(natives_df)
```
```{r}
nativeness_df <- rbind(learners_df, natives_df) # combine
```
```{r}
nativeness_df %>%
janitor::tabyl(type)
```
```{r}
nativeness_df %>%
unnest_tokens(output = "word", input = "essay") %>%
count(word, type) %>%
group_by(type) %>%
summarize(total_words = sum(n))
```
```{r}
nativeness_corpus <-
nativeness_df %>%
corpus(text_field = "essay")
nativeness_corpus_summary <-
nativeness_corpus %>%
summary(n = ndoc(nativeness_corpus))
nativeness_corpus_summary %>%
slice_head(n = 10)
```
```{r}
nativeness_corpus$doc_id <- 1:ndoc(nativeness_corpus)
nativeness_corpus %>%
docvars() %>%
slice_head(n = 5)
```
```{r}
nativeness_tokens <-
nativeness_corpus %>%
tokens(what = "word",
remove_punct = TRUE,
remove_numbers = TRUE,
remove_symbols = TRUE)
nativeness_tokens %>%
tokens_group(groups = type) %>%
head()
```
```{r}
nativeness_dfm <-
nativeness_tokens %>%
dfm()
nativeness_dfm %>%
head(n = 5)
nativeness_dfm %>%
dfm_group(groups = type) %>%
head(n = 5)
```
```{r}
nativeness_dfm %>%
topfeatures(n = 25)
```
```{r}
nativeness_dfm %>%
textstat_frequency(n = 5, groups = type)
```
```{r}
nativeness_dfm %>%
dfm_tfidf() %>%
textstat_frequency(n = 5, groups = type, force = TRUE)
```
```{r}
set.seed(4321) # make reproducible
num_docs <-
nativeness_dfm %>%
ndoc()
train_size <-
(num_docs * .75) %>% # get size of sample
round() # round to nearest whole number
train_ids <- sample(x = 1:num_docs, # population
size = train_size, # size of sample
replace = FALSE) # without replacement
```
```{r}
nativeness_dfm_train <-
nativeness_dfm %>%
dfm_subset(doc_id %in% train_ids)
nativeness_dfm_test <-
nativeness_dfm %>%
dfm_subset(!doc_id %in% train_ids)
```
```{r}
nativeness_dfm %>%
docvars() %>%
janitor::tabyl(type)
nativeness_dfm_train %>%
docvars() %>%
janitor::tabyl(type)
nativeness_dfm_test %>%
docvars() %>%
janitor::tabyl(type)
```
```{r}
nb1 <- textmodel_nb(x = nativeness_dfm_train, y = nativeness_dfm_train$type)
summary(nb1)
coef(nb1) %>% head()
predict(nb1, type = "prob") %>% # get the predicted document scores
tail # preview predicted probability scores
```
```{r}
nb1_predictions <-
predict(nb1, type = "prob") %>% # get the predicted document scores
as.data.frame() %>% # convert to data frame
mutate(document = rownames(.)) %>% # add the document names to the data frame
as_tibble() %>% # convert to tibble
pivot_longer(cols = c("Learner", "Native"), # convert from wide to long format
names_to = "prediction", # new column for ham/spam predictions
values_to = "probability") %>% # probablity scores for each
group_by(document) %>% # group parameter by document
slice_max(probability, n = 1) %>% # keep the document row with highest probablity
slice_head(n = 1) %>% # for predictions that were 50/50
ungroup() %>% # remove grouping parameter
mutate(doc_id = str_remove(document, "text") %>% as.numeric) %>% # clean up document column so it matches doc_id in
arrange(doc_id) # order by doc_id
nb1_predictions %>%
slice_head(n = 10) # preview
```
```{r}
nb1_predictions_actual <-
cbind(actual = nb1$y, nb1_predictions) %>% # column-bind actual classes
select(doc_id, document, actual, prediction, probability) # organize variables
nb1_predictions_actual %>%
slice_head(n = 5) # preview
```
```{r}
tab_class <-
table(nb1_predictions_actual$actual, # actual class labels
nb1_predictions_actual$prediction) # predicted class labels
caret::confusionMatrix(tab_class, mode = "prec_recall") # model performance statistics
```
```{r}
predicted_class <-
predict(nb1, newdata = nativeness_dfm_test)
actual_class <- nativeness_dfm_test$type
tab_class <- table(actual_class, predicted_class) # cross-tabulate actual and predicted class labels
caret::confusionMatrix(tab_class, mode = "prec_recall") # model performance statistics
```
## Preparation
Data set transformation
Splitting into training and test sets
## Model training
Aim to use the create an abstraction of the patterns in the dataset
- Feature engineering
- Model selection
- Model evaluation
The In Figure () Let's consider the results from a hypothetical model of text classification on the SMS dataset I introduced at in this subsection.
```{r pda-contigency-table, echo=FALSE, eval=FALSE}
# Simulated table
# sms observations (testing 25%): 1210
knitr::include_graphics("images/10-prediction/pda-sms-contingency-table.png")
```
- accuracy (measure of overall correct predictions)
- precision (measure of the quality of the predictions)
- Percentage of predicted 'ham' messages that were correct
- recall (measure of the quantity of the predictions)
- Percentage of actual 'ham' messages that were correct
- F1-score (summarizes the balance between precision and recall)
Avoiding overfitting
## Model testing
Aim to test the abstracted model to new observations.
Model testing
## Evaluation
Evaluation of results
Relationship between predicted and actual classes in a confusion matrix as seen in Figure \@ref(fig:pda-confusion-matrix-image).
```{r pda-confusion-matrix-image, echo=FALSE, fig.cap='Confusion matrix'}
knitr::include_graphics("images/10-prediction/pda-confusion-matrix.png")
```
## ...
In Table () we see the top five terms for each class after breaking the messages into terms and then counting up the frequencies.
```{r pred-sms-terms-freq, echo=FALSE, eval=FALSE}
sms_f <-
sms %>%
unnest_tokens(terms, message, token = "regex", pattern = " ") %>%
count(sms_type, terms)
sms_f %>%
arrange(sms_type, desc(n)) %>%
group_by(sms_type) %>%
slice_head(n = 5) %>%
select(sms_type, terms, frequency = n) %>%
kable(booktabs = TRUE,
caption = "Top five most frequent terms for 'ham' and 'spam'.")
```
<!-- There are a couple things we may want to take into consideration given our first-pass results. First, there appears to some overlap in the top terms in each class (i.e. 'you', 'to', and 'a'). Ideally we want to create maximum separation between the terms that are most indicative of each class. Think of this from the point of view of a human learner. If you were to study a frequency list like this to try to learn how do distinguish between 'spam' and 'ham' and then you were given the term 'you' to make your decision on a test your decision would almost be a complete guess --the uncertainty is high because term figures prominently in both classes. Second you will note that the frequency for the first five terms of 'ham' is much higher than terms in 'spam'. This imbalance suggests that there are simply more 'ham' messages in our data or that 'ham' messages are longer (have more terms), or both. Any of these sources can potentially bias our machine learner to choose 'ham' over 'spam' for reasons which are not founded on the distinction between terms. -->
```{r pred-sms-dtm, echo=FALSE, eval=FALSE}
library(tidymodels)
sms_split <- initial_split(sms, strata = "sms_type")
train_data <- training(sms_split)
test_data <- testing(sms_split)
library(textrecipes)
```
## Summary
...