/
Part-5-Regression-Models.html
2005 lines (1338 loc) · 62.4 KB
/
Part-5-Regression-Models.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<title>Applied Machine Learning - Regression Models</title>
<meta charset="utf-8" />
<meta name="author" content="Max Kuhn (RStudio)" />
<script src="libs/htmlwidgets-1.5.1/htmlwidgets.js"></script>
<script src="libs/jquery-1.12.4/jquery.min.js"></script>
<link href="libs/leaflet-1.3.1/leaflet.css" rel="stylesheet" />
<script src="libs/leaflet-1.3.1/leaflet.js"></script>
<link href="libs/leafletfix-1.0.0/leafletfix.css" rel="stylesheet" />
<script src="libs/Proj4Leaflet-1.0.1/proj4-compressed.js"></script>
<script src="libs/Proj4Leaflet-1.0.1/proj4leaflet.js"></script>
<link href="libs/rstudio_leaflet-1.3.1/rstudio_leaflet.css" rel="stylesheet" />
<script src="libs/leaflet-binding-2.0.2/leaflet.js"></script>
<link href="libs/countdown-0.3.3/countdown.css" rel="stylesheet" />
<script src="libs/countdown-0.3.3/countdown.js"></script>
<script src="libs/kePrint-0.0.1/kePrint.js"></script>
<link rel="stylesheet" href="mtheme_max.css" type="text/css" />
<link rel="stylesheet" href="fonts_mtheme_max.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Applied Machine Learning - Regression Models
### Max Kuhn (RStudio)
---
# Loading
.font70[
```r
library(tidymodels)
```
```
## Registered S3 method overwritten by 'xts':
## method from
## as.zoo.xts zoo
```
```
## ── Attaching packages ───────────────────────────────────────── tidymodels 0.0.2 ──
```
```
## ✔ broom 0.5.1 ✔ purrr 0.3.3
## ✔ dials 0.0.3.9002 ✔ recipes 0.1.7.9001
## ✔ dplyr 0.8.3 ✔ rsample 0.0.5
## ✔ ggplot2 3.2.1 ✔ tibble 2.1.3
## ✔ infer 0.4.0 ✔ yardstick 0.0.4
## ✔ parsnip 0.0.4
```
```
## ── Conflicts ──────────────────────────────────────────── tidymodels_conflicts() ──
## ✖ dplyr::combine() masks gridExtra::combine()
## ✖ purrr::discard() masks scales::discard()
## ✖ dplyr::filter() masks stats::filter()
## ✖ recipes::fixed() masks stringr::fixed()
## ✖ dplyr::group_rows() masks kableExtra::group_rows()
## ✖ dplyr::lag() masks stats::lag()
## ✖ ggplot2::margin() masks dials::margin()
## ✖ dials::offset() masks stats::offset()
## ✖ recipes::step() masks stats::step()
```
```r
library(tune)
```
]
---
# Outline
* Example Data
* Regularized Linear Models
* Multivariate Adaptive Regression Splines
* Parallel Processing
* Bayesian Optimization
---
# Example Data: Train Ridership
These data are used in our [Feature Engineering and Selection](https://bookdown.org/max/FES/chicago-intro.html) book.
Several years worth of data were assembled to try to predict the daily number of people entering the Clark and Lake elevated ("L") train station in Chicago.
For predictors,
* the 14-day lagged ridership at this and other stations (units: thousands of rides/day)
* weather data
* home/away game schedules for Chicago teams
* the date
The data are in `dials`. See `?Chicago`.
---
# L Train Locations
<div id="htmlwidget-972050f33c54948a3258" style="width:100%;height:504px;" class="leaflet html-widget"></div>
<script type="application/json" data-for="htmlwidget-972050f33c54948a3258">{"x":{"options":{"crs":{"crsClass":"L.CRS.EPSG3857","code":null,"proj4def":null,"projectedBounds":null,"options":{}}},"calls":[{"method":"addTiles","args":["//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",null,null,{"minZoom":0,"maxZoom":18,"tileSize":256,"subdomains":"abc","errorTileUrl":"","tms":false,"noWrap":false,"zoomOffset":0,"zoomReverse":false,"opacity":1,"zIndex":1,"detectRetina":false,"attribution":"© <a href=\"http://openstreetmap.org\">OpenStreetMap<\/a> contributors, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA<\/a>"}]},{"method":"addCircleMarkers","args":[[41.870851,41.886848,41.885412,41.878723,42.04771,41.938132,41.878183,41.953775,41.966286,42.008362,41.829353,41.80209,42.038951,41.853732,41.8768,41.885269,41.872108,41.831191,41.884431,41.854517,41.875478,41.984246,41.750419,41.874341,41.88574,42.033456,41.887389,41.77886,41.821732,41.804546,41.903355,41.891665,41.977984,41.875474,41.943744,41.883164,41.874257,42.058282,41.85182,41.875539,41.854109,41.722377,41.888969,41.87592,41.886519,41.891189,41.8837,41.795172,42.05416,41.932732,41.964273,41.952925,41.878153,41.921939,41.85177331,41.909744,41.853751,41.887159,41.90392,41.882023,41.910655,41.918217,41.916157,41.879507,42.041655,41.887163,41.89681,41.780309,41.882695,41.854225,41.98227,41.993664,41.969139,41.853839,41.880703,41.910409,41.875706,41.983507,41.857908,42.027612,41.876862,41.966046,41.990259,41.97766526,42.019063,41.780536,41.873797,41.78661,41.778943,41.799756,41.871574,41.87349,41.768367,41.853206,41.966115,41.929728,41.871551,41.853964,42.073153,41.839234,41.884321,41.809209,41.880745,41.831677,41.84678,41.78013,41.804236,41.885678,41.79542,41.965996,42.015876,41.973453,41.936033,41.925051,41.810318,41.94738,42.063987,41.887293,41.816462,41.970634,41.967901,42.001073,41.943623,41.939751,41.961539,41.875568,41.886988,41.88422,41.983504,41.867405,41.896075,41.947428,41.735372,41.947028,41.896671,41.954521,41.966163,41.874039,41.961756,41.885586,41.884914,41.884809,41.884904,42.02624348,41.853115,41.88322],[-87.776812,-87.803176,-87.725404,-87.63374,-87.683543,-87.712359,-87.629296,-87.654929,-87.678639,-87.665909,-87.680622,-87.618487,-87.751919,-87.724311,-87.631739,-87.666969,-87.791602,-87.630636,-87.626149,-87.675975,-87.688436,-87.838028,-87.625112,-87.70604,-87.627835,-87.679538,-87.76565,-87.663766,-87.621371,-87.684019,-87.666496,-87.628021,-87.658668,-87.649707,-87.663619,-87.62944,-87.817318,-87.683337,-87.745336,-87.640984,-87.694774,-87.624342,-87.633924,-87.659458,-87.744698,-87.647578,-87.6278,-87.618327,-87.68356,-87.653131,-87.657588,-87.729229,-87.627596,-87.69689,-87.75669201,-87.677437,-87.733258,-87.783661,-87.631412,-87.626098,-87.649177,-87.652644,-87.687364,-87.626037,-87.681602,-87.754986,-87.635924,-87.605857,-87.63378,-87.685129,-87.8089,-87.659202,-87.658493,-87.714842,-87.629378,-87.639302,-87.673932,-87.859388,-87.669147,-87.678329,-87.628196,-87.701644,-87.659076,-87.90422307,-87.672892,-87.630952,-87.725663,-87.737875,-87.644244,-87.724493,-87.745154,-87.806961,-87.625724,-87.630968,-87.6941,-87.708541,-87.66953,-87.705408,-87.69073,-87.665317,-87.706155,-87.618826,-87.627696,-87.625826,-87.648088,-87.615546,-87.704406,-87.641782,-87.631157,-87.708821,-87.669092,-87.65853,-87.653266,-87.652866,-87.63094,-87.71906,-87.685617,-87.774135,-87.619021,-87.760892,-87.713065,-87.661061,-87.670907,-87.65338,-87.743574,-87.631722,-87.793783,-87.696234,-87.65884,-87.62659,-87.655214,-87.653626,-87.624717,-87.674642,-87.628176,-87.674868,-87.688502,-87.627479,-87.675047,-87.652193,-87.711327,-87.627813,-87.716523,-87.74722084,-87.626402,-87.626189],3,null,null,{"interactive":true,"className":"","stroke":true,"color":"red","weight":5,"opacity":0.5,"fill":true,"fillColor":"red","fillOpacity":0.2},null,null,["Austin (Blue Line)","Harlem/Lake (Green Line)","Pulaski (Green Line)","Quincy/Wells (Brown, Orange, Purple & Pink Lines)","Davis (Purple Line)","Belmont (Blue Line)","Jackson (Blue Line)","Sheridan (Red Line)","Damen (Brown Line)","Morse (Red Line)","35th/Archer (Orange Line)","51st (Green Line)","Dempster-Skokie (Yellow Line)","Pulaski (Pink Line)","LaSalle/Van Buren (Brown, Orange, Purple & Pink Lines)","Ashland (Green & Pink Lines)","Oak Park (Blue Line)","Sox-35th (Red Line)","Randolph/Wabash (Brown, Green, Orange, Pink & Purple Lines)","Damen (Pink Line)","Western (Blue Line - Forest Park Branch)","Cumberland (Blue Line)","79th (Red Line)","Kedzie-Homan (Blue Line)","State/Lake (Brown, Green, Orange, Pink & Purple Lines)","Main (Purple Line)","Central (Green Line)","Ashland/63rd (Green Line)","Indiana (Green Line)","Western (Orange Line)","Division (Blue Line)","Grand (Red Line)","Berwyn (Red Line)","UIC-Halsted (Blue Line)","Southport (Brown Line)","Washington (Blue Line)","Forest Park (Blue Line)","Noyes (Purple Line)","Cicero (Pink Line)","Clinton (Blue Line)","California (Pink Line)","95th/Dan Ryan (Red Line)","Merchandise Mart (Brown & Purple Lines)","Racine (Blue Line)","Cicero (Green Line)","Grand (Blue Line)","Washington (Red Line)","Garfield (Green Line)","Foster (Purple Line)","Diversey (Brown & Purple Lines)","Wilson (Red & Purple Lines)","Irving Park (Blue Line)","Jackson (Red Line)","California (Blue Line)","54th/Cermak (Pink Line)","Damen (Blue Line)","Kostner (Pink Line)","Ridgeland (Green Line)","Clark/Division (Red Line)","Madison/Wabash (Brown, Green, Orange, Pink & Purple Lines)","North/Clybourn (Red Line)","Armitage (Brown & Purple Lines)","Western (Blue Line - O'Hare Branch)","Adams/Wabash (Brown, Green, Orange, Pink & Purple Lines)","Dempster (Purple Line)","Laramie (Green Line)","Chicago (Brown & Purple Lines)","Cottage Grove (Green Line)","Washington/Wells (Brown, Orange, Purple & Pink Lines)","Western (Pink Line)","Harlem (Blue Line - O'Hare Branch)","Granville (Red Line)","Lawrence (Red Line)","Central Park (Pink Line)","Monroe (Blue Line)","Sedgwick (Brown & Purple Lines)","Illinois Medical District (Blue Line)","Rosemont (Blue Line)","18th (Pink Line)","South Boulevard (Purple Line)","Harold Washington Library-State/Van Buren (Brown, Orange, Purple & Pink Lines)","Francisco (Brown Line)","Thorndale (Red Line)","O'Hare (Blue Line)","Howard (Red, Purple & Yellow Lines)","63rd (Red Line)","Pulaski (Blue Line)","Midway (Orange Line)","Halsted (Green Line)","Pulaski (Orange Line)","Cicero (Blue Line)","Harlem (Blue Line - Forest Park Branch)","69th (Red Line)","Cermak-Chinatown (Red Line)","Rockwell (Brown Line)","Logan Square (Blue Line)","Polk (Pink Line)","Kedzie (Pink Line)","Linden (Purple Line)","Ashland (Orange Line)","Kedzie (Green Line)","47th (Green Line)","Monroe (Red Line)","35th-Bronzeville-IIT (Green Line)","Halsted (Orange Line)","King Drive (Green Line)","Kedzie (Orange Line)","Clinton (Green & Pink Lines)","Garfield (Red Line)","Kedzie (Brown Line)","Jarvis (Red Line)","Argyle (Red Line)","Wellington (Brown & Purple Lines)","Fullerton (Red, Brown & Purple Lines)","47th (Red Line)","Addison (Blue Line)","Central (Purple Line)","Austin (Green Line)","43rd (Green Line)","Jefferson Park (Blue Line)","Kimball (Brown Line)","Loyola (Red Line)","Paulina (Brown Line)","Belmont (Red, Brown & Purple Lines)","Montrose (Blue Line)","LaSalle (Blue Line)","Oak Park (Green Line)","California (Green Line)","Bryn Mawr (Red Line)","Roosevelt (Red, Orange & Green Lines)","Chicago (Blue Line)","Addison (Red Line)","87th (Red Line)","Addison (Brown Line)","Chicago (Red Line)","Irving Park (Brown Line)","Western (Brown Line)","Harrison (Red Line)","Montrose (Brown Line)","Morgan (Green & Pink Lines)","Homan (Green Line)","Lake (Red Line)","Conservatory (Green Line)","Oakton-Skokie (Yellow Line)","Cermak-McCormick Place (Green Line)","Washington/Wabash (Brown, Green, Orange, Purple & Pink Lines)"],null,null,{"interactive":false,"permanent":false,"direction":"auto","opacity":1,"offset":[0,0],"textsize":"10px","textOnly":false,"className":"","sticky":true},null]},{"method":"addCircleMarkers","args":[41.885737,-87.630886,6,null,null,{"interactive":true,"className":"","stroke":true,"color":"green","weight":5,"opacity":0.5,"fill":true,"fillColor":"green","fillOpacity":0.2},null,null,null,null,null,{"interactive":false,"permanent":false,"direction":"auto","opacity":1,"offset":[0,0],"textsize":"10px","textOnly":false,"className":"","sticky":true},null]}],"limits":{"lat":[41.722377,42.073153],"lng":[-87.90422307,-87.605857]}},"evals":[],"jsHooks":[]}</script>
---
# Hands-On: Explore the Data
Take a look at these data for a few minutes and see if you can find any interesting characteristics in the predictors or the outcome.
<div class="countdown" id="timer_5dd037c8" style="bottom:0;left:1;" data-warnwhen="0">
<code class="countdown-time"><span class="countdown-digits minutes">10</span><span class="countdown-digits colon">:</span><span class="countdown-digits seconds">00</span></code>
</div>
---
# How Should Features Be Encoded/Engineered?
Should the ridership data be transformed?
How should we encode the date?
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
*us_hol <-
* timeDate::listHolidays() %>%
* str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago)
```
]
.pull-right[
Define a few holidays from the `timeDate` package to be used later.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
* recipe(ridership ~ ., data = Chicago)
```
]
.pull-right[
`ridership` at Clark and Lake is the outcome.
All other columns are predictors.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
* step_holiday(date, holidays = us_hol)
```
]
.pull-right[
Make indicator variables for the 20 US holidays identified in `us_hol`.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
step_holiday(date, holidays = us_hol) %>%
* step_date(date)
```
]
.pull-right[
Make factor variables from the `date` column, such as `dow`, `month`, and `year`.
These are not automatically converted to dummy variables.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
step_holiday(date, holidays = us_hol) %>%
step_date(date) %>%
* step_rm(date)
```
]
.pull-right[
We've made all of our date-based predictors, so remove the `date` column from the data.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
step_holiday(date, holidays = us_hol) %>%
step_date(date) %>%
step_rm(date) %>%
* step_dummy(all_nominal())
```
]
.pull-right[
Make dummy variables out of all of the factor or character columns in the data.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
step_holiday(date, holidays = us_hol) %>%
step_date(date) %>%
step_rm(date) %>%
step_dummy(all_nominal()) %>%
* step_zv(all_predictors())
```
]
.pull-right[
In case there are column with only a single unique value (perhaps due to resampling), remove them.
]
---
# A Recipe
.pull-left[
```r
library(stringr)
# define a few holidays
us_hol <-
timeDate::listHolidays() %>%
str_subset("(^US)|(Easter)")
chi_rec <-
recipe(ridership ~ ., data = Chicago) %>%
step_holiday(date, holidays = us_hol) %>%
step_date(date) %>%
step_rm(date) %>%
step_dummy(all_nominal()) %>%
step_zv(all_predictors())
* # step_normalize(one_of(!!stations))
* # step_pca(one_of(!!stations), num_comp = tune())
```
]
.pull-right[
The ridership between stations is highly correlated.
If we use a model that would be harded by this, we _could_ extract the principal components for these columns.
]
---
# Resampling
If your job were to model these data, you would probably take historical data as your training set and use the most recent data as the test set.
Our resampling scheme will emulate this using [rolling forecasting origin](https://otexts.com/fpp2/accuracy.html) resampling with
* Moving analysis sets of 15 years moving over 28 day periods
* An assessment set of the most recent 28 days of data
```r
data_folds <- rolling_origin(Chicago, initial = 364 * 15, assess = 7 * 4, skip = 7 * 4, cumulative = FALSE)
data_folds %>% nrow()
```
```
## [1] 8
```
---
# Resampling Graphic
<img src="images/part-5-resample-plot-1.svg" width="75%" style="display: block; margin: auto;" />
---
layout: false
class: inverse, middle, center
# Linear Models
---
# Linear Regression Analysis
We'll start by fitting linear regression models to these data.
As a reminder, the "linear" part means that the model is linear in the _parameters_; we can add nonlinear terms to the model (e.g. `x^2` or `log(x)`) without causing issues.
The most start might be with `lm` and the formula method.
```r
lm(ridership ~ . - date, data = Chicago)
```
We know that there are a lot of features that we'd miss out on though (e.g. holidays, day-of-the-week, etc.).
---
# Potential Issues with Linear Regression
We'll look at the L train data and examine a few different models to illustrate some more complex models and approaches to optimizing them. We'll start with linear models.
However, some potential issues with linear methods:
* They do not automatically do _feature selection_ and including irrelevant predictors may degrade performance.
* Linear models are sensitive to situations where the predictors are _highly correlated_ (aka collinearity). This isn't too big of an issue for these data though.
To mitigate these two scenarios, _regularization_ will be used. This approach adds a penalty to the regression parameters.
* In order to have a large slope in the model, the predictor will need to have a large impact on the model.
There are different types of regularization methods.
---
# Effect of Collinearity
As an example of collinearity, our data set has two predictors that have a correlation above 0.95: `Irving_Park` and `Belmont`.
What happens when we fit models with both predictors versus one-at-a-time?
<table class="table" style="margin-left: auto; margin-right: auto;">
<thead>
<tr>
<th style="border-bottom:hidden" colspan="1"></th>
<th style="border-bottom:hidden; padding-bottom:0; padding-left:3px;padding-right:3px;text-align: center; " colspan="3"><div style="border-bottom: 1px solid #ddd; padding-bottom: 5px; ">Coefficients</div></th>
<th style="border-bottom:hidden" colspan="1"></th>
</tr>
<tr>
<th style="text-align:left;"> Term </th>
<th style="text-align:right;"> Belmont Only </th>
<th style="text-align:right;"> Irving Park Only </th>
<th style="text-align:right;"> Both Predictors </th>
<th style="text-align:right;"> Variance Inflation </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> Irving Park </td>
<td style="text-align:right;"> --- </td>
<td style="text-align:right;"> 4.974 </td>
<td style="text-align:right;"> 4.109 </td>
<td style="text-align:right;"> 26.842 </td>
</tr>
<tr>
<td style="text-align:left;"> Belmont </td>
<td style="text-align:right;"> 4.433 </td>
<td style="text-align:right;"> --- </td>
<td style="text-align:right;"> 0.795 </td>
<td style="text-align:right;"> 25.112 </td>
</tr>
</tbody>
</table>
The coefficients can drastically change depending on what is in the model and their corresponding variances can also be artificially large and may flip signs.
---
# Regularized Linear Regression
Now suppose we want to see if _regularizing_ the regression coefficients will result in better fits.
The [`glmnet`](https://www.jstatsoft.org/article/view/v033i01) model can be used to build a linear model using L<sub>1</sub> or L<sub>2</sub> regularization (or a mixture of the two).
* The general formulation minimizes: `\(\sum_{i = 1}^{n} (y_i - \sum_{j = 1}^{p} x_{ij} \beta_j) ^ 2 + penalty\)`.
* An L<sub>1</sub> penalty (penalty is `\(\lambda_1\sum|\beta_j|\)`) can have the effect of setting coefficients to zero.
* L<sub>2</sub> regularization ( `\(\lambda_2\sum\beta_j^2\)` ) is basically ridge regression where the magnitude of the coefficients are dampened to avoid overfitting.
For a `glmnet` model, we need to determine the total amount regularization (called `lambda`) and the mixture of L<sub>1</sub> and L<sub>2</sub> (called `alpha`).
* `alpha` = 1 is a _lasso model_ while `alpha` = 0 is _ridge regression_ (aka weight decay).
Predictors require centering/scaling before being used in a `glmnet`, lasso, or ridge regression model.
Technical bits can be found in [Statistical Learning with Sparsity](https://web.stanford.edu/~hastie/StatLearnSparsity/).
???
Note the need to center and scale based on the type of penalty
---
# Harmonization of Parameter Names
If you are new to these models, `lambda` and `alpha` are pretty arcane and don't tell you anything about what they do.
Other packages use different names for these parameters (`reg_param`, `penalty`, `lambda1`, `lambda2`, etc.) so it isn't very friendly.
The `parsnip` package tries to standardize on less jargony and more self-documenting. We use `penalty` (instead of `lambda`) and `mixture` instead of `alpha`. These will always be the same for models within an engine and between-models too.
For this problem, we have two tuning parameters:
* `mixture` must be between zero and one. A small grid is used for this parameter.
* `penalty` is not as clear-cut. We consider values on the log<sub>10</sub> scale. Usually values less than one are sufficient but this is not always true.
---
# Tuning the Model
Let's once again use grid search with a regular grid to find good values of `penalty` and `mixture`.
It turns out that evaluating values of `penalty` are _cheaper_ than values of `mixture`. We'll tune a grid of 20 penalty values and 5 mixtures between ridge regression and the lasso.
```r
glmn_grid <- expand.grid(penalty = 10^seq(-3, -1, length = 20), mixture = (0:5)/5)
```
The reason that penalties are cheap is that this model simultaneously computes parameter estimates for _all possible penalty values_ (for a fixed mixture). This is the _sub-model trick_.
Using the grid above, we evaluate 120 models but only fit five.
---
# Tuning the Model
```r
# We need to normalize the predictors:
glmn_rec <- chi_rec %>% step_normalize(all_predictors())
glmn_mod <-
linear_reg(penalty = tune(), mixture = tune()) %>% set_engine("glmnet")
# Save the assessment set predictions
ctrl <- control_grid(save_pred = TRUE)
glmn_res <-
tune_grid(
glmn_rec,
model = glmn_mod,
resamples = data_folds,
grid = glmn_grid,
control = ctrl
)
```
---
# While We Wait, Can I Interest You in Parallelism?
.pull-left[
There is no real barrier to running these in parallel.
Can we benefit from splitting the fits up to run on multiple cores?
These speed-ups can be very model- and data-dependent but this pattern generally holds.
Note that there is little incremental benefit to using more workers than physical cores on the computer. Use `parallel::detectCores(logical = FALSE)`.
(A lot more details can be found in [this blog post](http://appliedpredictivemodeling.com/blog/2018/1/17/parallel-processing))
]
.pull-right[
<img src="images/part-5-par-plot-1.svg" width="100%" style="display: block; margin: auto;" />
In these simulations, we estimated the speed-up by using the sub-model trick to be about _25-fold_.
]
---
# Running in Parallel with {tune}
.pull-left[
To loop through the models and data sets, `tune` uses the [`foreach`](https://www.rdocumentation.org/packages/foreach) package, which can parallelize `for` loops.
`foreach` has a number of _parallel backends_ which allow various technologies to be used in conjunction with the package.
On CRAN, these are the "`do{X}`" packages, such as
[`doAzureParallel`](https://github.com/Azure/doAzureParallel),
[`doFuture`](https://www.rdocumentation.org/packages/doFuture), [`doMC`](https://www.rdocumentation.org/packages/doMC),
[`doMPI`](https://www.rdocumentation.org/packages/doMPI), [`doParallel`](https://www.rdocumentation.org/packages/doParallel), [`doRedis`](https://www.rdocumentation.org/packages/doRedis), and [`doSNOW`](https://www.rdocumentation.org/packages/doSNOW).
For example, `doMC` uses the `multicore` package, which forks processes to split computations (for unix and OS X). `doParallel` can be used for all operating systems.
]
.pull-right[
To use parallel processing in `tune`, no changes are needed when calling `tune_*()`.
The parallel technology must be _registered_ with `foreach` prior to calling `tune_*()`:
```r
library(doParallel)
cl <- makeCluster(6)
registerDoParallel(cl)
# run `tune_grid()`...
stopCluster(cl)
```
]
---
# Plotting the Resampling Profile
.code70[
.pull-left[
```r
rmse_vals <- collect_metrics(glmn_res) %>% filter(.metric == "rmse")
rmse_vals %>%
mutate(mixture = format(mixture)) %>%
ggplot(aes(x = penalty, y = mean, col = mixture)) +
geom_line() +
geom_point() +
scale_x_log10()
```
<img src="images/part-5-lr-grid-plot-1.svg" width="95%" style="display: block; margin: auto;" />
]
]
.pull-right[
A pure ridge regression solution (`mixture = 0`) does poorly and the model seems to like a small amount of regularization overall.
]
---
# The numerically best results
The numerically best results were:
```r
show_best(glmn_res, metric = "rmse", maximize = FALSE)
```
```
## # A tibble: 5 x 7
## penalty mixture .metric .estimator mean n std_err
## <dbl> <dbl> <chr> <chr> <dbl> <int> <dbl>
## 1 0.00162 0.8 rmse standard 1.15 8 0.0688
## 2 0.00127 0.8 rmse standard 1.15 8 0.0680
## 3 0.001 0.8 rmse standard 1.15 8 0.0682
## 4 0.00207 0.8 rmse standard 1.15 8 0.0699
## 5 0.00264 0.8 rmse standard 1.15 8 0.0712
```
```r
best_glmn <- select_best(glmn_res, metric = "rmse", maximize = FALSE)
best_glmn
```
```
## # A tibble: 1 x 2
## penalty mixture
## <dbl> <dbl>
## 1 0.00162 0.8
```
---
# Residual Analysis
Recall that the `save_pred = TRUE` option was used. That retains the held-out predictions for each resample and sub-model. Those are in a list column called `.predictions`.
We can use `tidyr::unnest()` to get the results back or use this convenience function:
```r
lr_pred <- collect_predictions(glmn_res)
lr_pred %>% slice(1:10)
```
```
## # A tibble: 10 x 6
## id .pred .row penalty mixture ridership
## <chr> <dbl> <int> <dbl> <dbl> <dbl>
## 1 Slice1 18.8 5461 0.001 0 19.6
## 2 Slice1 18.8 5461 0.00127 0 19.6
## 3 Slice1 18.8 5461 0.00162 0 19.6
## 4 Slice1 18.8 5461 0.00207 0 19.6
## 5 Slice1 18.8 5461 0.00264 0 19.6
## 6 Slice1 18.8 5461 0.00336 0 19.6
## 7 Slice1 18.8 5461 0.00428 0 19.6
## 8 Slice1 18.8 5461 0.00546 0 19.6
## 9 Slice1 18.8 5461 0.00695 0 19.6
## 10 Slice1 18.8 5461 0.00886 0 19.6
```
---
# Observed Versus Predicted Plot
.code70[
.pull-left[
```r
# Keep the best model
lr_pred <-
lr_pred %>%
inner_join(best_glmn, by = c("penalty", "mixture"))
ggplot(lr_pred, aes(x = .pred, y = ridership)) +
geom_abline(col = "green") +
geom_point(alpha = .3) +
coord_equal()
```
]
]
.pull-right[
<img src="images/part-5-lr-pred-plot-1.svg" width="75%" style="display: block; margin: auto;" />
]
---
# Which training set points had the worst results?
.pull-left[
```r
large_resid <-
lr_pred %>%
mutate(resid = ridership - .pred) %>%
arrange(desc(abs(resid))) %>%
slice(1:4)
library(lubridate)
Chicago %>%
slice(large_resid$.row) %>%
mutate(day = wday(date, label = TRUE)) %>%
bind_cols(large_resid) %>%
select(date, day, ridership, .pred, resid)
```
```
## # A tibble: 4 x 5
## date day ridership .pred resid
## <date> <ord> <dbl> <dbl> <dbl>
## 1 2016-07-04 Mon 5.92 11.2 -5.26
## 2 2016-03-12 Sat 12.4 7.59 4.80
## 3 2016-06-26 Sun 5.07 7.63 -2.56
## 4 2016-04-01 Fri 22.4 19.8 2.56
```
]
.pull-right[
We have a July 4th holiday indicator yet still over-predicted.
For this data set, I end up googling to see why my predictions fail.
]
---
# Which training set points had the worst results?
.pull-left[
```r
large_resid <-
lr_pred %>%
mutate(resid = ridership - .pred) %>%
arrange(desc(abs(resid))) %>%
slice(1:4)
library(lubridate)
Chicago %>%
slice(large_resid$.row) %>%
mutate(day = wday(date, label = TRUE)) %>%
bind_cols(large_resid) %>%
select(date, day, ridership, .pred, resid)
```
```
## # A tibble: 4 x 5
## date day ridership .pred resid
## <date> <ord> <dbl> <dbl> <dbl>
## 1 2016-07-04 Mon 5.92 11.2 -5.26
## 2 2016-03-12 Sat 12.4 7.59 4.80
## 3 2016-06-26 Sun 5.07 7.63 -2.56
## 4 2016-04-01 Fri 22.4 19.8 2.56
```
]
.pull-right[
We have a July 4th holiday indicator yet still over-predicted.
For this data set, I end up googling to see why my predictions fail.
<img src="images/chicago-2016-03-12.png" width="100%" />
]
---
# Creating a Final Model
Let's prep the recipe then fit the final glmnet model with the best parameters:
.pull-left[
```r
glmn_rec_final <- prep(glmn_rec)
glmn_mod_final <- finalize_model(glmn_mod, best_glmn)
glmn_mod_final
```
```
## Linear Regression Model Specification (regression)
##
## Main Arguments:
## penalty = 0.00162377673918872
## mixture = 0.8
##
## Computational engine: glmnet
```
```r
glmn_fit <-
glmn_mod_final %>%
fit(ridership ~ ., data = juice(glmn_rec_final))
```
]
.pull-right[
```r
glmn_fit
```
```
## parsnip model object
##
## Fit in: 39ms
## Call: glmnet::glmnet(x = as.matrix(x), y = y, family = "gaussian", alpha = ~0.8)
##
## Df %Dev Lambda
## 1 0 0.0000 7.2490
## 2 2 0.1117 6.6050
## 3 5 0.2175 6.0180
## 4 5 0.3095 5.4830
## 5 8 0.3869 4.9960
## 6 8 0.4523 4.5520
## 7 9 0.5068 4.1480
## 8 9 0.5524 3.7800
## 9 9 0.5904 3.4440
## 10 9 0.6221 3.1380
## 11 10 0.6488 2.8590
## 12 10 0.6711 2.6050
## 13 10 0.6896 2.3740
## 14 10 0.7051 2.1630
## 15 10 0.7180 1.9710
## 16 9 0.7287 1.7960
## 17 9 0.7377 1.6360
## 18 9 0.7452 1.4910
## 19 8 0.7515 1.3580
## 20 8 0.7568 1.2380
## 21 9 0.7622 1.1280
## 22 9 0.7668 1.0280
## 23 10 0.7708 0.9362
## 24 11 0.7763 0.8531
## 25 14 0.7836 0.7773
## 26 14 0.7923 0.7082
## 27 16 0.8002 0.6453
## 28 16 0.8084 0.5880
## 29 16 0.8152 0.5357
## 30 16 0.8209 0.4881
## 31 16 0.8257 0.4448
## 32 18 0.8299 0.4053
## 33 19 0.8341 0.3693
## 34 20 0.8379 0.3365
## 35 22 0.8413 0.3066
## 36 24 0.8451 0.2793
## 37 25 0.8492 0.2545
## 38 28 0.8616 0.2319
## 39 29 0.8740 0.2113
## 40 30 0.8843 0.1925
## 41 30 0.8931 0.1754
## 42 30 0.9008 0.1598
## 43 31 0.9075 0.1456
## 44 33 0.9132 0.1327
## 45 36 0.9180 0.1209
## 46 37 0.9223 0.1102
## 47 36 0.9257 0.1004
## 48 37 0.9288 0.0915
## 49 37 0.9315 0.0833
## 50 37 0.9337 0.0759
## 51 36 0.9354 0.0692
## 52 37 0.9369 0.0630
## 53 37 0.9380 0.0574
## 54 38 0.9391 0.0523
## 55 37 0.9399 0.0477
## 56 38 0.9406 0.0435
## 57 39 0.9414 0.0396
## 58 38 0.9420 0.0361
## 59 42 0.9430 0.0329
## 60 45 0.9438 0.0300
## 61 46 0.9445 0.0273
## 62 48 0.9452 0.0249
## 63 48 0.9457 0.0227
## 64 54 0.9461 0.0206
## 65 58 0.9465 0.0188
## 66 59 0.9470 0.0171
## 67 60 0.9475 0.0156
## 68 60 0.9478 0.0142
## 69 63 0.9481 0.0130
## 70 64 0.9484 0.0118
## 71 67 0.9486 0.0108
## 72 68 0.9488 0.0098
## 73 68 0.9489 0.0089
## 74 68 0.9491 0.0081
## 75 69 0.9492 0.0074
## 76 71 0.9493 0.0068
## 77 72 0.9494 0.0062
## 78 72 0.9495 0.0056
## 79 73 0.9496 0.0051
## 80 73 0.9497 0.0047
## 81 75 0.9497 0.0042
## 82 74 0.9498 0.0039
## 83 75 0.9498 0.0035
## 84 76 0.9498 0.0032
## 85 76 0.9499 0.0029
## 86 77 0.9499 0.0027
## 87 78 0.9499 0.0024
## 88 77 0.9499 0.0022
## 89 78 0.9500 0.0020
## 90 78 0.9500 0.0018
## 91 80 0.9500 0.0017
## 92 82 0.9500 0.0015
## 93 82 0.9500 0.0014
## 94 82 0.9500 0.0013
## 95 83 0.9500 0.0012
```
]
---
# Using the `glmnet` Object
.pull-left[
The `parsnip` object saves the optimized model that was fit to the entire training set in the slot `fit`.
This can be used as it normally would.
The plot on the right is creating using
```r
library(glmnet)
plot(glmn_fit$fit, xvar = "lambda")
```
However, **please don't use `predict(object$fit)` **!
Use the `predict()` method on the object that is produced by `fit`.
]
.pull-right[
<img src="images/part-5-reg-path-1.svg" width="99%" style="display: block; margin: auto;" />
]
Coefs:
```