-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpractica-guiada-4.Rmd
198 lines (135 loc) · 3.08 KB
/
practica-guiada-4.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
---
title: "Practica guiada 4 - Random Forest Regressor con Tunning"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Regresión con Random Forest con Tunning
## Dataset
El dataset corresponde a Boston, que se encuentra disponible en Kaggle; una plataforma de competencia de machine learning.
Más info en: https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html
#### Cargo las librerias
```{r warning=FALSE, message=FALSE}
library(tidymodels)
library(tidyverse)
library(magrittr)
library(corrr)
library(MASS) #el dataset se encuentra en esta librería
```
#### Ingreso los datos
```{r}
data(Boston)
```
### División de los datos
Voy a dividir los datos en train y test
```{r}
set.seed(1234)
p_split <- Boston %>%
initial_split(prop = 0.75)
p_train <- training(p_split)
p_test <- testing(p_split)
glimpse(p_train)
```
Los datos de TRAIN voy a dividirlos en 3-folds para hacer validación cruzada v-folds=3
```{r}
p_folds <- vfold_cv(p_train, v=3, repeats = 5)
```
```{r}
p_folds
```
Veamos los splits de validación cruzada, son 3 folds que se repiten 5 veces.
```{r}
p_folds$splits
```
## Datos de TEST
```{r}
head(p_test)
```
### Preprocesamiento de los datos
```{r}
recipe_rf <- p_train %>%
recipe(medv~.) %>%
step_corr(all_predictors()) %>% #elimino las correlaciones
step_center(all_predictors(), -all_outcomes()) %>% #centrado
step_scale(all_predictors(), -all_outcomes()) %>% #escalado
prep()
```
## Modelo de Random Forest
```{r}
rf_tune <- rand_forest(
mtry = tune(),
trees = 1000,
min_n = tune()
) %>%
set_mode("regression") %>%
set_engine("ranger")
```
## Workflow
```{r}
tune_wf <- workflow() %>%
add_recipe(recipe_rf) %>%
add_model(rf_tune)
```
## Entrenamiento del Modelo
```{r}
set.seed(8577)
doParallel::registerDoParallel()
ranger_tune <-tune_grid(tune_wf,
resamples = p_folds,
grid = 11
)
```
```{r}
show_best(ranger_tune, metric = "rmse")
```
```{r}
ranger_tune %>%
collect_metrics() %>%
filter(.metric == "rmse") %>%
dplyr::select(mean, min_n, mtry) %>%
pivot_longer(min_n:mtry,
values_to = "value",
names_to = "parameter"
) %>%
ggplot(aes(value, mean, color = parameter)) +
geom_point(show.legend = FALSE) +
facet_wrap(~parameter, scales = "free_x") +
labs(x = NULL, y = "rmse")
```
```{r}
show_best(ranger_tune, "rmse")
```
```{r}
best_rmse <- select_best(ranger_tune, "rmse")
best_rmse
```
```{r}
final_rf <- finalize_workflow(
tune_wf,
best_rmse
)
final_rf
```
## Predicción en TEST
```{r}
final_res <- last_fit(final_rf, p_split)
collect_metrics(final_res)
```
```{r}
collect_predictions(final_res) %>%
ggplot(aes(medv, .pred)) +
geom_abline(lty = 2, color = "gray50") +
geom_point(alpha = 0.5, color = "midnightblue") +
coord_fixed()
```
## Importancia de variables
```{r message=FALSE, warning=FALSE}
library(vip)
final_random_forest <- finalize_model(rf_tune, best_rmse)
final_random_forest %>%
set_engine("ranger", importance = "permutation") %>%
fit(medv ~ .,
data = p_train) %>%
vip::vip(geom = "point")
```