-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathrCh09.html
1762 lines (1513 loc) · 73.4 KB
/
rCh09.html
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
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>())
<span class="kw">source</span>(<span class="st">'runDir.R'</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(<span class="st">'ggplot2'</span>)
<span class="kw">runDir</span>(<span class="st">'../CodeExamples/c09_Exploring_advanced_methods'</span>,
<span class="st">'../Spambase'</span>,<span class="dt">last=</span><span class="dv">179</span>)</code></pre></div>
<pre><code>[1] "############################### start 165 Fri Jun 17 10:42:20 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00165_example_9.1_of_section_9.1.1.R"
[1] "##### in directory ../Spambase"
> # example 9.1 of section 9.1.1
> # (example 9.1 of section 9.1.1) : Exploring advanced methods : Using bagging and random forests to reduce training variance : Using bagging to improve prediction
> # Title: Preparing Spambase data and evaluating the performance of decision trees
>
> spamD <- read.table('spamD.tsv',header=T,sep='\t') # Note: 1
> spamTrain <- subset(spamD,spamD$rgroup>=10)
> spamTest <- subset(spamD,spamD$rgroup<10)
> spamVars <- setdiff(colnames(spamD),list('rgroup','spam'))
> spamFormula <- as.formula(paste('spam=="spam"', # Note: 2
paste(spamVars,collapse=' + '),sep=' ~ '))
> 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)
> accuracyMeasures(predict(treemodel, newdata=spamTrain), # Note: 8
spamTrain$spam=="spam",
name="tree, training")
model accuracy f1 dev.norm
1 tree, training 0.9104514 0.88337 0.5618654
> accuracyMeasures(predict(treemodel, newdata=spamTest),
spamTest$spam=="spam",
name="tree, test")
model accuracy f1 dev.norm
1 tree, test 0.8799127 0.8414986 0.6702857
> # 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, which is the
> # harmonic mean of precision and recall.
>
> # 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:
> # Evaluate the decision tree model against the
> # training and test sets.
>
[1] "############################### end 165 Fri Jun 17 10:42:20 2016"
[1] "############################### start 167 Fri Jun 17 10:42:20 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00167_example_9.2_of_section_9.1.1.R"
[1] "##### in directory ../Spambase"
> # example 9.2 of section 9.1.1
> # (example 9.2 of section 9.1.1) : Exploring advanced methods : Using bagging and random forests to reduce training variance : 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=T)})
> treelist <-lapply(1:ntree, # Note: 3
FUN=function(iter)
{samp <- samples[,iter];
rpart(spamFormula, spamTrain[samp,])})
> predict.bag <- function(treelist, newdata) { # Note: 4
preds <- sapply(1:length(treelist),
FUN=function(iter) {
predict(treelist[[iter]], newdata=newdata)})
predsums <- rowSums(preds)
predsums/length(treelist)
}
> accuracyMeasures(predict.bag(treelist, newdata=spamTrain), # Note: 5
spamTrain$spam=="spam",
name="bagging, training")
model accuracy f1 dev.norm
1 bagging, training 0.9215544 0.8973144 0.4719576
> accuracyMeasures(predict.bag(treelist, newdata=spamTest),
spamTest$spam=="spam",
name="bagging, test")
model accuracy f1 dev.norm
1 bagging, test 0.9061135 0.8731563 0.5325537
> # 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.
>
> # Note 5:
> # Evaluate the bagged decision trees against the
> # training and test sets.
>
[1] "############################### end 167 Fri Jun 17 10:43:03 2016"
[1] "############################### start 169 Fri Jun 17 10:43:03 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00169_example_9.3_of_section_9.1.2.R"
[1] "##### in directory ../Spambase"
> # example 9.3 of section 9.1.2
> # (example 9.3 of section 9.1.2) : Exploring advanced methods : Using bagging and random forests to reduce training variance : Using random forests to further improve prediction
> # Title: Using random forests
>
> library(randomForest) # Note: 1
randomForest 4.6-12
Type rfNews() to see new features/changes/bug fixes.
Attaching package: 'randomForest'
The following object is masked from 'package:ggplot2':
margin
> set.seed(5123512) # Note: 2
> fmodel <- randomForest(x=spamTrain[,spamVars], # Note: 3
y=spamTrain$spam,
ntree=100, # Note: 4
nodesize=7, # Note: 5
importance=T) # Note: 6
> accuracyMeasures(predict(fmodel, # Note: 7
newdata=spamTrain[,spamVars],type='prob')[,'spam'],
spamTrain$spam=="spam",name="random forest, train")
model accuracy f1 dev.norm
1 random forest, train 0.9884142 0.9851943 0.1428786
> ## model accuracy f1 dev.norm
> ## 1 random forest, train 0.9884142 0.9706611 0.1428786
> accuracyMeasures(predict(fmodel,
newdata=spamTest[,spamVars],type='prob')[,'spam'],
spamTest$spam=="spam",name="random forest, test")
model accuracy f1 dev.norm
1 random forest, test 0.9541485 0.9401709 0.3972416
> ## model accuracy f1 dev.norm
> ## 1 random forest, test 0.9541485 0.8845029 0.3972416
>
> # Note 1:
> # Load the randomForest package.
>
> # Note 2:
> # Set the pseudo-random seed to a known value to try
> # and 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.
>
[1] "############################### end 169 Fri Jun 17 10:43:08 2016"
[1] "############################### start 171 Fri Jun 17 10:43:08 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00171_example_9.4_of_section_9.1.2.R"
[1] "##### in directory ../Spambase"
> # example 9.4 of section 9.1.2
> # (example 9.4 of section 9.1.2) : Exploring advanced methods : Using bagging and random forests to reduce training variance : 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 2.096811 3.7304353 4.334207
word.freq.address 3.603167 3.9967031 4.977452
word.freq.all 2.799456 4.9527834 4.924958
word.freq.3d 3.000273 0.4125932 2.917972
word.freq.our 9.037946 7.9421391 10.731509
word.freq.over 5.879377 4.2402613 5.751371
word.freq.remove 16.637390 13.9331691 17.753122
word.freq.internet 7.301055 4.4458342 7.947515
word.freq.order 3.937897 4.3587883 4.866540
word.freq.mail 5.022432 3.4701224 6.103929
MeanDecreaseGini
word.freq.make 5.877954
word.freq.address 10.081640
word.freq.all 23.524720
word.freq.3d 1.550635
word.freq.our 52.569163
word.freq.over 11.820391
word.freq.remove 174.126926
word.freq.internet 22.578106
word.freq.order 11.809265
word.freq.mail 11.127200
> ## non-spam spam MeanDecreaseAccuracy
> ## word.freq.make 2.096811 3.7304353 4.334207
> ## word.freq.address 3.603167 3.9967031 4.977452
> ## word.freq.all 2.799456 4.9527834 4.924958
> ## word.freq.3d 3.000273 0.4125932 2.917972
> ## word.freq.our 9.037946 7.9421391 10.731509
> ## word.freq.over 5.879377 4.2402613 5.751371
> ## word.freq.remove 16.637390 13.9331691 17.753122
> ## word.freq.internet 7.301055 4.4458342 7.947515
> ## word.freq.order 3.937897 4.3587883 4.866540
> ## word.freq.mail 5.022432 3.4701224 6.103929
>
> 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.
>
[1] "############################### end 171 Fri Jun 17 10:43:08 2016"
[1] "############################### start 172 Fri Jun 17 10:43:08 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00172_example_9.5_of_section_9.1.2.R"
[1] "##### in directory ../Spambase"
> # example 9.5 of section 9.1.2
> # (example 9.5 of section 9.1.2) : Exploring advanced methods : Using bagging and random forests to reduce training variance : Using random forests to further improve prediction
> # Title: Fitting with fewer variables
>
> selVars <- names(sort(varImp[,1], decreasing=T))[1:25] # Note: 1
> fsel <- randomForest(x=spamTrain[,selVars],y=spamTrain$spam, # Note: 2
ntree=100,
nodesize=7,
importance=T)
> accuracyMeasures(predict(fsel,
newdata=spamTrain[,selVars],type='prob')[,'spam'],
spamTrain$spam=="spam",name="RF small, train")
model accuracy f1 dev.norm
1 RF small, train 0.9864832 0.9827267 0.1379438
> ## model accuracy f1 dev.norm
> ## 1 RF small, train 0.9876901 0.9688546 0.1506817
>
> accuracyMeasures(predict(fsel,
newdata=spamTest[,selVars],type='prob')[,'spam'],
spamTest$spam=="spam",name="RF small, test")
model accuracy f1 dev.norm
1 RF small, test 0.9497817 0.9348442 0.3985712
> ## model accuracy f1 dev.norm
> ## 1 RF small, test 0.9497817 0.8738142 0.400825
>
> # Note 1:
> # Sort the variables by their importance, as
> # measured by accuracy change.
>
> # Note 2:
> # Build a random forest model using only the 25
> # most important variables.
>
[1] "############################### end 172 Fri Jun 17 10:43:11 2016"
[1] "############################### start 175 Fri Jun 17 10:43:11 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00175_example_9.6_of_section_9.2.2.R"
[1] "##### in directory ../Spambase"
> # example 9.6 of section 9.2.2
> # (example 9.6 of section 9.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,]
[1] "############################### end 175 Fri Jun 17 10:43:11 2016"
[1] "############################### start 176 Fri Jun 17 10:43:11 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00176_example_9.7_of_section_9.2.2.R"
[1] "##### in directory ../Spambase"
> # example 9.7 of section 9.2.2
> # (example 9.7 of section 9.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 our 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
> ## 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
>
> #
> # calculate the root mean squared error (rmse)
> #
> resid.lin <- train$y-predict(lin.model)
> sqrt(mean(resid.lin^2))
[1] 3.481091
> ## [1] 3.481091
>
[1] "############################### end 176 Fri Jun 17 10:43:11 2016"
[1] "############################### start 177 Fri Jun 17 10:43:11 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00177_example_9.8_of_section_9.2.2.R"
[1] "##### in directory ../Spambase"
> # example 9.8 of section 9.2.2
> # (example 9.8 of section 9.2.2) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : A one-dimensional regression example
> # Title: GAM applied to our artificial example
>
> library(mgcv) # Note: 1
Loading required package: nlme
This is mgcv 1.8-12. For overview type 'help("mgcv-package")'.</code></pre>
<div class="figure">
<img src="rCh09_files/figure-markdown_github/ch9ex1-1.png" alt="" />
</div>
<pre><code>> glin.model <- gam(y~s(x), data=train) # Note: 2
> glin.model$converged # Note: 3
[1] TRUE
> ## [1] TRUE
>
> summary(glin.model)
Family: gaussian
Link function: identity
Formula:
y ~ s(x)
Parametric coefficients:
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:
edf Ref.df F p-value
s(x) 8.685 8.972 497.4 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
R-sq.(adj) = 0.832 Deviance explained = 83.4%
GCV = 2.144 Scale est. = 2.121 n = 901
> ## 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
>
> #
> # calculate the root mean squared error (rmse)
> #
> resid.glin <- train$y-predict(glin.model)
> sqrt(mean(resid.glin^2))
[1] 1.448514
> ## [1] 1.448514
>
> # Note 1:
> # Load the mgcv package.
>
> # Note 2:
> # Build the model, specifying that x should be
> # treated as a nonlinear variable.
>
> # Note 3:
> # The converged parameter tells you if the algorithm
> # converged. You should only trust the output if this is TRUE.
>
> # Note 4:
> # Setting family=gaussian and link=identity tells you that the model was treated with the same
> # distributions assumptions as a standard linear regression.
>
> # Note 5:
> # The parametric coefficients are the linear terms (in this example, only the constant term).
> # This section of the summary tells you which linear terms were
> # significantly different from 0.
>
> # Note 6:
> # The smooth terms are the nonlinear terms. This section of the summary tells you which
> # nonlinear terms were significantly different from 0. It also tells you
> # the effective degrees of freedom (edf) used up to build each smooth
> # term. An edf near 1 indicates that the variable has an approximately
> # linear relationship to the output.
>
> # Note 7:
> # “R-sq (adj)” is the adjusted R-squared. “Deviance
> # explained” is the raw R-squared (0.834).
>
[1] "############################### end 177 Fri Jun 17 10:43:12 2016"
[1] "############################### start 178 Fri Jun 17 10:43:12 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00178_example_9.9_of_section_9.2.2.R"
[1] "##### in directory ../Spambase"
> # example 9.9 of section 9.2.2
> # (example 9.9 of section 9.2.2) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : A one-dimensional regression example
> # Title: Comparing linear regression and GAM performance
>
> actual <- test$y
> pred.lin <- predict(lin.model, newdata=test) # Note: 1
> pred.glin <- predict(glin.model, newdata=test)
> resid.lin <- actual-pred.lin
> resid.glin <- actual-pred.glin
> sqrt(mean(resid.lin^2)) # Note: 2
[1] 2.792653
> ## [1] 2.792653
> sqrt(mean(resid.glin^2))
[1] 1.401399
> ## [1] 1.401399
>
> cor(actual, pred.lin)^2 # Note: 3
[1] 0.1543172
> ## [1] 0.1543172
> cor(actual, pred.glin)^2
[1] 0.7828869
> ## [1] 0.7828869
>
> # Note 1:
> # Call both models on the test
> # data.
>
> # Note 2:
> # Compare the RMSE of the linear model and the GAM
> # on the test data.
>
> # Note 3:
> # Compare the R-squared of the linear model and the
> # GAM on test data.
>
[1] "############################### end 178 Fri Jun 17 10:43:12 2016"
[1] "############################### start 179 Fri Jun 17 10:43:12 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00179_example_9.10_of_section_9.2.3.R"
[1] "##### in directory ../Spambase"
> # example 9.10 of section 9.2.3
> # (example 9.10 of section 9.2.3) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Extracting the nonlinear relationships
> # Title: Extracting a learned spline from a GAM
>
> sx <- predict(glin.model, type="terms")
> summary(sx)
s(x)
Min. :-17.527035
1st Qu.: -2.378636
Median : 0.009427
Mean : 0.000000
3rd Qu.: 2.869166
Max. : 4.084999
> ## s(x)
> ## Min. :-17.527035
> ## 1st Qu.: -2.378636
> ## Median : 0.009427
> ## Mean : 0.000000
> ## 3rd Qu.: 2.869166
> ## Max. : 4.084999
>
> xframe <- cbind(train, sx=sx[,1])
> ggplot(xframe, aes(x=x)) + geom_point(aes(y=y), alpha=0.4) +
geom_line(aes(y=sx))</code></pre>
<div class="figure">
<img src="rCh09_files/figure-markdown_github/ch9ex1-2.png" alt="" />
</div>
<pre><code>[1] "############################### end 179 Fri Jun 17 10:43:12 2016"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>())
<span class="kw">source</span>(<span class="st">'runDir.R'</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(<span class="st">'ggplot2'</span>)
<span class="kw">runDir</span>(<span class="st">'../CodeExamples/c09_Exploring_advanced_methods'</span>,
<span class="st">'../CDC'</span>,<span class="dt">first=</span><span class="dv">180</span>,<span class="dt">last=</span><span class="dv">184</span>)</code></pre></div>
<pre><code>[1] "############################### start 180 Fri Jun 17 10:43:12 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00180_example_9.11_of_section_9.2.4.R"
[1] "##### in directory ../CDC"
> # example 9.11 of section 9.2.4
> # (example 9.11 of section 9.2.4) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Using GAM on actual data
> # Title: Applying linear regression (with and without GAM) to health data
>
> library(mgcv)
> library(ggplot2)
> load("NatalBirthData.rData")
> train <- sdata[sdata$ORIGRANDGROUP<=5,]
> test <- sdata[sdata$ORIGRANDGROUP>5,]
> form.lin <- as.formula("DBWT ~ PWGT + WTGAIN + MAGER + UPREVIS")
> linmodel <- lm(form.lin, data=train) # Note: 1
> summary(linmodel)
Call:
lm(formula = form.lin, data = train)
Residuals:
Min 1Q Median 3Q Max
-3155.43 -272.09 45.04 349.81 2870.55
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2419.7090 31.9291 75.784 < 2e-16 ***
PWGT 2.1713 0.1241 17.494 < 2e-16 ***
WTGAIN 7.5773 0.3178 23.840 < 2e-16 ***
MAGER 5.3213 0.7787 6.834 8.6e-12 ***
UPREVIS 12.8753 1.1786 10.924 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 562.7 on 14381 degrees of freedom
Multiple R-squared: 0.06596, Adjusted R-squared: 0.0657
F-statistic: 253.9 on 4 and 14381 DF, p-value: < 2.2e-16
> ## Call:
> ## lm(formula = form.lin, data = train)
> ##
> ## Residuals:
> ## Min 1Q Median 3Q Max
> ## -3155.43 -272.09 45.04 349.81 2870.55
> ##
> ## Coefficients:
> ## Estimate Std. Error t value Pr(>|t|)
> ## (Intercept) 2419.7090 31.9291 75.784 < 2e-16 ***
> ## PWGT 2.1713 0.1241 17.494 < 2e-16 ***
> ## WTGAIN 7.5773 0.3178 23.840 < 2e-16 ***
> ## MAGER 5.3213 0.7787 6.834 8.6e-12 ***
> ## UPREVIS 12.8753 1.1786 10.924 < 2e-16 ***
> ## ---
> ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> ##
> ## Residual standard error: 562.7 on 14381 degrees of freedom
> ## Multiple R-squared: 0.06596, Adjusted R-squared: 0.0657 # Note: 2
> ## F-statistic: 253.9 on 4 and 14381 DF, p-value: < 2.2e-16
>
> form.glin <- as.formula("DBWT ~ s(PWGT) + s(WTGAIN) +
s(MAGER) + s(UPREVIS)")
> glinmodel <- gam(form.glin, data=train) # Note: 3
> glinmodel$converged # Note: 4
[1] TRUE
> ## [1] TRUE
> summary(glinmodel)
Family: gaussian
Link function: identity
Formula:
DBWT ~ s(PWGT) + s(WTGAIN) + s(MAGER) + s(UPREVIS)
Parametric coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3276.948 4.623 708.8 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Approximate significance of smooth terms:
edf Ref.df F p-value
s(PWGT) 5.374 6.443 69.010 < 2e-16 ***
s(WTGAIN) 4.719 5.743 102.313 < 2e-16 ***
s(MAGER) 7.742 8.428 7.145 1.37e-09 ***
s(UPREVIS) 5.491 6.425 48.423 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
R-sq.(adj) = 0.0927 Deviance explained = 9.42%
GCV = 3.0804e+05 Scale est. = 3.0752e+05 n = 14386
> ## Family: gaussian
> ## Link function: identity
> ##
> ## Formula:
> ## DBWT ~ s(PWGT) + s(WTGAIN) + s(MAGER) + s(UPREVIS)
> ##
> ## Parametric coefficients:
> ## Estimate Std. Error t value Pr(>|t|)
> ## (Intercept) 3276.948 4.623 708.8 <2e-16 ***
> ## ---
> ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> ##
> ## Approximate significance of smooth terms:
> ## edf Ref.df F p-value
> ## s(PWGT) 5.374 6.443 68.981 < 2e-16 ***
> ## s(WTGAIN) 4.719 5.743 102.313 < 2e-16 ***
> ## s(MAGER) 7.742 8.428 6.959 1.82e-09 ***
> ## s(UPREVIS) 5.491 6.425 48.423 < 2e-16 ***
> ## ---
> ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> ##
> ## R-sq.(adj) = 0.0927 Deviance explained = 9.42% # Note: 5
> ## GCV score = 3.0804e+05 Scale est. = 3.0752e+05 n = 14386
>
> # Note 1:
> # Build a linear model with four
> # variables.
>
> # Note 2:
> # The model explains about 7% of the variance; all
> # coefficients are significantly different from 0.
>
> # Note 3:
> # Build a GAM with the same
> # variables.
>
> # Note 4:
> # Verify that the model has
> # converged.
>
> # Note 5:
> # The model explains just under 10% of the variance;
> # all variables have a nonlinear effect significantly different from
> # 0.
>
[1] "############################### end 180 Fri Jun 17 10:43:13 2016"
[1] "############################### start 181 Fri Jun 17 10:43:13 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00181_example_9.12_of_section_9.2.4.R"
[1] "##### in directory ../CDC"
> # example 9.12 of section 9.2.4
> # (example 9.12 of section 9.2.4) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Using GAM on actual data
> # Title: Plotting GAM results
>
> terms <- predict(glinmodel, type="terms") # Note: 1
> tframe <- cbind(DBWT = train$DBWT, as.data.frame(terms)) # Note: 2
> colnames(tframe) <- gsub('[()]', '', colnames(tframe)) # Note: 3
> pframe <- cbind(tframe, train[,c("PWGT", "WTGAIN",
"MAGER", "UPREVIS")]) # Note: 4
> p1 <- ggplot(pframe, aes(x=PWGT)) +
geom_point(aes(y=scale(sPWGT, scale=F))) + # Note: 5
geom_smooth(aes(y=scale(DBWT, scale=F))) # + # Note: 6
> # [...] # Note: 7
>
> # Note 1:
> # Get the matrix of s()
> # functions.
>
> # Note 2:
> # Bind in birth weight; convert to data
> # frame.
>
> # Note 3:
> # Make the column names reference-friendly
> # (“s(PWGT)” is converted to “sPWGT”, etc.).
>
> # Note 4:
> # Bind in the input variables.
>
> # Note 5:
> # Plot s(PWGT) shifted to be zero mean versus PWGT (mother’s weight) as points.
>
> # Note 6:
> # Plot the smoothing curve of DWBT (birth weight) shifted to be zero mean versus PWGT (mother’s
> # weight).
>
> # Note 7:
> # Repeat for remaining variables (omitted for
> # brevity).
>
[1] "############################### end 181 Fri Jun 17 10:43:13 2016"
[1] "############################### start 182 Fri Jun 17 10:43:13 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00182_example_9.13_of_section_9.2.4.R"
[1] "##### in directory ../CDC"
> # example 9.13 of section 9.2.4
> # (example 9.13 of section 9.2.4) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Using GAM on actual data
> # Title: Checking GAM model performance on hold-out data
>
> pred.lin <- predict(linmodel, newdata=test) # Note: 1
> pred.glin <- predict(glinmodel, newdata=test)
> cor(pred.lin, test$DBWT)^2 # Note: 2
[1] 0.0616812
> # [1] 0.0616812
> cor(pred.glin, test$DBWT)^2
[1] 0.08857426
> # [1] 0.08857426
>
> # Note 1:
> # Run both the linear model and the GAM on the test
> # data.
>
> # Note 2:
> # Calculate R-squared for both
> # models.
>
[1] "############################### end 182 Fri Jun 17 10:43:13 2016"
[1] "############################### start 183 Fri Jun 17 10:43:13 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00183_example_9.14_of_section_9.2.5.R"
[1] "##### in directory ../CDC"
> # example 9.14 of section 9.2.5
> # (example 9.14 of section 9.2.5) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Using GAM for logistic regression
> # Title: GLM logistic regression
>
> form <- as.formula("DBWT < 2000 ~ PWGT + WTGAIN + MAGER + UPREVIS")
> logmod <- glm(form, data=train, family=binomial(link="logit"))
[1] "############################### end 183 Fri Jun 17 10:43:14 2016"
[1] "############################### start 184 Fri Jun 17 10:43:14 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00184_example_9.15_of_section_9.2.5.R"
[1] "##### in directory ../CDC"
> # example 9.15 of section 9.2.5
> # (example 9.15 of section 9.2.5) : Exploring advanced methods : Using generalized additive models (GAMs) to learn non-monotone relationships : Using GAM for logistic regression
> # Title: GAM logistic regression
>
> form2 <- as.formula("DBWT<2000~s(PWGT)+s(WTGAIN)+
s(MAGER)+s(UPREVIS)")
> glogmod <- gam(form2, data=train, family=binomial(link="logit"))
> glogmod$converged
[1] TRUE
> ## [1] TRUE
>
> summary(glogmod)
Family: binomial
Link function: logit
Formula:
DBWT < 2000 ~ s(PWGT) + s(WTGAIN) + s(MAGER) + s(UPREVIS)
Parametric coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.94085 0.06794 -58 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Approximate significance of smooth terms:
edf Ref.df Chi.sq p-value
s(PWGT) 1.905 2.420 2.463 0.39023
s(WTGAIN) 3.674 4.543 64.211 1.81e-12 ***
s(MAGER) 1.003 1.005 8.347 0.00393 **
s(UPREVIS) 6.802 7.216 217.631 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
R-sq.(adj) = 0.0331 Deviance explained = 9.14%
UBRE = -0.76987 Scale est. = 1 n = 14386
> ## Family: binomial
> ## Link function: logit
> ##
> ## Formula:
> ## DBWT < 2000 ~ s(PWGT) + s(WTGAIN) + s(MAGER) + s(UPREVIS)
> ##
> ## Parametric coefficients:
> ## Estimate Std. Error z value Pr(>|z|)
> ## (Intercept) -3.94085 0.06794 -58 <2e-16 ***
> ## ---
> ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> ##
> ## Approximate significance of smooth terms:
> ## edf Ref.df Chi.sq p-value
> ## s(PWGT) 1.905 2.420 2.463 0.36412 # Note: 1
> ## s(WTGAIN) 3.674 4.543 64.426 1.72e-12 ***
> ## s(MAGER) 1.003 1.005 8.335 0.00394 **
> ## s(UPREVIS) 6.802 7.216 217.631 < 2e-16 ***
> ## ---
> ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> ##
> ## R-sq.(adj) = 0.0331 Deviance explained = 9.14% # Note: 2
> ## UBRE score = -0.76987 Scale est. = 1 n = 14386
>
> # Note 1:
> # Note that there’s no proof that the mother’s weight (PWGT) has a significant effect on
> # outcome.
>
> # Note 2:
> # “Deviance explained” is the pseudo R-squared: 1 -
> # (deviance/null.deviance).
>
[1] "############################### end 184 Fri Jun 17 10:43:17 2016"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>())
<span class="kw">source</span>(<span class="st">'runDir.R'</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(<span class="st">'ggplot2'</span>)
<span class="kw">load</span>(<span class="st">'../PUMS/psub.RData'</span>)
<span class="kw">runDir</span>(<span class="st">'../CodeExamples/c09_Exploring_advanced_methods'</span>,
<span class="st">'../PUMS'</span>,<span class="dt">first=</span><span class="dv">185</span>,<span class="dt">last=</span><span class="dv">195</span>)</code></pre></div>
<pre><code>[1] "############################### start 185 Fri Jun 17 10:43:17 2016"
[1] "##### running ../CodeExamples/c09_Exploring_advanced_methods/00185_example_9.16_of_section_9.3.1.R"
[1] "##### in directory ../PUMS"
> # example 9.16 of section 9.3.1
> # (example 9.16 of section 9.3.1) : Exploring advanced methods : Using kernel methods to increase data separation : Understanding kernel functions
> # Title: An artificial kernel example
>
> u <- c(1,2)
> v <- c(3,4)
> k <- function(u,v) { # Note: 1
u[1]*v[1] + u[2]*v[2] +
u[1]*u[1]*v[1]*v[1] + u[2]*u[2]*v[2]*v[2] +
u[1]*u[2]*v[1]*v[2]
}
> phi <- function(x) { # Note: 2
x <- as.numeric(x)
c(x,x*x,combn(x,2,FUN=prod))
}
> print(k(u,v)) # Note: 3
[1] 108
> ## [1] 108
> print(phi(u))
[1] 1 2 1 4 2
> ## [1] 1 2 1 4 2
> print(phi(v))
[1] 3 4 9 16 12
> ## [1] 3 4 9 16 12
> print(as.numeric(phi(u) %*% phi(v))) # Note: 4
[1] 108
> ## [1] 108
>
> # Note 1:
> # Define a function of two vector variables
> # (both two dimensional) as the sum of various products of terms.
>
> # Note 2:
> # Define a function of a single vector variable
> # that returns a vector containing the original entries plus all products of
> # entries.
>
> # Note 3:
> # Example evaluation of k(,).
>
> # Note 4:
> # Confirm phi() agrees with k(,). phi() is the certificate that shows k(,) is in fact a