gpt4 book ai didi

r - 如何创建自定义模型(在插入符号中使用循环/子模型技巧)

转载 作者:行者123 更新时间:2023-11-30 08:48:38 26 4
gpt4 key购买 nike

我在这个问题上挣扎了很长一段时间。我感觉自己像个十足的白痴,因为答案可能是非常明显的,但我找不到一条线索来解释如何做到这一点。

关于自定义模型创建的文档部分对我来说就像 this 。我觉得在我的教育过程中,我错过了一些非常具体的类(class),现在每个人都记得,但我除外,因为我发现的只是“是的,只需创建一个自定义模型,然后完成”。

此处的实际问题:

我想获得 caretgbm 的每次迭代的预测。例如,在 gbm 中,我可以在 predict(..., n.trees = 1:100) 中使用 n.trees ,它是完成。

caret 中,显然我需要使用称为子模型技巧的东西,这意味着 - 如果我理解正确 - 我必须创建自己的自定义模型。

但是我可以在getModelInfo('gbm')中看到,有某种循环函数!

$gbm$loop
function (grid)
{
loop <- plyr::ddply(grid, c("shrinkage", "interaction.depth",
"n.minobsinnode"), function(x) c(n.trees = max(x$n.trees)))
submodels <- vector(mode = "list", length = nrow(loop))
for (i in seq(along = loop$n.trees)) {
index <- which(grid$interaction.depth == loop$interaction.depth[i] &
grid$shrinkage == loop$shrinkage[i] & grid$n.minobsinnode ==
loop$n.minobsinnode[i])
trees <- grid[index, "n.trees"]
submodels[[i]] <- data.frame(n.trees = trees[trees !=
loop$n.trees[i]])
}
list(loop = loop, submodels = submodels)

我该如何使用它?为什么默认情况下它不工作?我真的需要创建一个自定义模型吗?或者也许不需要?

免责声明 1:我不想使用任何交叉验证。我只想为单个 GBM 运行的每次迭代提取预测。

免责声明 2:我不想在 $finalModel 上使用 predict.gbm(),因为我还想测试一些其他算法,这些算法也可以使用那个子模型技巧。我不想使用所有不同算法特定的 predict() 函数,因为那我为什么还要费心插入符号呢。

我什至不知道应该把什么作为可复制的例子。代码没有问题。我只是不知道这东西是如何工作的。

最佳答案

以下示例介绍了如何为每棵树的测试数据提取所需的预测:

library(caret)
library(mlbench) #for the data set
data(Sonar) #some data set I always use on stack overflow

res <- train(Class~.,
data = Sonar,
method = "gbm",
trControl = trainControl(method = "cv", #some evaluations scheme
number = 5,
savePredictions = "all"), #tell caret you would like to save all,
tuneGrid = expand.grid(shrinkage = 0.01,
interaction.depth = 2,
n.minobsinnode = 10,
n.trees = 1:100)) #some random values and all the trees

res$pred #results are stored in here

基本上,您在帖子中显示的代码告诉 caret 不要调整所有 n.tree 模型,而只是使用 max(n.trees) 调整模型。每个超参数组合,然后使用它来获得 n.trees < max(n.trees) 的预测

一些情节

library(ggplot2)

ggplot(res$results)+
geom_line(aes(x = n.trees, y = Accuracy))

enter image description here

您也可以选择不savePredictions = "all"因为这会产生一个需要内存的火车对象。而是使用res$results您可以在其中计算所有所需的指标。

关于r - 如何创建自定义模型(在插入符号中使用循环/子模型技巧),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com