我创建了以下配方来预测我在 R 中的随机森林:
set.seed(123456)
cv_folds <- Data_train %>% vfold_cv(v = 4, strata = Lead_week)
# Create a recipe
rf_mod_recipe <- recipe(Lead_week ~ Jaar + Aantal + Verzekering + Leeftijd + Retentie +
Aantal_proeven + Geslacht + FLG_ADVERTISING + FLG_MAIL +
FLG_PHONE + FLG_EMAIL + Proef1 + Proef2 + Regio +
Month + AC,
data = Data_train) %>%
step_normalize(Leeftijd)
# Specify the recipe
rf_mod <- rand_forest(mtry = tune(), min_n = tune(), trees = 200) %>%
set_mode("regression") %>%
set_engine("ranger", importance = "permutation")
# Create a workflow
rf_mod_workflow <- workflow() %>%
add_model(rf_mod) %>%
add_recipe(rf_mod_recipe)
rf_mod_workflow
# State our error metrics
class_metrics <- metric_set(rmse, mae)
rf_grid <- grid_regular(
mtry(range = c(5, 15)),
min_n(range = c(10, 200)),
levels = 5
)
rf_grid
# Train the model
set.seed(654321)
rf_tune_res <- tune_grid(
rf_mod_workflow,
resamples = cv_folds,
grid = rf_grid,
metrics = class_metrics
)
# Collect the optimal hyperparameters
rf_tune_res %>%
collect_metrics()
# Select the best number of mtry
best_rmse <- select_best(rf_tune_res, "rmse")
rf_final_wf <- finalize_workflow(rf_mod_workflow, best_rmse)
rf_final_wf
# Create a workflow
rf_mod_workflow <- workflow() %>%
add_model(rf_mod) %>%
add_recipe(rf_mod_recipe)
rf_mod_workflow
predict(rf_final_wf, grid) %>%
bind_cols(rf_mod_recipe %>% select(AC)) %>%
ggplot(aes(y = .pred, x = AC)) +
geom_path()
在检索到样本内性能后,我使用工作流来预测保留数据。
# Finalise the workflow
set.seed(56789)
rf_final_fit <- rf_final_wf %>%
last_fit(splits, metrics = class_metrics)
# Collect predictions
summary_rf <- rf_final_fit %>%
collect_predictions()
summary(summary_rf$.pred)
# Collect metrics
rf_final_fit %>%
collect_metrics()
所以我使用交叉验证来微调并最终测试保留数据。但是,如何获得部分依赖图来“打开黑匣子”?