- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
概览
我正在按照教程(见下文)从袋装树、随机森林、提升树和一般线性模型中找到最适合的模型。
教程(参见下面的示例)
https://bcullen.rbind.io/post/2020-06-02-tidymodels-decision-tree-learning-in-r/
问题
在这种情况下,我想进一步探索数据,并为我在随机森林模型中的数据可视化最重要的预测变量(见下图)。
我的数据框称为FID,随机森林模型中的预测变量涉及:
因变量是频率(数字)
当我尝试运行绘图以可视化最重要的预测变量时,我不断收到此错误消息:-
Error: Problem with `mutate()` input `oob_rmse`.
x non-numeric argument to mathematical function
ℹ Input `oob_rmse` is `map_dbl(fit, ~sqrt(.x$prediction.error))`.
Run `rlang::last_error()` to see where the error occurred.
Called from: signal_abort(cnd)
如果有人对如何修复错误消息有任何建议,我将不胜感激。
提前致谢
如何从教程中的 R 代码生成绘图的示例
可视化模型
绘制以显示教程中 R 代码中最重要的预测变量
我的 R 代码
##Open libraries
library(tidymodels)
library(parsnip)
library(forcats)
library(ranger)
library(baguette)
###########################################################
#split this single dataset into two: a training set and a testing set
data_split <- initial_split(FID)
# Create data frames for the two sets:
train_data <- training(data_split)
test_data <- testing(data_split)
# resample the data with 10-fold cross-validation (10-fold by default)
cv <- vfold_cv(train_data, v=3)
###########################################################
##Produce the recipe
rec <- recipe(Frequency ~ ., data = FID) %>%
step_nzv(all_predictors(), freq_cut = 0, unique_cut = 0) %>% # remove variables with zero variances
step_novel(all_nominal()) %>% # prepares test data to handle previously unseen factor levels
step_medianimpute(all_numeric(), -all_outcomes(), -has_role("id vars")) %>% # replaces missing numeric observations with the median
step_dummy(all_nominal(), -has_role("id vars")) # dummy codes categorical variables
###################################################################################
###################################################
##Random forests
###################################################
mod_rf <-rand_forest(trees = 1e3) %>%
set_engine("ranger",
num.threads = parallel::detectCores(),
importance = "permutation",
verbose = TRUE) %>%
set_mode("regression")
##Create Workflow
wflow_rf <- workflow() %>%
add_model(mod_rf) %>%
add_recipe(rec)
##Fit the model
plan(multisession)
fit_rf<-fit_resamples(
wflow_rf,
cv,
metrics = metric_set(rmse, rsq),
control = control_resamples(save_pred = TRUE,
extract = function(x) extract_model(x)))
# extract roots
rf_tree_roots <- function(x){
map_chr(1:1000,
~ranger::treeInfo(x, tree = .)[1, "splitvarName"])
}
rf_roots <- function(x){
x %>%
dplyr::select(.extracts) %>%
unnest(cols = c(.extracts)) %>%
dplyr::mutate(fit = map(.extracts,
~.x$fit$fit$fit),
oob_rmse = map_dbl(fit,
~sqrt(.x$prediction.error)),
roots = map(fit,
~rf_tree_roots(.))
) %>%
dplyr::select(roots) %>%
unnest(cols = c(roots))
}
##Open a plotting window
dev.new()
# plot
rf_roots(fit_rf) %>%
group_by(roots) %>%
count() %>%
dplyr::arrange(desc(n)) %>%
dplyr::filter(n > 75) %>%
ggplot(aes(fct_reorder(roots, n), n)) +
geom_col() +
coord_flip() +
labs(x = "root", y = "count")
##Error message
Error: Problem with `mutate()` input `oob_rmse`.
x non-numeric argument to mathematical function
ℹ Input `oob_rmse` is `map_dbl(fit, ~sqrt(.x$prediction.error))`.
Run `rlang::last_error()` to see where the error occurred.
Called from: signal_abort(cnd)
数据框 - FID
structure(list(Year = c(2015, 2015, 2015, 2015, 2015, 2015, 2015,
2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 2017, 2017, 2017,
2017, 2017, 2017, 2017, 2017, 2017, 2017), Month = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L), .Label = c("January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December"), class = "factor"), Frequency = c(36,
28, 39, 46, 5, 0, 0, 22, 10, 15, 8, 33, 33, 29, 31, 23, 8, 9,
7, 40, 41, 41, 30, 30, 44, 37, 41, 42, 20, 0, 7, 27, 35, 27,
43, 38), Days = c(31, 28, 31, 30, 6, 0, 0, 29, 15,
29, 29, 31, 31, 29, 30, 30, 7, 0, 7, 30, 30, 31, 30, 27, 31,
28, 30, 30, 21, 0, 7, 26, 29, 27, 29, 29)), row.names = c(NA,
-36L), class = "data.frame")
最佳答案
它不会正确提取错误,如果您查看包含所有模型的小标题:
fit_rf$.extracts
[[1]]
# A tibble: 1 x 1
.extracts
<list>
1 <ranger>
它嵌入在列表或列表中,但没有名称:
names(fit_rf$.extracts[[1]][[1]])
NULL
因此这部分将失败:
map(fit_rf$.extracts,~.x$fit$fit$fit)
如果您查看第一个 unnest 之后的结构,这已经是合适的:
fit_rf %>% dplyr::select(.extracts) %>% unnest(cols = c(.extracts))
# A tibble: 3 x 1
.extracts
<list>
1 <ranger>
2 <ranger>
3 <ranger>
所以我们可以这样做:
rf_roots <- function(x){
x %>%
select(.extracts) %>%
unnest(cols = c(.extracts)) %>%
mutate(oob_rmse = map_dbl(.extracts,
~sqrt(.x$prediction.error)),
roots = map(.extracts,
~rf_tree_roots(.))
) %>%
dplyr::select(roots) %>%
unnest(cols = c(roots))
}
这现在可以工作了:
rf_roots(fit_rf)
# A tibble: 3,000 x 1
roots
<chr>
1 Month_August
2 Year
3 Month_July
4 Month_September
5 Month_December
6 Month_March
7 Month_July
8 Month_September
9 Month_December
10 Days
附加组件:如果目标是获取每个模型中每棵树的根变量,可以简单地执行:
root_vars = unnest(fit_rf,.extracts) %>%
pull(.extracts) %>%
map(rf_tree_roots)
或以 R 为基数:
lapply(fit_rf$.extracts,function(i)rf_tree_roots(i[[1]][[1]]))
你可以很容易地取消列出它来制作条形图。
关于r - Tidymodels 包 : Visualising a random forest model using ggplot() to show the most important predictors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64939433/
我有以下代码,我在其中对不同的 mtry 和 min_n 进行了一些网格搜索。我知道如何提取精度最高的参数(参见第二个代码框)。如何提取训练数据集中每个特征的重要性?我在网上找到的指南显示了如何使用“
我正在使用 tidymodels创建随机森林预测。我的测试数据包含训练数据中不存在的新因子水平,这会导致错误: 1: Novel levels found in column 'Siblings':
我最近一直在使用 tidymodels 来运行模型并选择最能满足某些目标函数的参数。例如对 mtcars 数据使用假设回归 ( using the regression examples from t
有没有办法在 tidy 模型中获取逻辑回归的标准误差和 p 值? 我可以通过下面的代码获得系数..但我想计算每个特征的优势比,我还需要标准误差.. glm.fit % set_engine(eng
数据集可以在这里找到: https://www.kaggle.com/mlg-ulb/creditcardfraud 我正在尝试使用 tidymodels 在此数据集上运行具有 5 折交叉验证的游侠。
通过 tidymodels 和 R 中的 vip 包,我计算了变量重要性。就代码而言,它看起来像这样: rf_vi_fit %>% pull_workflow_fit() %>% vip(geom =
我使用 tidymodels 在 R 中训练和测试了一个随机森林模型。现在我想使用相同的模型来预测一个全新的数据集(不是训练数据集)。 例如 Julia silge,在这篇博文中解释了训练、测试和评估
下面的代码工作正常,没有我所知道的错误,但我想添加更多内容。 我想补充的两件事是: 1 - 模型对训练数据对最终图的预测。我想在适合训练数据的模型上运行 collect_predictions()。
我尝试使用 tidymodels 来调整配方和模型参数的工作流程。调整单个工作流时没有问题。但是当使用多个工作流调整工作流集时,它总是失败。这是我的代码: # read the training da
我想使用 tidymodels 调整岭回归.我看过这个 nested sampling tutorial ,但不确定如何将调整从一个超参数增加到两个。请看下面的例子: 示例数据: library("m
我已经设法使用 tidymodels 构建了一个决策树模型。包,但我不确定如何提取结果并绘制树。我知道我可以使用 rpart和 rpart.plot包来实现同样的事情,但我宁愿使用 tidymodel
我想使用 recipes 创建一个食谱该软件包既可以估算缺失的数据,又可以添加指示哪些值缺失的指标列。如果有一个选项可以选择为原始数据框中的每一列包含一个指标列,或者只包含原始数据框中缺少数据的列的指
我真的很喜欢 tidymodels,但我不清楚我如何才能将该模型工作流适合嵌套分组依据之类的东西。例如,tidyr 在 mtcars 的圆柱体之类的东西上勾勒出一个简单的嵌套,然后为每个圆柱体拟合一个
我有以下代码用于使用 lightgbm 模型创建 tidymodels 工作流。但是,当我尝试保存到 .rds 对象并进行预测时出现了一些问题 library(AmesHousing) library
如何使用此 tidymodels 工作流程拟合模型? library(tidymodels) workflow() %>% add_model(linear_reg() %>% set_engin
我正在尝试对一个模型进行 k 折交叉验证,该模型根据卫星图像预测树种断面积比例的联合分布。这需要使用 DiricihletReg::DirichReg() 函数,这反过来又需要使用 Dirichlet
我可以在经典 Iris 数据集上应用 PCA 以获得每个维度的累积比例: library(tidyverse) x % as.matrix() pca % select(-Species) iris_
仍然习惯于 stackoverflow,所以如果发布不正确,我们深表歉意。 最近,我发现自己不得不运行许多预测变量略有不同的模型来衡量模型性能(我确信有一种更优雅的方法可以做到这一点),我正在考虑创建
我有一个二元分类问题,使用了随机森林和逻辑回归。根据 conf_mat、collect_metrics() 和 collect_predictions 的结果,我想更改我的模型,仅当模型“确定”时才分
我想对 LASSO 算法执行惩罚选择并使用 tidymodels 预测结果.我将使用波士顿住房数据集来说明这个问题。 library(tidymodels) library(tidyverse) li
我是一名优秀的程序员,十分优秀!