Modellazione con tidymodels in R
David Svancer
Data Scientist
Prevedere hwy usando cty come predittore
$$hwy = \beta_{0} + \beta_{1} cty$$
Parametri del modello
Prevedere hwy usando cty come predittore
$$hwy = \beta_{0} + \beta_{1} cty$$
Parametri del modello
Parametri stimati dai dati di training
$$\small hwy = 0.77 + 1.35(cty)$$
Formule del modello in parsnip
Forma generale
output ~ predictor_1 + predictor_2 + ...
Notazione abbreviata
output ~ .
Prevedere hwy usando cty come variabile predittore
hwy ~ cty
Sintassi unificata per specificare modelli in R
Specifica il tipo di modello
Specifica il motore
Specifica la modalità
Definisci la specifica del modello con parsnip
linear_reg()
Passa lm_model alla funzione fit()
data da usare per l'addestramento
lm_model <- linear_reg() %>%set_engine('lm') %>%set_mode('regression')
lm_fit <- lm_model %>%
fit(hwy ~ cty, data = mpg_training)
La funzione tidy()
parsnip addestratoterm ed estimate danno i parametri stimati
tidy(lm_fit)
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.769 0.528 1.46 1.47e- 1
2 cty 1.35 0.0305 44.2 6.32e-97
Passa il modello parsnip addestrato alla funzione predict()
new_data indica il dataset su cui prevedere i nuovi valori
Output standardizzato di predict()
new_data.predhwy_predictions <- lm_fit %>% predict(new_data = mpg_test)hwy_predictions
# A tibble: 57 x 1
.pred
<dbl>
1 25.0
2 27.7
3 25.0
4 25.0
5 22.3
# ... with 47 more rows
La funzione bind_cols()
Passi
hwy e cty da mpg_testbind_cols() e aggiungi la colonna delle previsionimpg_test_results <- mpg_test %>% select(hwy, cty) %>%bind_cols(hwy_predictions) mpg_test_results
# A tibble: 57 x 3
hwy cty .pred
<int> <int> <dbl>
1 29 18 25.0
2 31 20 27.7
3 27 18 25.0
4 26 18 25.0
5 25 16 22.3
# ... with 47 more rows
Modellazione con tidymodels in R