forked from WinVector/PDSwR2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
c10_Exploring_advanced_methods.Rmd
1617 lines (1082 loc) · 46.9 KB
/
c10_Exploring_advanced_methods.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
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
---
output: github_document
---
00324_example_10.1_of_section_10.1.1.R
```{r 00324_example_10.1_of_section_10.1.1.R }
# example 10.1 of section 10.1.1
# (example 10.1 of section 10.1.1) : Exploring advanced methods : Tree-based methods : A basic decision tree
# Title: Preparing Spambase data and evaluating a decision tree model
spamD <- read.table('../Spambase/spamD.tsv', header = TRUE, sep = '\t') # Note: 1
spamD$isSpam <- spamD$spam == 'spam'
spamTrain <- subset(spamD, spamD$rgroup >= 10)
spamTest <- subset(spamD, spamD$rgroup < 10)
spamVars <- setdiff(colnames(spamD), list('rgroup', 'spam', 'isSpam'))
library(wrapr)
spamFormula <- mk_formula("isSpam", spamVars) # Note: 2
loglikelihood <- function(y, py) { # Note: 3
pysmooth <- ifelse(py == 0, 1e-12,
ifelse(py == 1, 1 - 1e-12, py))
sum(y * log(pysmooth) + (1 - y) * log(1 - pysmooth))
}
accuracyMeasures <- function(pred, truth, name = "model") { # Note: 4
dev.norm <- -2 * loglikelihood(as.numeric(truth), pred) / length(pred) # Note: 5
ctable <- table(truth = truth,
pred = (pred > 0.5)) # Note: 6
accuracy <- sum(diag(ctable)) / sum(ctable)
precision <- ctable[2, 2] / sum(ctable[, 2])
recall <- ctable[2, 2] / sum(ctable[2, ])
f1 <- 2 * precision * recall / (precision + recall)
data.frame(model = name, accuracy = accuracy, f1 = f1, dev.norm)
}
library(rpart) # Note: 7
treemodel <- rpart(spamFormula, spamTrain, method = "class")
library(rpart.plot) # Note: 8
rpart.plot(treemodel, type = 5, extra = 6)
predTrain <- predict(treemodel, newdata = spamTrain)[, 2] # Note: 9
trainperf_tree <- accuracyMeasures(predTrain, # Note: 10
spamTrain$spam == "spam",
name = "tree, training")
predTest <- predict(treemodel, newdata = spamTest)[, 2]
testperf_tree <- accuracyMeasures(predTest,
spamTest$spam == "spam",
name = "tree, test")
# Note 1:
# Load the data and split into training (90% of data)
# and test (10% of data) sets.
# Note 2:
# Use all the features and do binary classification,
# where TRUE corresponds to spam documents.
# Note 3:
# A function to calculate log likelihood
# (for calculating deviance).
# Note 4:
# A function to calculate and return various measures
# on the model: normalized deviance, prediction accuracy, and f1.
# Note 5:
# Normalize the deviance by the number of data points
# so that we can compare the deviance across training and test sets.
# Note 6:
# Convert the class probability estimator into a
# classifier by labeling documents that score greater than 0.5 as
# spam.
# Note 7:
# Load the rpart library and fit a decision tree
# model.
# Note 8:
# For plotting the tree.
# Note 9:
# Get the predicted probabilities of the class
# "spam".
# Note 10:
# Evaluate the decision tree model against the
# training and test sets.
```
00325_informalexample_10.1_of_section_10.1.1.R
```{r 00325_informalexample_10.1_of_section_10.1.1.R }
# informalexample 10.1 of section 10.1.1
# (informalexample 10.1 of section 10.1.1) : Exploring advanced methods : Tree-based methods : A basic decision tree
library(pander) # Note: 1
panderOptions("plain.ascii", TRUE) # Note: 2
panderOptions("keep.trailing.zeros", TRUE)
panderOptions("table.style", "simple")
perf_justify <- "lrrr"
perftable <- rbind(trainperf_tree, testperf_tree)
pandoc.table(perftable, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## ---------------- ---------- -------- ----------
## tree, training 0.8996 0.8691 0.6304
## tree, test 0.8712 0.8280 0.7531
# Note 1:
# A package to make nicely formatted ascii tables.
# Note 2:
# Set some options globally so we don't have to keep setting them in every call.
```
00326_example_10.2_of_section_10.1.2.R
```{r 00326_example_10.2_of_section_10.1.2.R }
# example 10.2 of section 10.1.2
# (example 10.2 of section 10.1.2) : Exploring advanced methods : Tree-based methods : Using bagging to improve prediction
# Title: Bagging decision trees
ntrain <- dim(spamTrain)[1]
n <- ntrain # Note: 1
ntree <- 100
samples <- sapply(1:ntree, # Note: 2
FUN = function(iter)
{ sample(1:ntrain, size = n, replace = TRUE) })
treelist <-lapply(1:ntree, # Note: 3
FUN = function(iter) {
samp <- samples[, iter];
rpart(spamFormula, spamTrain[samp, ], method = "class") })
predict.bag <- function(treelist, newdata) { # Note: 4
preds <- sapply(1:length(treelist),
FUN = function(iter) {
predict(treelist[[iter]], newdata = newdata)[, 2] })
predsums <- rowSums(preds)
predsums / length(treelist)
}
pred <- predict.bag(treelist, newdata = spamTrain)
trainperf_bag <- accuracyMeasures(pred, # Note: 5
spamTrain$spam == "spam",
name = "bagging, training")
pred <- predict.bag(treelist, newdata = spamTest)
testperf_bag <- accuracyMeasures(pred,
spamTest$spam == "spam",
name = "bagging, test")
perftable <- rbind(trainperf_bag, testperf_bag)
pandoc.table(perftable, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## ------------------- ---------- -------- ----------
## bagging, training 0.9167 0.8917 0.5080
## bagging, test 0.9127 0.8824 0.5793
# Note 1:
# Use bootstrap samples the same size as the training
# set, with 100 trees.
# Note 2:
# Build the bootstrap samples by sampling the row indices of spamTrain with replacement. Each
# column of the matrix samples represents the row indices into spamTrain
# that comprise the bootstrap sample.
# Note 3:
# Train the individual decision trees and return them
# in a list. Note: this step can take a few minutes.
# Note 4:
# predict.bag assumes the underlying classifier returns decision probabilities, not
# decisions. predict.bag takes the mean of the predictions of all the individual trees
# Note 5:
# Evaluate the bagged decision trees against the
# training and test sets.
```
00327_example_10.3_of_section_10.1.3.R
```{r 00327_example_10.3_of_section_10.1.3.R }
# example 10.3 of section 10.1.3
# (example 10.3 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
# Title: Using random forests
library(randomForest) # Note: 1
set.seed(5123512) # Note: 2
fmodel <- randomForest(x = spamTrain[, spamVars], # Note: 3
y = spamTrain$spam,
ntree = 100, # Note: 4
nodesize = 7, # Note: 5
importance = TRUE) # Note: 6
pred <- predict(fmodel,
spamTrain[, spamVars],
type = 'prob')[, 'spam']
trainperf_rf <- accuracyMeasures(predict(fmodel, # Note: 7
newdata = spamTrain[, spamVars], type = 'prob')[, 'spam'],
spamTrain$spam == "spam", name = "random forest, train")
testperf_rf <- accuracyMeasures(predict(fmodel,
newdata = spamTest[, spamVars], type = 'prob')[, 'spam'],
spamTest$spam == "spam", name = "random forest, test")
perftable <- rbind(trainperf_rf, testperf_rf)
pandoc.table(perftable, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## ---------------------- ---------- -------- ----------
## random forest, train 0.9884 0.9852 0.1440
## random forest, test 0.9498 0.9341 0.3011
# Note 1:
# Load the randomForest package.
# Note 2:
# Set the pseudo-random seed to a known value to try to make the random forest run
# repeatable.
# Note 3:
# Call the randomForest() function to build the model
# with explanatory variables as x and the category to be predicted as
# y.
# Note 4:
# Use 100 trees to be compatible with our bagging
# example. The default is 500 trees.
# Note 5:
# Specify that each node of a tree must have a minimum of 7 elements to be compatible with the
# default minimum node size that rpart() uses on this training set.
# Note 6:
# Tell the algorithm to save information to be used for
# calculating variable importance (we’ll see this later).
# Note 7:
# Report the model quality.
```
00328_informalexample_10.2_of_section_10.1.3.R
```{r 00328_informalexample_10.2_of_section_10.1.3.R }
# informalexample 10.2 of section 10.1.3
# (informalexample 10.2 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
trainf <- rbind(trainperf_tree, trainperf_bag, trainperf_rf)
pandoc.table(trainf, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## ---------------------- ---------- -------- ----------
## tree, training 0.8996 0.8691 0.6304
## bagging, training 0.9160 0.8906 0.5106
## random forest, train 0.9884 0.9852 0.1440
```
00329_informalexample_10.3_of_section_10.1.3.R
```{r 00329_informalexample_10.3_of_section_10.1.3.R }
# informalexample 10.3 of section 10.1.3
# (informalexample 10.3 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
testf <- rbind(testperf_tree, testperf_bag, testperf_rf)
pandoc.table(testf, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## --------------------- ---------- -------- ----------
## tree, test 0.8712 0.8280 0.7531
## bagging, test 0.9105 0.8791 0.5834
## random forest, test 0.9498 0.9341 0.3011
```
00330_informalexample_10.4_of_section_10.1.3.R
```{r 00330_informalexample_10.4_of_section_10.1.3.R }
# informalexample 10.4 of section 10.1.3
# (informalexample 10.4 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
difff <- data.frame(model = c("tree", "bagging", "random forest"),
accuracy = trainf$accuracy - testf$accuracy,
f1 = trainf$f1 - testf$f1,
dev.norm = trainf$dev.norm - testf$dev.norm)
pandoc.table(difff, justify=perf_justify)
##
##
## model accuracy f1 dev.norm
## --------------- ---------- --------- ----------
## tree 0.028411 0.04111 -0.12275
## bagging 0.005523 0.01158 -0.07284
## random forest 0.038633 0.05110 -0.15711
```
00331_example_10.4_of_section_10.1.3.R
```{r 00331_example_10.4_of_section_10.1.3.R }
# example 10.4 of section 10.1.3
# (example 10.4 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
# Title: randomForest variable importances
varImp <- importance(fmodel) # Note: 1
varImp[1:10, ] # Note: 2
## non-spam spam MeanDecreaseAccuracy
## word.freq.make 1.656795 3.432962 3.067899
## word.freq.address 2.631231 3.800668 3.632077
## word.freq.all 3.279517 6.235651 6.137927
## word.freq.3d 3.900232 1.286917 3.753238
## word.freq.our 9.966034 10.160010 12.039651
## word.freq.over 4.657285 4.183888 4.894526
## word.freq.remove 19.172764 14.020182 20.229958
## word.freq.internet 7.595305 5.246213 8.036892
## word.freq.order 3.167008 2.505777 3.065529
## word.freq.mail 3.820764 2.786041 4.869502
varImpPlot(fmodel, type = 1) # Note: 3
# Note 1:
# Call importance() on the spam
# model.
# Note 2:
# The importance() function returns a matrix of
# importance measures (larger values = more important).
# Note 3:
# Plot the variable importance as measured by
# accuracy change.
```
00332_example_10.5_of_section_10.1.3.R
```{r 00332_example_10.5_of_section_10.1.3.R }
# example 10.5 of section 10.1.3
# (example 10.5 of section 10.1.3) : Exploring advanced methods : Tree-based methods : Using random forests to further improve prediction
# Title: Fitting with fewer variables
sorted <- sort(varImp[, "MeanDecreaseAccuracy"], # Note: 1
decreasing = TRUE)
selVars <- names(sorted)[1:30]
fsel <- randomForest(x = spamTrain[, selVars], # Note: 2
y = spamTrain$spam,
ntree = 100,
nodesize = 7,
importance = TRUE)
trainperf_rf2 <- accuracyMeasures(predict(fsel,
newdata = spamTrain[, selVars], type = 'prob')[, 'spam'],
spamTrain$spam == "spam", name = "RF small, train")
testperf_rf2 <- accuracyMeasures(predict(fsel,
newdata=spamTest[, selVars], type = 'prob')[, 'spam'],
spamTest$spam == "spam", name = "RF small, test")
perftable <- rbind(testperf_rf, testperf_rf2) # Note: 3
pandoc.table(perftable, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## --------------------- ---------- -------- ----------
## random forest, test 0.9498 0.9341 0.3011
## RF small, test 0.9520 0.9368 0.4000
# Note 1:
# Sort the variables by their importance, as
# measured by accuracy change.
# Note 2:
# Build a random forest model using only the 30
# most important variables.
# Note 3:
# Compare the two random forest models on the test set.
```
00333_example_10.6_of_section_10.1.4.R
```{r 00333_example_10.6_of_section_10.1.4.R }
# example 10.6 of section 10.1.4
# (example 10.6 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Load the iris data
iris <- iris
iris$class <- as.numeric(iris$Species == "setosa") # Note: 1
set.seed(2345)
intrain <- runif(nrow(iris)) < 0.75 # Note: 2
train <- iris[intrain, ]
test <- iris[!intrain, ]
head(train)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species class
## 1 5.1 3.5 1.4 0.2 setosa 1
## 2 4.9 3.0 1.4 0.2 setosa 1
## 3 4.7 3.2 1.3 0.2 setosa 1
## 4 4.6 3.1 1.5 0.2 setosa 1
## 5 5.0 3.6 1.4 0.2 setosa 1
## 6 5.4 3.9 1.7 0.4 setosa 1
input <- as.matrix(train[, 1:4]) # Note: 3
# Note 1:
# setosa is the positive class.
# Note 2:
# Split the data into training and test (75%/25%).
# Note 3:
# Create the input matrix.
```
00334_example_10.7_of_section_10.1.4.R
```{r 00334_example_10.7_of_section_10.1.4.R }
# example 10.7 of section 10.1.4
# (example 10.7 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Cross-validate to determine model size
library(xgboost)
cv <- xgb.cv(input, # Note: 1
label = train$class, # Note: 2
params = list(
objective = "binary:logistic" # Note: 3
),
nfold = 5, # Note: 4
nrounds = 100, # Note: 5
print_every_n = 10, # Note: 6
metrics = "logloss") # Note: 7
evalframe <- as.data.frame(cv$evaluation_log) # Note: 8
head(evalframe) # Note: 9
## iter train_logloss_mean train_logloss_std test_logloss_mean
## 1 1 0.4547800 7.758350e-05 0.4550578
## 2 2 0.3175798 9.268527e-05 0.3179284
## 3 3 0.2294212 9.542411e-05 0.2297848
## 4 4 0.1696242 9.452492e-05 0.1699816
## 5 5 0.1277388 9.207258e-05 0.1280816
## 6 6 0.0977648 8.913899e-05 0.0980894
## test_logloss_std
## 1 0.001638487
## 2 0.002056267
## 3 0.002142687
## 4 0.002107535
## 5 0.002020668
## 6 0.001911152
(NROUNDS <- which.min(evalframe$test_logloss_mean)) # Note: 10
## [1] 18
library(ggplot2)
ggplot(evalframe, aes(x = iter, y = test_logloss_mean)) +
geom_line() +
geom_vline(xintercept = NROUNDS, color = "darkred", linetype = 2) +
ggtitle("Cross-validated log loss as a function of ensemble size")
# Note 1:
# The input matrix.
# Note 2:
# The class labels, which must also be numeric
# (1 for setosa, 0 for not setosa).
# Note 3:
# Use the objective "binary:logistic" for binary
# classification, "reg:linear" for regression.
# Note 4:
# Use 5-fold cross-validation.
# Note 5:
# Build an ensemble of 100 trees.
# Note 6:
# Print a message every 10th iteration
# (use verbose = FALSE for no messages).
# Note 7:
# Use minimum cross-validated logloss (related to deviance)
# to pick the optimum number of trees. for regression,
# use metrics = "rmse"
# Note 8:
# Get the performance log.
# Note 9:
# evalframe records the training and cross-validated
# logloss as a function of the number of trees.
# Note 10:
# Find the number of trees that gave the minimum
# cross-validated logloss.
```
00335_example_10.8_of_section_10.1.4.R
```{r 00335_example_10.8_of_section_10.1.4.R }
# example 10.8 of section 10.1.4
# (example 10.8 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Fit an xgboost model
model <- xgboost(data = input,
label = train$class,
params = list(
objective = "binary:logistic"
),
nrounds = NROUNDS,
verbose = FALSE)
test_input <- as.matrix(test[, 1:4]) # Note: 1
pred <- predict(model, test_input) # Note: 2
accuracyMeasures(pred, test$class)
## model accuracy f1 dev.norm
## 1 model 1 1 0.03458392
# Note 1:
# Create the input matrix for the test data.
# Note 2:
# Make predictions
```
00336_informalexample_10.5_of_section_10.1.4.R
```{r 00336_informalexample_10.5_of_section_10.1.4.R }
# informalexample 10.5 of section 10.1.4
# (informalexample 10.5 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
library(zeallot)
c(texts, labels) %<-% readRDS("../IMDB/IMDBtrain.RDS")
```
00337_informalexample_10.6_of_section_10.1.4.R
```{r 00337_informalexample_10.6_of_section_10.1.4.R }
# informalexample 10.6 of section 10.1.4
# (informalexample 10.6 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
source("../IMDB/lime_imdb_example.R")
vocab <- create_pruned_vocabulary(texts)
dtm_train <- make_matrix(texts, vocab)
```
00338_informalexample_10.7_of_section_10.1.4.R
```{r 00338_informalexample_10.7_of_section_10.1.4.R }
# informalexample 10.7 of section 10.1.4
# (informalexample 10.7 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
cv <- xgb.cv(dtm_train,
label = labels,
params = list(
objective = "binary:logistic"
),
nfold = 5,
nrounds = 500,
early_stopping_rounds = 20, # Note: 1
print_every_n = 10,
metrics = "logloss")
evalframe <- as.data.frame(cv$evaluation_log)
(NROUNDS <- which.min(evalframe$test_logloss_mean))
## [1] 319
# Note 1:
# Stop early if performance doesn’t improve for
# 20 rounds.
```
00339_informalexample_10.8_of_section_10.1.4.R
```{r 00339_informalexample_10.8_of_section_10.1.4.R }
# informalexample 10.8 of section 10.1.4
# (informalexample 10.8 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
model <- xgboost(data = dtm_train, label = labels,
params = list(
objective = "binary:logistic"
),
nrounds = NROUNDS,
verbose = FALSE)
pred = predict(model, dtm_train)
trainperf_xgb = accuracyMeasures(pred, labels, "training")
c(test_texts, test_labels) %<-% readRDS("../IMDB/IMDBtest.RDS") # Note: 1
dtm_test = make_matrix(test_texts, vocab)
pred = predict(model, dtm_test)
testperf_xgb = accuracyMeasures(pred, test_labels, "test")
perftable <- rbind(trainperf_xgb, testperf_xgb)
pandoc.table(perftable, justify = perf_justify)
##
##
## model accuracy f1 dev.norm
## ---------- ---------- -------- ----------
## training 0.9891 0.9891 0.1723
## test 0.8725 0.8735 0.5955
# Note 1:
# Load the test data and convert it to a document-term matrix.
```
00340_example_10.9_of_section_10.1.4.R
```{r 00340_example_10.9_of_section_10.1.4.R }
# example 10.9 of section 10.1.4
# (example 10.9 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Load the natality data
load("../CDC/NatalBirthData.rData")
train <- sdata[sdata$ORIGRANDGROUP <= 5, ] # Note: 1
test <- sdata[sdata$ORIGRANDGROUP >5 , ]
input_vars <- setdiff(colnames(train), c("DBWT", "ORIGRANDGROUP")) # Note: 2
str(train[, input_vars])
## 'data.frame': 14386 obs. of 11 variables:
## $ PWGT : int 155 140 151 160 135 180 200 135 112 98 ...
## $ WTGAIN : int 42 40 1 47 25 20 24 51 36 22 ...
## $ MAGER : int 30 32 34 32 24 25 26 26 20 22 ...
## $ UPREVIS : int 14 13 15 1 4 10 14 15 14 10 ...
## $ CIG_REC : logi FALSE FALSE FALSE TRUE FALSE FALSE ...
## $ GESTREC3 : Factor w/ 2 levels ">= 37 weeks",..: 1 1 1 2 1 1 1 1 1 1 ...
## $ DPLURAL : Factor w/ 3 levels "single","triplet or higher",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ URF_DIAB : logi FALSE FALSE FALSE FALSE FALSE FALSE ...
## $ URF_CHYPER: logi FALSE FALSE FALSE FALSE FALSE FALSE ...
## $ URF_PHYPER: logi FALSE FALSE FALSE FALSE FALSE FALSE ...
## $ URF_ECLAM : logi FALSE FALSE FALSE FALSE FALSE FALSE ...
# Note 1:
# Split the data into training and test sets.
# Note 2:
# Use all the variables in the model.
# DBWT (baby's birth weight) is
# the value to be predicted, and ORIGRANDGROUP is the grouping variable.
```
00341_example_10.10_of_section_10.1.4.R
```{r 00341_example_10.10_of_section_10.1.4.R }
# example 10.10 of section 10.1.4
# (example 10.10 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Use vtreat to prepare data for xgboost
library(vtreat)
treatplan <- designTreatmentsZ(train, # Note: 1
input_vars,
codeRestriction = c("clean", "isBAD", "lev" ), # Note: 2
verbose = FALSE)
train_treated <- prepare(treatplan, train) # Note: 3
str(train_treated)
## 'data.frame': 14386 obs. of 14 variables:
## $ PWGT : num 155 140 151 160 135 180 200 135 112 98 ...
## $ WTGAIN : num 42 40 1 47 25 20 24 51 36 22 ...
## $ MAGER : num 30 32 34 32 24 25 26 26 20 22 ...
## $ UPREVIS : num 14 13 15 1 4 10 14 15 14 10 ...
## $ CIG_REC : num 0 0 0 1 0 0 0 0 0 0 ...
## $ URF_DIAB : num 0 0 0 0 0 0 0 0 0 0 ...
## $ URF_CHYPER : num 0 0 0 0 0 0 0 0 0 0 ...
## $ URF_PHYPER : num 0 0 0 0 0 0 0 0 0 0 ...
## $ URF_ECLAM : num 0 0 0 0 0 0 0 0 0 0 ...
## $ GESTREC3_lev_x_37_weeks : num 0 0 0 1 0 0 0 0 0 0 ...
## $ GESTREC3_lev_x_37_weeks_1 : num 1 1 1 0 1 1 1 1 1 1 ...
## $ DPLURAL_lev_x_single : num 1 1 1 1 1 1 1 1 1 1 ...
## $ DPLURAL_lev_x_triplet_or_higher: num 0 0 0 0 0 0 0 0 0 0 ...
## $ DPLURAL_lev_x_twin : num 0 0 0 0 0 0 0 0 0 0 ...
# Note 1:
# Create the treatment plan.
# Note 2:
# Create clean numeric variables ("clean"),
# missingness indicators ("isBad"),
# indicator variables ("lev"),
# but not catP (prevalence) variables.
# Note 3:
# Prepare the training data.
```
00342_example_10.11_of_section_10.1.4.R
```{r 00342_example_10.11_of_section_10.1.4.R }
# example 10.11 of section 10.1.4
# (example 10.11 of section 10.1.4) : Exploring advanced methods : Tree-based methods : Gradient-boosted trees
# Title: Fit and apply an xgboost model for birth weight
birthwt_model <- xgboost(as.matrix(train_treated),
train$DBWT,
params = list(
objective = "reg:linear",
base_score = mean(train$DBWT)
),
nrounds = 50,
verbose = FALSE)
test_treated <- prepare(treatplan, test)
pred <- predict(birthwt_model, as.matrix(test_treated))
```
00345_example_10.12_of_section_10.2.2.R
```{r 00345_example_10.12_of_section_10.2.2.R }
# example 10.12 of section 10.2.2
# (example 10.12 of section 10.2.2) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : A one-dimensional regression example
# Title: Preparing an artificial problem
set.seed(602957)
x <- rnorm(1000)
noise <- rnorm(1000, sd = 1.5)
y <- 3 * sin(2 * x) + cos(0.75 * x) - 1.5 * (x^2) + noise
select <- runif(1000)
frame <- data.frame(y = y, x = x)
train <- frame[select > 0.1, ]
test <-frame[select <= 0.1, ]
```
00346_example_10.13_of_section_10.2.2.R
```{r 00346_example_10.13_of_section_10.2.2.R }
# example 10.13 of section 10.2.2
# (example 10.13 of section 10.2.2) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : A one-dimensional regression example
# Title: Linear regression applied to the artificial example
lin_model <- lm(y ~ x, data = train)
summary(lin_model)
##
## Call:
## lm(formula = y ~ x, data = train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.698 -1.774 0.193 2.499 7.529
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.8330 0.1161 -7.175 1.51e-12 ***
## x 0.7395 0.1197 6.180 9.74e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.485 on 899 degrees of freedom
## Multiple R-squared: 0.04075, Adjusted R-squared: 0.03968
## F-statistic: 38.19 on 1 and 899 DF, p-value: 9.737e-10
rmse <- function(residuals) { # Note: 1
sqrt(mean(residuals^2))
}
train$pred_lin <- predict(lin_model, train) # Note: 2
resid_lin <- with(train, y - pred_lin)
rmse(resid_lin)
## [1] 3.481091
library(ggplot2) # Note: 3
ggplot(train, aes(x = pred_lin, y = y)) +
geom_point(alpha = 0.3) +
geom_abline()
# Note 1:
# A convenience function for calculating
# root mean squared error (RMSE) from a vector of residuals.
# Note 2:
# Calculate the RMSE of this model on the training data.
# Note 3:
# Plot y versus prediction.
```
00347_example_10.14_of_section_10.2.2.R
```{r 00347_example_10.14_of_section_10.2.2.R }
# example 10.14 of section 10.2.2
# (example 10.14 of section 10.2.2) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : A one-dimensional regression example
# Title: GAM applied to the artificial example
library(mgcv) # Note: 1
gam_model <- gam(y ~ s(x), data = train) # Note: 2
gam_model$converged # Note: 3
## [1] TRUE
summary(gam_model)
## Family: gaussian # Note: 4
## Link function: identity
##
## Formula:
## y ~ s(x)
##
## Parametric coefficients: # Note: 5
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.83467 0.04852 -17.2 <2e-16 ***
## ---
## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
##
## Approximate significance of smooth terms: # Note: 6
## edf Ref.df F p-value
## s(x) 8.685 8.972 497.8 <2e-16 ***
## ---
## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
##
## R-sq.(adj) = 0.832 Deviance explained = 83.4% # Note: 7
## GCV score = 2.144 Scale est. = 2.121 n = 901
train$pred <- predict(gam_model, train) # Note: 8
resid_gam <- with(train, y - pred)
rmse(resid_gam)