forked from dlab-berkeley/R-Machine-Learning-Legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine-learning-in-r.Rmd
2291 lines (1525 loc) · 63.9 KB
/
machine-learning-in-r.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Machine Learning in R"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
output: bookdown::gitbook
documentclass: book
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
github-repo: dlab-berkeley/Machine-Learning-with-tidymodels
description: "D-Lab's Machine Learning with Tidymodels Workshop"
---
# Preface
## Prereqs
<!--chapter:end:index.Rmd-->
# Overview
## Package installation
The following packages are required to run the code in this workshop:
```{r}
# Install packages
if (!require("pacman")) install.packages("pacman")
install.packages("tidyverse")
pacman::p_load(# Tidymodels framework
tidymodels,
# Tidyverse packages including dplyr and ggplot2
tidyverse,
# Algorithms
glmnet, ranger, rpart, xgboost, pvclust, mclust,
# Visualization
rpart.plot, vip, ape, corrr, GGally,
# Machine learning frameworks
caret, SuperLearner,
# R utility packages
remotes, here, glue, patchwork, doParallel,
# Import/export of any filetype.
rio,
# Misc
pROC, bookdown)
# Install packages not on CRAN or with old version on CRAN.
remotes::install_github("ck37/ck37r")
# Hide the many messages and possible warnings from loading all these packages.
suppressMessages(suppressWarnings({
library(ape) # Cluster visualizations
library(caret) # createDataPartition creates a stratified random split
library(ck37r) # impute_missing_values, standardize, SuperLearner helpers
library(glmnet) # Lasso
library(mclust) # Model-based clustering
library(PCAmixdata) # PCA
library(pROC) # Compute and plot AUC
library(pvclust) # Dendrograms with p-values
library(ranger) # Random forest algorithm
library(remotes) # Allows installing packages from github
library(rio) # Import/export for any filetype.
library(rpart) # Decision tree algorithm
library(rpart.plot) # Decision tree plotting
library(SuperLearner) # Ensemble methods
library(xgboost) # Boosting method
library(vip) # Variable importance plots
}))
```
<!--chapter:end:01-overview.Rmd-->
# Preprocessing
## Load packages
Explicitly load the packages that we need for this analysis.
```{r}
library(rio) # painless data import and export
library(tidyverse) # tidyverse packages
library(tidymodels) # tidymodels framework
library(here) # reproducible way to find files
```
## Load the data
Load the heart disease dataset.
```{r load_data}
# Load the heart disease dataset using import() from the rio package.
data_original <- import(here("data-raw", "heart.csv"))
# Preserve the original copy
data <- data_original
# Inspect
glimpse(data)
class(data)
```
## Read background information and variable descriptions
https://archive.ics.uci.edu/ml/datasets/heart+Disease
## Quick overviews on machine learning
- In this workshop, we will cover classical and ensemble machine learning models.
![Based on https://vas3k.com/blog/machine_learning/](https://i.vas3k.ru/7vz.jpg)
- As for the first step, we will focus on supervised machine learning (regression and classification).
![Based on https://vas3k.com/blog/machine_learning/](https://i.vas3k.ru/7w1.jpg)
## Machine learning workflow
- Before diving into the specific problem (i.e., preprocessing), let's take a step back and think about the big picture.
![A schematic for the typical modeling process (from Tidy Modeling with R)](https://www.tmwr.org/premade/modeling-process.svg)
- Preprocessing happens between the EDA and the initial feature engineering.
![Based on https://vas3k.com/blog/machine_learning/](https://i.vas3k.ru/7r8.jpg)
- Data (e.g., text, image, and video) and Features (the dimensions of a numeric vector) are different!
## Why taking a tidyverse approach to machine learning?
### Benefits
- Readable code (e.g., `dplyr` is quite intuitive even for beginning R users.)
- Reusable data structures (e.g., `broom` package helps to visualize model outputs, such as p-value, using `ggplot2`)
- Extendable code (e.g., you can easily build a machine learning pipeline by using the pipe operator (`%>%`) and the `purrr` package)
### tidymodels
- Like `tidyverse`, `tidymodels` is a collection of packages.
- [`rsample`](https://rsample.tidymodels.org/): for data splitting
- [`recipes`](https://recipes.tidymodels.org/index.html): for pre-processing
- [`parsnip`](https://www.tidyverse.org/blog/2018/11/parsnip-0-0-1/): for model building
- [`tune`](https://github.com/tidymodels/tune): parameter tuning
- [`yardstick`](https://github.com/tidymodels/yardstick): for model evaluations
- [`workflows`](https://github.com/tidymodels/workflows): for bundling a pieplne that bundles together pre-processing, modeling, and post-processing requests
## Data preprocessing
Data peprocessing is an integral first step in machine learning workflows. Because different algorithms sometimes require the moving parts to be coded in slightly different ways, always make sure you research the algorithm you want to implement so that you properly setup your $y$ and $x$ variables and split your data appropriately.
> NOTE: also, use the `save` function to save your variables of interest. In the remaining walkthroughs, we will use the `load` function to load the relevant variables.
The list of the preprocessing steps draws on the vignette of the [`parsnip`](https://www.tidymodels.org/find/parsnip/) package.
- dummy: Also called one-hot encoding
- zero variance: Removing columns (or features) with a single unique value
- impute: Imputing missing values
- decorrelate: Mitigating correlated predictors (e.g., principal component analysis)
- normalize: Centering and/or scaling predictors (e.g., log scaling)
- transform: Making predictors symmetric
In this workshop, we focus on two preprocessing tasks.
### Task 1: What is one-hot encoding?
One additional preprocessing aspect to consider: datasets that contain factor (categorical) features should typically be expanded out into numeric indicators (this is often referred to as [one-hot encoding](https://hackernoon.com/what-is-one-hot-encoding-why-and-when-do-you-have-to-use-it-e3c6186d008f). You can do this manually with the `model.matrix` R function. This makes it easier to code a variety of algorithms to a dataset as many algorithms handle factors poorly (decision trees being the main exception). Doing this manually is always good practice. In general however, functions like `lm` will do this for you automatically.
- Since the "ca", "cp", "slope", and "thal" features are currently integer type, convert them to factors. The other relevant variables are either continuous or are already indicators (just 1's and 0's).
```{r}
# Turn selected numeric variables into factor variables
data <- data %>%
mutate(across(c("sex", "ca", "cp", "slope", "thal"), as.factor))
```
### Task 2: Handling missing data
Missing values need to be handled somehow. Listwise deletion (deleting any row with at least one missing value) is common but this method throws out a lot of useful information. Many advocate for mean imputation, but arithmetic means are sensitive to outliers. Still, others advocate for Chained Equation/Bayesian/Expectation Maximization imputation (e.g., the [mice](https://www.jstatsoft.org/article/view/v045i03/v45i03.pdf) and [Amelia II](https://gking.harvard.edu/amelia) R packages). K-nearest neighbor imputation can also be useful but median imputation is used in this workshop.
However, you will want to learn about [Generalized Low Rank Models](https://stanford.edu/~boyd/papers/pdf/glrm.pdf) for missing data imputation in your research. See the `impute_missing_values` function from the ck37r package to learn more - you might need to install an h2o dependency.
First, count the number of missing values across variables in our dataset.
- Using base R
```{r review_missingness base}
# Using base R; The output is a numeric vector.
colSums(is.na(data))
class(colSums(is.na(data)))
```
- Using tidyverse
```{r review_missingness tidyverse}
# Using tidyverse; The output is a dataframe.
# Option 1 and Option 2 produce same outputs.
map_df(data, ~ is.na(.) %>% sum()) # Option 1
map_df(data,
function(x){is.na(x) %>% sum()}) %>% # Option 2
as_tibble()
```
We have no missing values, so let's introduce a few to the "oldpeak" feature for this example to see how it works:
```{r}
# Add five missing values added to oldpeak in row numbers 50, 100, 150, 200, 250
data$oldpeak[c(50, 100, 150, 200, 250)] <- NA
```
There are now 5 missing values in the "oldpeak" feature.
```{r}
# Check the number of missing values
data %>%
map_df(~is.na(.) %>% sum())
# Check the rate of missing values
data %>%
map_df(~is.na(.) %>% mean())
```
## Preprocessing workflow
![Art by Allison Horst](https://education.rstudio.com/blog/2020/02/conf20-intro-ml/recipes.png)
- Step 1: `recipe()` defines target and predictor variables (ingredients).
- Step 2: `step_*()` defines preprocessing steps to be taken (recipe).
- Step 3: `prep()` prepares a dataset to base each step on.
- Step 4: `bake()` applies the pre-processing steps to your datasets.
**Useful references**
- Alison Hill, ["Introduction Machine Learning with the Tidyverse"](https://education.rstudio.com/blog/2020/02/conf20-intro-ml/)
- Rebecca Barter, ["Using the recipes package for easy pre-processing"](http://www.rebeccabarter.com/blog/2019-06-06_pre_processing/)
## Regressioin setup
Splitting data into training and test subsets is a fundamental step in machine learning. Usually, the marjority portion of the original dataset is partitioned to the training set, where the algorithms learn the relationships between the $x$ feature predictors and the $y$ outcome variable. Then, these models are given new data (the test set) to see how well they perform on data they have not yet seen.
Since **age** is a **continuous variable** and will be **the outcome** for the OLS and lasso regressions, we will not perform a stratified random split like we will for the classification tasks (see below). Instead, [let's randomly assign](https://stackoverflow.com/questions/17200114/how-to-split-data-into-training-testing-sets-using-sample-function) 70% of the `age` values to the training set and the remaining 30% to the test set.
### Outcome variable
```{r}
# Continuous variable
data$age %>% unique()
```
### Data splitting using random sampling
Take the simple approach to data splitting and divide our data into training and test sets; 70% of the data will be assigned to the training set and the remaining 30% will be assigned to the holdout, or test, set.
```{r}
# for reproducibility
set.seed(1234)
# split
split_reg <- initial_split(data, prop = 0.7)
# training set
raw_train_x_reg <- training(split_reg)
# test set
raw_test_x_reg <- testing(split_reg)
```
### recipe
```{r}
# Regression recipe
rec_reg <- raw_train_x_reg %>%
# Define the outcome variable
recipe(age ~ .) %>%
# Median impute oldpeak column
step_medianimpute(oldpeak) %>%
# Expand "sex", "ca", "cp", "slope", and "thal" features out into dummy variables (indicators).
step_dummy(c("sex", "ca", "cp", "slope", "thal"))
# Prepare a dataset to base each step on
prep_reg <- rec_reg %>% prep(retain = TRUE)
```
```{r}
# x features
train_x_reg <- juice(prep_reg, all_predictors())
test_x_reg <- bake(prep_reg, raw_test_x_reg, all_predictors())
# y variables
train_y_reg <- juice(prep_reg, all_outcomes())$age %>% as.numeric()
test_y_reg <- bake(prep_reg, raw_test_x_reg, all_outcomes())$age %>% as.numeric()
# Checks
names(train_x_reg) # Make sure there's no age variable!
class(train_y_reg) # Make sure this is a continuous variable!
```
- Note that other imputation methods are also available. Fancier methods tend to take longer time than simpler ones such as mean, median, or mode imputation.
```{r}
grep("impute", ls("package:recipes"), value = TRUE)
```
- You can also create your own `step_` functions. For more information, see [tidymodels.org](https://www.tidymodels.org/learn/develop/recipes/).
- Now that the data have been imputed and properly converted, we can assign the regression outcome variable (`age`) to its own vector for the lasso **REGRESSION task**. Remember that lasso can also perform classification as well.
## Classification setup
Assign the outcome variable to its own vector for the decision tree, random forest, gradient boosted tree, and SuperLearner ensemble **CLASSIFICATION tasks**. However, keep in mind that these algorithms can also perform regression!
This time however, **"target"** will by our y **outcome variable** (1 = person has heart disease, 0 = person does not have heart disease) - the others will be our x features.
### Outcome variable
```{r}
## Categorical variable
data$target %>% unique()
```
### Data splitting using stratified random sampling
For classification, we then use [stratified random sampling](https://stats.stackexchange.com/questions/250273/benefits-of-stratified-vs-random-sampling-for-generating-training-data-in-classi) to divide our data into training and test sets; 70% of the data will be assigned to the training set and the remaining 30% will be assigned to the holdout, or test, set.
```{r}
# split
split_class <- initial_split(data %>%
mutate(target = as.factor(target)),
prop = 0.7,
strata = target)
# training set
raw_train_x_class <- training(split_class)
# testing set
raw_test_x_class <- testing(split_class)
```
### recipe
```{r}
# Classification recipe
rec_class <- raw_train_x_class %>%
# Define the outcome variable
recipe(target ~ .) %>%
# Median impute oldpeak column
step_medianimpute(oldpeak) %>%
# Expand "sex", "ca", "cp", "slope", and "thal" features out into dummy variables (indicators).
step_normalize(age) %>%
step_dummy(c("sex", "ca", "cp", "slope", "thal"))
# Prepare a dataset to base each step on
prep_class <- rec_class %>%prep(retain = TRUE)
```
```{r}
# x features
train_x_class <- juice(prep_class, all_predictors())
test_x_class <- bake(prep_class, raw_test_x_class, all_predictors())
# y variables
train_y_class <- juice(prep_class, all_outcomes())$target %>% as.factor()
test_y_class <- bake(prep_class, raw_test_x_class, all_outcomes())$target %>% as.factor()
# Checks
names(train_x_class) # Make sure there's no target variable!
class(train_y_class) # Make sure this is a factor variable!
```
### Save our preprocessed data
We save our preprocessed data into an RData file so that we can easily load it the later files.
```{r save_data}
save(data, data_original, # data
split_reg, split_class, # splits
rec_reg, rec_class, # recipes
prep_reg, prep_class, # preps
train_x_reg, train_y_reg, # train sets
test_x_reg, test_y_reg, # test sets
train_x_class, train_y_class, # train sets
test_x_class, test_y_class, # test
file = here("data", "preprocessed.RData"))
```
<!--chapter:end:02-preprocessing.Rmd-->
# OLS and lasso
## Load packages
```{r}
library(glmnet)
library(rio) # painless data import and export
library(tidyverse) # tidyverse packages
library(tidymodels) # tidymodels framework
library(here) # reproducible way to find files
library(glue) # glue strings and objects
library(vip) # variable importance
source(here("functions", "utils.R"))
theme_set(theme_minimal())
```
## Load data
Load `train_x_reg`, `train_y_reg`, `test_x_reg`, and `test_y_reg` variables we defined in 02-preprocessing.Rmd for the OLS and Lasso *regression* tasks.
```{r}
# Objects: task_reg, task_class
load(here("data", "preprocessed.RData"))
```
## Overview
* LASSO = sets Beta coefficients of unrelated (to Y) predictors to zero
* RIDGE = sets Beta coefficients of unrelated (to Y) predictors NEAR ZERO but does not remove them
* ELASTICNET = a combination of LASSO and RIDGE
Review "Challenge 0" in the Challenges folder for a useful review of how OLS regression works and [see the yhat blog](http://blog.yhat.com/posts/r-lm-summary.html) for help interpreting its output.
Linear regression is a useful introduction to machine learning, but in your research you might be faced with warning messages after `predict()` about the [rank of your matrix](https://stats.stackexchange.com/questions/35071/what-is-rank-deficiency-and-how-to-deal-with-it).
The lasso is useful to try and remove some of the non-associated features from the model. Because glmnet expects a matrix of predictors, use `as.matrix` to convert it from a data frame to a matrix. (You don't need to worry about this, if you use `tidymodels`.)
Be sure to [read the glmnet vignette](https://web.stanford.edu/~hastie/Papers/Glmnet_Vignette.pdf)
## Non-tidy
### OLS
Below is an refresher of ordinary least squares linear (OLS) regression that predicts age using the other variables as predictors.
```{r}
# Fit the regression model; lm() will automatically add a temporary intercept column
ols <- lm(train_y_reg ~ ., data = train_x_reg)
# Predict outcome for the test data
ols_predicted <- predict(ols, test_x_reg)
# Root mean-squared error
sqrt(mean((test_y_reg - ols_predicted )^2))
```
### Lasso
```{r}
# Fit the lasso model
lasso <- cv.glmnet(x = as.matrix(train_x_reg),
y = train_y_reg,
family = "gaussian",
alpha = 1)
lasso$lambda.min
# Predict outcome for the test data
lasso_predicted <- predict(lasso, newx = as.matrix(test_x_reg),
s = 0.1) # Tuning parameter; An arbitrary number not optimized
# Calculate root mean-squared error
sqrt(mean((lasso_predicted - test_y_reg)^2))
```
## tidymodels
#### parsnip
- Build models
1. Specify a model
2. Specify an engine
3. Specify a mode
```{r}
# OLS spec
ols_spec <- linear_reg() %>% # Specify a model
set_engine("lm") %>% # Specify an engine: lm, glmnet, stan, keras, spark
set_mode("regression") # Declare a mode: regression or classification
# Lasso spec
lasso_spec <- linear_reg(penalty = 0.1, # tuning parameter
mixture = 1) %>% # 1 = lasso, 0 = ridge
set_engine("glmnet") %>%
set_mode("regression")
# If you don't understand parsnip arguments
lasso_spec %>% translate() # See the documentation
```
- Fit models
```{r}
ols_fit <- ols_spec %>%
fit_xy(x = train_x_reg, y= train_y_reg)
# fit(train_y_reg ~ ., train_x_reg) # When you data are not preprocessed
lasso_fit <- lasso_spec %>%
fit_xy(x = train_x_reg, y= train_y_reg)
```
#### yardstick
- Visualize model fits
```{r}
map2(list(ols_fit, lasso_fit), c("OLS", "Lasso"), visualize_fit)
```
- Let's formally test prediction performance.
**Metrics**
- `rmse`: Root mean squared error (the smaller the better)
- `mae`: Mean absolute error (the smaller the better)
- `rsq`: R squared (the larger the better)
- To learn more about other metrics, check out the yardstick package [references](https://yardstick.tidymodels.org/reference/index.html).
```{r}
# Define performance metrics
metrics <- yardstick::metric_set(rmse, mae, rsq)
# Evaluate many models
evals <- purrr::map(list(ols_fit, lasso_fit), evaluate_reg) %>%
reduce(bind_rows) %>%
mutate(type = rep(c("OLS", "Lasso"), each = 3))
# Visualize the test results
evals %>%
ggplot(aes(x = fct_reorder(type, .estimate), y = .estimate)) +
geom_point() +
labs(x = "Model",
y = "Estimate") +
facet_wrap(~glue("{toupper(.metric)}"), scales = "free_y")
```
- For more information, read [Tidy Modeling with R](https://www.tmwr.org/) by Max Kuhn and Julia Silge.
#### tune
##### tune ingredients
```{r}
# tune() = placeholder
tune_spec <- linear_reg(penalty = tune(), # tuning parameter
mixture = 1) %>% # 1 = lasso, 0 = ridge
set_engine("glmnet") %>%
set_mode("regression")
tune_spec
# penalty() searches 50 possible combinations
lambda_grid <- grid_regular(penalty(), levels = 50)
# 10-fold cross-validation
set.seed(1234) # for reproducibility
rec_folds <- vfold_cv(train_x_reg %>% bind_cols(tibble(age = train_y_reg)))
```
##### Add these elements to a workflow
```{r}
# Workflow
rec_wf <- workflow() %>%
add_model(tune_spec) %>%
add_formula(age~.)
# Tuning results
rec_res <- rec_wf %>%
tune_grid(
resamples = rec_folds,
grid = lambda_grid
)
```
##### Visualize
- Visualize the distribution of log(lambda) vs mean-squared error.
```{r}
# Visualize
rec_res %>%
collect_metrics() %>%
ggplot(aes(penalty, mean, col = .metric)) +
geom_errorbar(aes(
ymin = mean - std_err,
ymax = mean + std_err
),
alpha = 0.3
) +
geom_line(size = 2) +
scale_x_log10() +
labs(x = "log(lambda)") +
facet_wrap(~glue("{toupper(.metric)}"),
scales = "free",
nrow = 2) +
theme(legend.position = "none")
```
> NOTE: when log(lambda) is equal to 0 that means lambda is equal to 1. In this graph, the far right side is overpenalized, as the model is emphasizing the beta coefficients being small. As log(lambda) becomes increasingly negative, lambda is correspondingly closer to zero and we are approaching the OLS solution.
- Show the lambda that results in the minimum estimated mean-squared error (MSE):
```{r}
top_rmse <- show_best(rec_res, metric = "rmse")
best_rmse <- select_best(rec_res, metric = "rmse")
best_rmse
glue('The RMSE of the intiail model is
{evals %>%
filter(type == "Lasso", .metric == "rmse") %>%
select(.estimate) %>%
round(2)}')
glue('The RMSE of the tuned model is {rec_res %>%
collect_metrics() %>%
filter(.metric == "rmse") %>%
arrange(mean) %>%
dplyr::slice(1) %>%
select(mean) %>%
round(2)}')
```
- Finalize your workflow and visualize [variable importance](https://koalaverse.github.io/vip/articles/vip.html)
```{r}
finalize_lasso <- rec_wf %>%
finalize_workflow(best_rmse)
finalize_lasso %>%
fit(train_x_reg %>% bind_cols(tibble(age = train_y_reg))) %>%
pull_workflow_fit() %>%
vip::vip()
```
##### Test fit
- Apply the tuned model to the test dataset
```{r}
test_fit <- finalize_lasso %>%
fit(test_x_reg %>% bind_cols(tibble(age = test_y_reg)))
evaluate_reg(test_fit)
```
TBD: Challenge 1
<!--chapter:end:03-lasso.Rmd-->
# Decision Trees
## Load packages
```{r}
library(rpart)
library(rpart.plot)
library(rio) # painless data import and export
library(tidyverse) # tidyverse packages
library(tidymodels) # tidymodels framework
library(here) # reproducible way to find files
library(glue) # glue strings and objects
library(patchwork) # arrange ggplots
library(doParallel) # parallel processing
source(here("functions", "utils.R"))
theme_set(theme_minimal())
```
## Load data
Load `train_x_class`, `train_y_class`, `test_x_class`, and `test_y_class` variables we defined in 02-preprocessing.Rmd for this *classification* task.
```{r}
# Objects: task_reg, task_class
load(here("data", "preprocessed.RData"))
```
## Overview
Decision trees are recursive partitioning methods that divide the predictor spaces into simpler regions and can be visualized in a tree-like structure. They attempt to classify data by dividing it into subsets according to a Y output variable and based on some predictors.
Let's see how a decision tree classifies if a person suffers from heart disease (`target` = 1) or not (`target` = 0).
## Non-tidy
### Fit model
```{r}
set.seed(3)
tree <- rpart::rpart(train_y_class ~ ., data = train_x_class,
# Use method = "anova" for a continuous outcome.
method = "class",
# Can use "gini" for gini coefficient.
parms = list(split = "information"))
# https://stackoverflow.com/questions/4553947/decision-tree-on-information-gain
```
### Investigate
- Here is the text-based display of the decision tree. Yikes! :^(
```{r}
print(tree)
```
Although interpreting the text can be intimidating, a decision tree's main strength is its tree-like plot, which is much easier to interpret.
```{r plot_tree}
rpart.plot::rpart.plot(tree)
```
We can also look inside of `tree` to see what we can unpack. "variable.importance" is one we should check out!
```{r}
names(tree)
tree$variable.importance
```
## Tidy models
### parsnip
- Build a model
1. Specify a model
2. Specify an engine
3. Specify a mode
```{r}
# workflow
tree_wf <- workflow() %>% add_formula(target~.)
# spec
tree_spec <- decision_tree(
# Mode
mode = "classification",
# Tuning parameters
cost_complexity = NULL,
tree_depth = NULL) %>%
set_engine("rpart") # rpart, c5.0, spark
tree_wf <- tree_wf %>% add_model(tree_spec)
```
- Fit a model
```{r}
tree_fit <- tree_wf %>% fit(train_x_class %>% bind_cols(tibble(target = train_y_class)))
```
### yardstick
- Let's formally test prediction performance.
**Metrics**
- `accuracy`: The proportion of the data predicted correctly
- `precision`: Positive predictive value
- `recall` (specificity): True positive rate (e.g., healthy people really healthy)
![From wikipedia](https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Precisionrecall.svg/525px-Precisionrecall.svg.png)
- To learn more about other metrics, check out the yardstick package [references](https://yardstick.tidymodels.org/reference/index.html).
```{r}
# Define performance metrics
metrics <- yardstick::metric_set(accuracy, precision, recall)
# Visualize
tree_fit_viz_metr <- visualize_class_eval(tree_fit)
tree_fit_viz_metr
tree_fit_viz_mat <- visualize_class_conf(tree_fit)
tree_fit_viz_mat
```
### tune
#### tune ingredients
In decision trees the main hyperparameter (configuration setting) is the **complexity parameter** (CP), but the name is a little counterintuitive; a high CP results in a simple decision tree with few splits, whereas a low CP results in a larger decision tree with many splits.
The other related hyperparameter is `tree_depth`.
```{r}
tune_spec <-
decision_tree(
cost_complexity = tune(),
tree_depth = tune(),
mode = "classification"
) %>%
set_engine("rpart")
tree_grid <- grid_regular(cost_complexity(),
tree_depth(),
levels = 5) # 2 parameters -> 5*5 = 25 combinations
tree_grid %>%
count(tree_depth)
# 10-fold cross-validation
set.seed(1234) # for reproducibility
tree_folds <- vfold_cv(train_x_class %>% bind_cols(tibble(target = train_y_class)),
strata = target)
```
#### Add these elements to a workflow
```{r}
# Update workflow
tree_wf <- tree_wf %>% update_model(tune_spec)
cl <- makeCluster(4)
registerDoParallel(cl)
# Tuning results
tree_res <- tree_wf %>%
tune_grid(
resamples = tree_folds,
grid = tree_grid,
metrics = metrics
)
```
#### Visualize
- The following plot draws on the [vignette](https://www.tidymodels.org/start/tuning/) of the tidymodels package.
```{r}
tree_res %>%
collect_metrics() %>%
mutate(tree_depth = factor(tree_depth)) %>%
ggplot(aes(cost_complexity, mean, col = .metric)) +
geom_point(size = 3) +
# Subplots
facet_wrap(~ tree_depth,
scales = "free",
nrow = 2) +
# Log scale x
scale_x_log10(labels = scales::label_number()) +
# Discrete color scale
scale_color_viridis_d(option = "plasma", begin = .9, end = 0) +
labs(x = "Cost complexity",
col = "Tree depth",
y = NULL) +
coord_flip()
```
```{r}
# Optimal parameter
best_tree <- select_best(tree_res, "recall")
best_tree
# Add the parameter to the workflow
finalize_tree <- tree_wf %>%
finalize_workflow(best_tree)
```
```{r}
tree_fit_tuned <- finalize_tree %>%
fit(train_x_class %>% bind_cols(tibble(target = train_y_class)))
# Metrics
(tree_fit_viz_metr + labs(title = "Non-tuned")) / (visualize_class_eval(tree_fit_tuned) + labs(title = "Tuned"))
# Confusion matrix
(tree_fit_viz_mat + labs(title = "Non-tuned")) / (visualize_class_conf(tree_fit_tuned) + labs(title = "Tuned"))
```
- Visualize variable importance
```{r}
tree_fit_tuned %>%
pull_workflow_fit() %>%
vip::vip()
```
#### Test fit