-
Notifications
You must be signed in to change notification settings - Fork 90
/
Part_2.html
785 lines (556 loc) · 19.6 KB
/
Part_2.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<title>Applied Machine Learning</title>
<meta charset="utf-8" />
<meta name="author" content="Max Kuhn and Davis Vaughan (RStudio)" />
<meta name="date" content="2020-01-26" />
<link href="libs/remark-css-0.0.1/default.css" rel="stylesheet" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<link rel="stylesheet" href="assets/css/aml-theme.css" type="text/css" />
<link rel="stylesheet" href="assets/css/aml-fonts.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: title-slide, center
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x" style="color: #ffffff;"></i>
<strong class="fa-stack-1x" style="color:#E7553C;">2</strong>
</span>
# Applied Machine Learning
## Data Usage
---
# Loading
.code90[
```r
library(tidymodels)
```
```
## Registered S3 method overwritten by 'xts':
## method from
## as.zoo.xts zoo
```
```
## ── Attaching packages ────────────────────────────── tidymodels 0.0.3 ──
```
```
## ✓ broom 0.5.3 ✓ purrr 0.3.3
## ✓ dials 0.0.4.9000 ✓ recipes 0.1.9
## ✓ dplyr 0.8.3 ✓ rsample 0.0.5
## ✓ ggplot2 3.2.1 ✓ tibble 2.1.3
## ✓ infer 0.5.1 ✓ yardstick 0.0.4
## ✓ parsnip 0.0.5
```
```
## ── Conflicts ───────────────────────────────── tidymodels_conflicts() ──
## x purrr::discard() masks scales::discard()
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## x ggplot2::margin() masks dials::margin()
## x recipes::step() masks stats::step()
## x recipes::yj_trans() masks scales::yj_trans()
```
```r
library(AmesHousing)
```
]
---
# Data Splitting and Spending
How do we "spend" the data to find an optimal model?
We _typically_ split data into training and test data sets:
* ***Training Set***: these data are used to estimate model parameters and to pick the values of the complexity parameter(s) for the model.
* ***Test Set***: these data can be used to get an independent assessment of model efficacy. They should not be used during model training.
---
# Mechanics of Data Splitting
There are a few different ways to do the split: simple random sampling, _stratified sampling based on the outcome_, by date, or methods that focus on the distribution of the predictors.
For stratification:
* **Classification**:
This would mean sampling within the classes to preserve the distribution of the outcome in the training and test sets.
* **Regression**:
Determine the quartiles of the data set and sample within those artificial groups.
---
# Ames Housing Data <img src="images/rsample.png" class="title-hex"><img src="images/dplyr.png" class="title-hex">
Let's load the example data set and split it. We'll put 75% into training and 25% into testing.
```r
# rsample loaded with tidyverse or tidymodels package
ames <-
make_ames() %>%
# Remove quality-related predictors
dplyr::select(-matches("Qu"))
nrow(ames)
```
```
## [1] 2930
```
```r
# resample functions
# Make sure that you get the same random numbers
set.seed(4595)
data_split <- initial_split(ames, strata = "Sale_Price")
ames_train <- training(data_split)
ames_test <- testing(data_split)
nrow(ames_train)/nrow(ames)
```
```
## [1] 0.7505119
```
???
The select statement removes subjective quality scores which, to me, seems
like it should be an outcome and not a predictor.
---
# Ames Housing Data <img src="images/rsample.png" class="title-hex">
What do these objects look like?
```r
# result of initial_split()
# <training / testing / total>
data_split
```
```
## <2199/731/2930>
```
```r
training(data_split)
```
```r
## # A tibble: 2,199 x 81
## MS_SubClass MS_Zoning Lot_Frontage Lot_Area Street Alley Lot_Shape Land_Contour Utilities Lot_Config Land_Slope
## <fct> <fct> <dbl> <int> <fct> <fct> <fct> <fct> <fct> <fct> <fct>
## 1 One_Story_… Resident… 141 31770 Pave No_A… Slightly… Lvl AllPub Corner Gtl
## 2 Two_Story_… Resident… 74 13830 Pave No_A… Slightly… Lvl AllPub Inside Gtl
## 3 Two_Story_… Resident… 78 9978 Pave No_A… Slightly… Lvl AllPub Inside Gtl
## 4 One_Story_… Resident… 43 5005 Pave No_A… Slightly… HLS AllPub Inside Gtl
## 5 One_Story_… Resident… 39 5389 Pave No_A… Slightly… Lvl AllPub Inside Gtl
## # … and many more rows and columns
## # …
```
---
layout: false
class: inverse, middle, center
# Creating Models in R
---
# Specifying Models in R Using Formulas
To fit a model to the housing data, the model terms must be specified. Historically, there are two main interfaces for doing this. The **formula** interface uses R [formula rules](https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Formulae-for-statistical-models) to specify a _symbolic_ representation of the terms:
.pull-left-a-lot[
Variables + interactions
```r
model_fn(
Sale_Price ~ Neighborhood + Year_Sold + Neighborhood:Year_Sold,
data = ames_train
)
```
Inline functions / transformations
```r
model_fn(
log10(Sale_Price) ~ ns(Longitude, df = 3) + ns(Latitude, df = 3),
data = ames_train
)
```
]
.pull-right-a-little[
Shorthand for all predictors
```r
model_fn(
Sale_Price ~ .,
data = ames_train
)
```
This is very convenient but it has some disadvantages.
]
---
# Downsides to Formulas
* You can't nest in-line functions such as
```r
model_fn(y ~ pca(scale(x1), scale(x2), scale(x3)), data = dat)
```
* All the model matrix calculations happen at once and can't be recycled when used in a model function.
* For very _wide_ data sets, the formula method can be [extremely inefficient](https://rviews.rstudio.com/2017/03/01/the-r-formula-method-the-bad-parts/).
* There are limited _roles_ that variables can take which has led to several re-implementations of formulas.
* Specifying multivariate outcomes is clunky and inelegant.
* Not all modeling functions have a formula method (consistency!).
---
# Specifying Models Without Formulas
Some modeling function have a non-formula (XY) interface. This usually has arguments for the predictors and the outcome(s):
```r
# Usually, the variables must all be numeric
pre_vars <- c("Year_Sold", "Longitude", "Latitude")
model_fn(x = ames_train[, pre_vars], y = ames_train$Sale_Price)
```
This is inconvenient if you have transformations, factor variables, interactions, or any other operations to apply to the data prior to modeling.
Overall, it is difficult to predict if a package has one or both of these interfaces. For example, `lm()` only has formulas.
There is a **third interface**, using _recipes_ that will be discussed later that solves some of these issues.
---
# A Linear Regression Model <img src="images/broom.png" class="title-hex">
Let's start by fitting an ordinary linear regression model to the training set. You can choose the model terms for your model, but I will use a very simple model:
```r
simple_lm <- lm(log10(Sale_Price) ~ Longitude + Latitude, data = ames_train)
```
Before looking at coefficients, we should do some model checking to see if there is anything obviously wrong with the model.
To get the statistics on the individual data points, we will use the awesome `broom` package:
```r
simple_lm_values <- augment(simple_lm)
names(simple_lm_values)
```
```
## [1] "log10.Sale_Price." "Longitude" "Latitude"
## [4] ".fitted" ".se.fit" ".resid"
## [7] ".hat" ".sigma" ".cooksd"
## [10] ".std.resid"
```
---
# A Linear Regression Model <img src="images/broom.png" class="title-hex">
```r
head(simple_lm_values, n = 2)
```
```
## # A tibble: 2 x 10
## log10.Sale_Pric… Longitude Latitude .fitted .se.fit .resid .hat .sigma
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 5.24 -93.6 42.1 5.23 0.00581 0.00920 0.00127 0.163
## 2 5.39 -93.6 42.1 5.22 0.00581 0.169 0.00127 0.163
## # … with 2 more variables: .cooksd <dbl>, .std.resid <dbl>
```
After working with the individual data points, you can move on to the coefficients themselves. `tidy()` extracts the coefficients from the model. `glance()` summarizes a model fit's overarching metrics.
.pull-left-a-lot[
```r
tidy(simple_lm)
```
```
## # A tibble: 3 x 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) -307. 15.1 -20.3 2.39e-84
## 2 Longitude -2.03 0.134 -15.1 2.41e-49
## 3 Latitude 2.89 0.190 15.3 5.43e-50
```
]
.pull-right-a-little[
```r
# But don't trust this too much!
glance(simple_lm)[1:3]
```
```
## # A tibble: 1 x 3
## r.squared adj.r.squared sigma
## <dbl> <dbl> <dbl>
## 1 0.170 0.169 0.163
```
]
---
# parsnip <img src="images/parsnip.png" class="title-hex">
- A tidy unified _interface_ to models
- `lm()` isn't the only way to perform linear regression
- `glmnet` for regularized regression
- `stan` for Bayesian regression
- `keras` for regression using tensorflow
- `spark` for large data sets
- But...remember the consistency slide?
- Each interface has its own minutae to remember
---
# parsnip in Action <img src="images/parsnip.png" class="title-hex">
.pull-left[
1) Create a specification
2) Set the engine
3) Fit the model
```r
spec_lin_reg <- linear_reg()
spec_lin_reg
```
```
## Linear Regression Model Specification (regression)
```
```r
lm_mod <- set_engine(spec_lin_reg, "lm")
lm_mod
```
```
## Linear Regression Model Specification (regression)
##
## Computational engine: lm
```
]
.pull-right[
```r
lm_fit <- fit(
lm_mod,
log10(Sale_Price) ~ Longitude + Latitude,
data = ames_train
)
lm_fit
```
```
## parsnip model object
##
## Fit time: 4ms
##
## Call:
## stats::lm(formula = formula, data = data)
##
## Coefficients:
## (Intercept) Longitude Latitude
## -306.688 -2.032 2.893
```
]
---
# Different interfaces <img src="images/parsnip.png" class="title-hex">
`parsnip` is not picky about the interface used to specify terms. Remember, `lm()` only allowed the formula interface!
```r
ames_train_log <- ames_train %>%
mutate(Sale_Price_Log = log10(Sale_Price))
fit_xy(
lm_mod,
y = dplyr::pull(ames_train_log, Sale_Price_Log),
x = dplyr::select(ames_train_log, Latitude, Longitude)
)
```
```
## parsnip model object
##
## Fit time: 2ms
##
## Call:
## stats::lm(formula = formula, data = data)
##
## Coefficients:
## (Intercept) Latitude Longitude
## -306.688 2.893 -2.032
```
---
# Alternative Engines <img src="images/parsnip.png" class="title-hex">
With `parsnip`, it is easy to switch to a different engine, like Stan, to run the
same model with alternative backends.
.pull-left[
```r
spec_stan <-
spec_lin_reg %>%
# Engine specific arguments are passed through here
set_engine("stan", chains = 4, iter = 1000)
# Otherwise, looks exactly the same!
fit_stan <- fit(
spec_stan,
log10(Sale_Price) ~ Longitude + Latitude,
data = ames_train
)
```
]
.pull-right[
```r
coef(fit_stan$fit)
```
```
## (Intercept) Longitude Latitude
## -306.335843 -2.030861 2.884487
```
```r
coef(lm_fit$fit)
```
```
## (Intercept) Longitude Latitude
## -306.688470 -2.032306 2.892838
```
]
---
# Different models <img src="images/parsnip.png" class="title-hex">
Switching _between_ models is easy since the interfaces are homogenous.
For example, to fit a 5-nearest neighbor model:
```r
fit_knn <-
nearest_neighbor(mode = "regression", neighbors = 5) %>%
set_engine("kknn") %>%
fit(log10(Sale_Price) ~ Longitude + Latitude, data = ames_train)
fit_knn
```
```
## parsnip model object
##
## Fit time: 36ms
##
## Call:
## kknn::train.kknn(formula = formula, data = data, ks = ~5)
##
## Type of response variable: continuous
## minimal mean absolute error: 0.06753097
## Minimal mean squared error: 0.009633708
## Best kernel: optimal
## Best k: 5
```
---
layout: false
class: middle, center
# Now that we have fit a model on the _training_ set,
# is it time to make predictions on the _test_ set?
---
<img src="images/nope.png" width="40%" style="display: block; margin: auto;" />
---
# DANGER
.pull-left[
In general, we would **not** want to predict the test set at this point, although we will do so to illustrate how the code works.
In a real scenario, we would use _resampling_ methods (e.g. cross-validation, bootstrapping, etc) or a validation set to evaluate how well the model is doing.
]
.pull-right[
<img src="images/nope.png" width="55%" style="display: block; margin: auto;" />
]
`tidymodels` has a great infrastructure to do this with `rsample`, and we will talk about this soon to demonstrate how we should _really_ evaluate models.
---
# Predictions <img src="images/purrr.png" class="title-hex"><img src="images/parsnip.png" class="title-hex"><img src="images/dplyr.png" class="title-hex">
For now, let's compute predictions and performance measures on the test set:
.pull-left[
```r
# Numeric predictions always in a df
# with column `.pred`
test_pred <-
lm_fit %>%
predict(ames_test) %>%
bind_cols(ames_test) %>%
mutate(log_price = log10(Sale_Price))
test_pred %>%
dplyr::select(log_price, .pred) %>%
slice(1:3)
```
```
## # A tibble: 3 x 2
## log_price .pred
## <dbl> <dbl>
## 1 5.33 5.23
## 2 5.02 5.23
## 3 5.27 5.27
```
]
.pull-right[
`parsnip` tools are very standardized.
* `predict()` always produces a tibble with a row for each row of `new_data`.
* The column names are also [predictable](https://tidymodels.github.io/parsnip/reference/predict.model_fit.html#value). For (univariate) regression predictions, the prediction column is always `.pred`.
]
So, for the KNN model, just change the argument to `fit_knn` and everything works.
---
# Estimating Performance <img src="images/yardstick.png" class="title-hex">
.pull-left[
The `yardstick` package is a tidy interface for computing measures of performance.
There are individual functions for specific metrics (e.g. `accuracy()`, `rmse()`, etc.).
When more than one metric is desired, `metric_set()` can create a new function that wraps them.
Note that these metric functions work with `group_by()`.
]
.pull-right[
```r
# yardstick loaded by tidymodels
perf_metrics <- metric_set(rmse, rsq, ccc)
# A tidy result back:
test_pred %>%
perf_metrics(truth = log_price, estimate = .pred)
```
```
## # A tibble: 3 x 3
## .metric .estimator .estimate
## <chr> <chr> <dbl>
## 1 rmse standard 0.155
## 2 rsq standard 0.181
## 3 ccc standard 0.306
```
There are sometimes different ways to [estimate these statistics](https://tidymodels.github.io/yardstick/articles/multiclass.html); `.estimator` is not always "standard".
]
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script src="https://platform.twitter.com/widgets.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "solarized-light",
"highlightLanguage": "R",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9"
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>