/
Part_3.html
738 lines (501 loc) · 21 KB
/
Part_3.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
<!DOCTYPE html>
<html>
<head>
<title>Modeling in the Tidyverse - Feature Engineering</title>
<meta charset="utf-8">
<meta name="author" content="Max Kuhn (RStudio)" />
<script src="libs/kePrint-0.0.1/kePrint.js"></script>
<link href="libs/countdown-0.1.0/countdown.css" rel="stylesheet" />
<script src="libs/countdown-0.1.0/countdown.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
# Modeling in the Tidyverse - Feature Engineering
### Max Kuhn (RStudio)
---
# Loading
```r
library(tidymodels)
```
```
## ── Attaching packages ─────── tidymodels 0.0.2 ──
```
```
## ✔ broom 0.5.2 ✔ purrr 0.3.2
## ✔ dials 0.0.2 ✔ recipes 0.1.5
## ✔ dplyr 0.8.1 ✔ rsample 0.0.4
## ✔ ggplot2 3.1.0 ✔ tibble 2.1.1
## ✔ infer 0.4.0 ✔ yardstick 0.0.2
## ✔ parsnip 0.0.2
```
```
## ── Conflicts ────────── tidymodels_conflicts() ──
## ✖ purrr::discard() masks scales::discard()
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ✖ recipes::step() masks stats::step()
```
---
# Previously
```r
library(AmesHousing)
ames <-
make_ames() %>%
dplyr::select(-matches("Qu"))
set.seed(4595)
data_split <- initial_split(ames, strata = "Sale_Price")
ames_train <- training(data_split)
ames_test <- testing(data_split)
spec_lm <-
linear_reg() %>%
set_engine("lm")
perf_metrics <- metric_set(rmse, rsq, ccc)
```
---
layout: false
class: inverse, middle, center
# Feature Engineering
---
# Preprocessing and Feature Engineering
This part mostly concerns what we can _do_ to our variables to make the models more effective.
This is mostly related to the predictors. Operations that we might use are:
* transformations of individual predictors or groups of variables
* alternate encodings of a variable
* elimination of predictors (unsupervised)
In statistics, this is generally called _preprocessing_ the data. As usual, the computer science side of modeling has a much flashier name: _feature engineering_.
---
# Reasons for Modifying the Data
* Some models (_K_-NN, SVMs, PLS, neural networks) require that the predictor variables have the same units. **Centering** and **scaling** the predictors can be used for this purpose.
* Other models are very sensitive to correlations between the predictors and **filters** or **PCA signal extraction** can improve the model.
* As we'll see in an example, changing the scale of the predictors using a **transformation** can lead to a big improvement.
* In other cases, the data can be **encoded** in a way that maximizes its effect on the model. Representing the date as the day of the week can be very effective for modeling public transportation data.
* Many models cannot cope with missing data so **imputation** strategies might be necessary.
* Development of new _features_ that represent something important to the outcome (e.g. compute distances to public transportation, university buildings, public schools, etc.)
---
layout: false
class: inverse, middle, center
# Preprocessing Categorical Predictors
---
# Dummy Variables
One common procedure for modeling is to create numeric representations of categorical data. This is usually done via _dummy variables_: a set of binary 0/1 variables for different levels of an R factor.
For example, the Ames housing data contains a predictor called `Alley` with levels: 'Gravel', 'No_Alley_Access', 'Paved'.
Most dummy variable procedures would make _two_ numeric variables from this predictor that are 1 when the observation has that level, and 0 otherwise.
<table class="table" style="width: auto !important; margin-left: auto; margin-right: auto;">
<thead>
<tr>
<th style="border-bottom:hidden; padding-bottom:0; padding-left:3px;padding-right:3px;text-align: center; " colspan="1"><div style="border-bottom: 1px solid #ddd; padding-bottom: 5px; ">Data</div></th>
<th style="border-bottom:hidden; padding-bottom:0; padding-left:3px;padding-right:3px;text-align: center; " colspan="2"><div style="border-bottom: 1px solid #ddd; padding-bottom: 5px; ">Dummy Variables</div></th>
</tr>
<tr>
<th style="text-align:left;"> </th>
<th style="text-align:right;"> No_Alley_Access </th>
<th style="text-align:right;"> Paved </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> Gravel </td>
<td style="text-align:right;"> 0 </td>
<td style="text-align:right;"> 0 </td>
</tr>
<tr>
<td style="text-align:left;"> No_Alley_Access </td>
<td style="text-align:right;"> 1 </td>
<td style="text-align:right;"> 0 </td>
</tr>
<tr>
<td style="text-align:left;"> Paved </td>
<td style="text-align:right;"> 0 </td>
<td style="text-align:right;"> 1 </td>
</tr>
</tbody>
</table>
---
# Dummy Variables
If there are _C_ levels of the factor, only _C_-1 dummy variables are created since the last can be inferred from the others. There are different contrast schemes for creating the new variables.
For ordered factors, [_polynomial_ contrasts are used](https://bookdown.org/max/FES/encodings-for-ordered-data.html). This is, in many cases, a bad idea. I usually convert them to unordered factors.
How do you create them in R?
The formula method does this for you<sup>1</sup>. Otherwise, the traditional method is to use `model.matrix()` to create a matrix. However, there are some caveats to this that can make things difficult.
We'll show another method for making them shortly.
.footnote[[1] _Almost always_ at least. Tree- and rule-based model functions do not. Examples are `randomforest::randomForest`, `ranger::ranger`, `rpart::rpart`, `C50::C5.0`, `Cubist::cubist`, `klaR::NaiveBayes` and others.]
???
Caveats include new (unseen) levels of a predictor value.
---
# Infrequent Levels in Categorical Factors
.pull-left[
One issue is: what happens when there are very few values of a level?
Consider the Ames training set and the `Neighborhood` variable.
If these data are resampled, what would happen to Landmark and similar locations when dummy variables are created?
]
.pull-right[
<img src="images/part-3-ames-hood-1.svg" width="100%" style="display: block; margin: auto;" />
]
???
Bring up the idea that these issues are model-dependent and something like trees wouldn't care.
Mention the alley variable and how almost all properties have no alley access.
Talk about near-zero-variance predictors.
---
# Infrequent Levels in Categorical Factors
A _zero-variance_ predictor that has only a single value (zero) would be the result.
Many models (e.g. linear/logistic regression, etc.) would find this numerically problematic and issue a warning and `NA` values for that coefficient. Trees and similar models would not notice.
There are two main approaches to dealing with this:
* Run a filter on the training set predictors prior to running the model and remove the zero-variance predictors.
* Recode the factor so that infrequently occurring predictors (and possibly new values) are pooled into an "other" category.
However, `model.matrix()` and the formula method are incapable of doing either of these.
---
# Recipes <img src="images/recipes.png" class="title-hex">
Recipes are an alternative method for creating the data frame of predictors for a model.
They allow for a sequence of _steps_ that define how data should be handled.
Recall the previous part where we used the formula `log10(Sale_Price) ~ Longitude + Latitude`? These steps are:
* Assign `Sale_Price` to be the outcome
* Assign `Longitude` and `Latitude` as predictors
* Log transform the outcome
To start using a recipe, these steps can be done using
```r
# recipes loaded by tidymodels
mod_rec <- recipe(Sale_Price ~ Longitude + Latitude, data = ames_train) %>%
step_log(Sale_Price, base = 10)
```
This creates the recipe for data processing (but does not execute it yet)
---
# Recipes and Categorical Predictors <img src="images/recipes.png" class="title-hex">
To deal with the dummy variable issue, we can expand the recipe with more steps:
.pull-left[
```r
mod_rec <- recipe(
Sale_Price ~ Longitude + Latitude + Neighborhood,
data = ames_train
) %>%
step_log(Sale_Price, base = 10) %>%
# Lump factor levels that occur in
# <= 5% of data as "other"
step_other(Neighborhood, threshold = 0.05) %>%
# Create dummy variables for _any_ factor variables
step_dummy(all_nominal())
```
]
.pull-right[
```r
mod_rec
```
```
## Data Recipe
##
## Inputs:
##
## role #variables
## outcome 1
## predictor 3
##
## Operations:
##
## Log transformation on Sale_Price
## Collapsing factor levels for Neighborhood
## Dummy variables from all_nominal()
```
]
Note that we can use standard `dplyr` selectors as well as some new ones based on the data type (`all_nominal()`) or by their role in the analysis (`all_predictors()`).
---
# Using Recipes <img src="images/recipes.png" class="title-hex">
<br>
<br>
.font200[
```
recipe --> prep --> bake/juice
(define) --> (calculate) --> (apply)
```
]
---
# Preparing the Recipe <img src="images/recipes.png" class="title-hex">
Now that we have a preprocessing _specification_, let's run it on the training set to _prepare_ the recipe:
```r
mod_rec_trained <- prep(mod_rec, training = ames_train, verbose = TRUE)
```
```
## oper 1 step log [training]
## oper 2 step other [training]
## oper 3 step dummy [training]
## The retained training set is ~ 0.19 Mb in memory.
```
Here, the "training" is to determine which levels to lump together and to enumerate the factor levels of the `Neighborhood` variable.
An unused option, `retain = TRUE`, that keeps the processed version of the training set around so we don't have to recompute it.
---
# Preparing the Recipe
```r
mod_rec_trained
```
```
## Data Recipe
##
## Inputs:
##
## role #variables
## outcome 1
## predictor 3
##
## Training data contained 2199 data points and no missing data.
##
## Operations:
##
## Log transformation on Sale_Price [trained]
## Collapsing factor levels for Neighborhood [trained]
## Dummy variables from Neighborhood [trained]
```
---
# Getting the Values <img src="images/recipes.png" class="title-hex">
Once the recipe is prepared, it can be applied to any data set using `bake()`:
```r
ames_test_dummies <- bake(mod_rec_trained, new_data = ames_test)
names(ames_test_dummies)
```
```
## [1] "Sale_Price" "Longitude" "Latitude"
## [4] "Neighborhood_College_Creek" "Neighborhood_Old_Town" "Neighborhood_Edwards"
## [7] "Neighborhood_Somerset" "Neighborhood_Northridge_Heights" "Neighborhood_Gilbert"
## [10] "Neighborhood_Sawyer" "Neighborhood_other"
```
If `retain = TRUE`, the training set does not need to be "rebaked". The `juice()` function can return the processed version of the training data.
Selectors can be used with `bake()` to only extract relevant columns and the default is `everything()`.
---
# How Data Are Used <img src="images/recipes.png" class="title-hex">
Note that we have:
```r
recipe(..., data = data_set)
prep(..., training = data_set)
bake(..., new_data = data_set)
```
In the first case, `data` is used by the `recipe` function only to determine the column names and types (e.g. factor, numeric, etc). A small subset can be passed via `head` or `slice`.
For `prep`, the `training` argument should have all of the data used to estimate parameters and other quantities.
For `bake`, `new_data` is the data that the pre-processing should be applied to.
---
# Hands-On: Zero-Variance Filter
Instead of using `step_other()`, take 10 minutes and research how to eliminate any zero-variance predictors using the [`recipe` reference site](https://tidymodels.github.io/recipes/reference/index.html).
Re-run the recipe with this step.
What were the results?
Do you prefer either of these approaches to the other?
<div class="countdown" id="timer_5ce8903d" style="bottom:0;left:1;">
<code><span class="digits minutes">10</span><span class="digits colon">:</span><span class="digits seconds">00</span></code>
</div>
---
layout: false
class: inverse, middle, center
# Interaction Effects
---
# Interactions <img src="images/ggplot2.png" class="title-hex">
An **interaction** between two predictors indicates that the relationship between the predictors and the outcome cannot be describe using only one of the variables.
For example, let's look at the relationship between the price of a house and the year in which it was built. The relationship appears to be slightly nonlinear, possibly quadratic:
.pull-left[
```r
price_breaks <- (1:6)*(10^5)
ggplot(
ames_train,
aes(x = Year_Built, y = Sale_Price)
) +
geom_point(alpha = 0.4) +
scale_y_log10() +
geom_smooth(method = "loess")
```
]
.pull-right[
<img src="images/part-3-year-built-plot-1.svg" width="90%" style="display: block; margin: auto;" />
]
---
# Interactions <img src="images/ggplot2.png" class="title-hex">
However... what if we seperate this trend based on whether the property has air conditioning (93.4% of the training set) or not (6.6%):
.pull-left[
```r
library(MASS) # to get robust linear regression model
ggplot(
ames_train,
aes(x = Year_Built,
y = Sale_Price)
) +
geom_point(alpha = 0.4) +
scale_y_log10() +
facet_wrap(~ Central_Air, nrow = 2) +
geom_smooth(method = "rlm")
```
]
.pull-right[
<img src="images/part-3-year-built-ac-plot-1.svg" width="100%" style="display: block; margin: auto;" />
]
---
# Interactions
It appears as though the relationship between the year built and the sale price is somewhat _different_ for the two groups.
* When there is no AC, the trend is perhaps flat or slightly decreasing.
* With AC, there is a linear increasing trend or is perhaps slightly quadratic with some outliers at the low end.
```r
mod1 <- lm(log10(Sale_Price) ~ Year_Built + Central_Air, data = ames_train)
mod2 <- lm(log10(Sale_Price) ~ Year_Built + Central_Air + Year_Built:Central_Air, data = ames_train)
anova(mod1, mod2)
```
```
## Analysis of Variance Table
##
## Model 1: log10(Sale_Price) ~ Year_Built + Central_Air
## Model 2: log10(Sale_Price) ~ Year_Built + Central_Air + Year_Built:Central_Air
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 2196 41.349
## 2 2195 40.239 1 1.1106 60.583 1.078e-14 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
```
---
# Interactions in Recipes <img src="images/recipes.png" class="title-hex">
We first create the dummy variables for the qualitative predictor (`Central_Air`) then use a formula to create the interaction using the `:` operator in an additional step:
```r
recipe(Sale_Price ~ Year_Built + Central_Air, data = ames_train) %>%
step_log(Sale_Price) %>%
step_dummy(Central_Air) %>%
step_interact(~ starts_with("Central_Air"):Year_Built) %>%
prep(training = ames_train) %>%
juice() %>%
# select a few rows with different values
slice(153:157)
```
```
## # A tibble: 5 x 4
## Year_Built Sale_Price Central_Air_Y Central_Air_Y_x_Year_Built
## <int> <dbl> <dbl> <dbl>
## 1 1912 12.0 1 1912
## 2 1930 10.9 0 0
## 3 1900 11.8 1 1900
## 4 1959 12.1 1 1959
## 5 1917 11.6 0 0
```
---
layout: false
class: inverse, middle, center
# Recipe and Models
---
# Longitude <img src="images/ggplot2.png" class="title-hex">
.pull-left[
```r
ggplot(ames_train,
aes(x = Longitude, y = Sale_Price)) +
geom_point(alpha = .5) +
geom_smooth(
method = "lm",
formula = y ~ splines::bs(x, 5),
se = FALSE
) +
scale_y_log10()
```
Splines add nonlinear versions of the predictor to a linear model to create smooth and flexible relationships between the predictor and outcome.
This "basis expansion" technique will be seen again in the regression section of the workshop.
]
.pull-right[
<img src="images/part-3-longitude-1.svg" width="100%" style="display: block; margin: auto;" />
]
---
# Latitude <img src="images/ggplot2.png" class="title-hex">
.pull-left[
```r
ggplot(ames_train,
aes(x = Latitude, y = Sale_Price)) +
geom_point(alpha = .5) +
geom_smooth(
method = "lm",
formula = y ~ splines::bs(x, 5),
se = FALSE
) +
scale_y_log10()
```
]
.pull-right[
<img src="images/part-3-latitude-1.svg" width="100%" style="display: block; margin: auto;" />
]
---
# Linear Models Again <img src="images/recipes.png" class="title-hex">
.font80[
Let's add a few extra predictors and some preprocessing.
* Two numeric predictors are very skewed and could use a transformation (`Lot_Area` and `Gr_Liv_Area`).
* We'll add neighborhood in as well and a few other house features.
* Our plots suggests that the coordinates can be helpful but probably require a nonlinear representation. We can add these using _B-splines_ with 5 degrees of freedom. To evaluate this, we will create two versions of the recipe to evaluate this hypothesis.
]
```r
ames_rec <-
recipe(Sale_Price ~ Bldg_Type + Neighborhood + Year_Built +
Gr_Liv_Area + Full_Bath + Year_Sold + Lot_Area +
Central_Air + Longitude + Latitude,
data = ames_train) %>%
step_log(Sale_Price, base = 10) %>%
step_BoxCox(Lot_Area, Gr_Liv_Area) %>%
step_other(Neighborhood, threshold = 0.05) %>%
step_dummy(all_nominal()) %>%
step_interact(~ starts_with("Central_Air"):Year_Built) %>%
step_bs(Longitude, Latitude, options = list(df = 5))
```
---
# Combining the Recipe with a Model <img src="images/recipes.png" class="title-hex"><img src="images/parsnip.png" class="title-hex"><img src="images/broom.png" class="title-hex">
It's pretty simple:
```r
ames_rec <- prep(ames_rec)
fit_lm <-
spec_lm %>%
fit(Sale_Price ~ ., data = juice(ames_rec)) # The recipe puts Sale_Price on the log scale
glance(fit_lm$fit)
```
```
## # A tibble: 1 x 11
## r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual
## <dbl> <dbl> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <int>
## 1 0.804 0.802 0.0793 357. 0 26 2467. -4880. -4726. 13.7 2173
```
```r
holdout_data <- bake(ames_rec, ames_test, all_predictors())
# but let's not do this
# predict(fit_lm, new_data = holdout_data)
```
---
# That Modeling Process Again
.pull-left[
We are
* estimating transformations on some variables,
* making nonlinear features for the geocoding variables, and
* estimating new encodings for some factor variables.
These should definately be included in our overall modeling process.
This will come into play in the next shortly
]
.pull-right[
<img src="images/diagram-packages.svg" width="120%" style="display: block; margin: auto;" />
]
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"ratio": "16:9",
"highlightLanguage": "R",
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function() {
var d = document, 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);
})();</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
}
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.bootcss.com/mathjax/2.7.1/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>