如何使用 Caret 包调整多个参数?

How to tune multiple parameters using Caret package?

我正在构建一个 CART 模型,我正在尝试调整 rpart 的 2 个参数 - CP 和 Maxdepth。虽然 Caret 包一次对一个参数运行良好,但当同时使用两个参数时,它会不断抛出错误,我无法弄清楚为什么

library(caret)
data(iris)
tc <- trainControl("cv",10)
rpart.grid <- expand.grid(cp=seq(0,0.1,0.01), minsplit=c(10,20)) 
train(Petal.Width ~ Petal.Length + Sepal.Width + Sepal.Length, data=iris, method="rpart", 
      trControl=tc,  tuneGrid=rpart.grid)

我收到以下错误:

Error in train.default(x, y, weights = w, ...) : 
  The tuning parameter grid should have columns cp

方法"rpart"只能调整cp,方法"rpart2"用于maxdepth。没有对 minsplit 或任何其他 rpart 控件进行调整。如果你想调整不同的选项,你可以编写一个自定义模型来考虑到这一点。

点击here for more info on how to do this. Also read 了解如何在train函数中使用rpart控件。

caret 无法使用集成方法做到这一点,因此您将不得不添加自己的方法。

或者,您可以在 mlr 类似的机器学习框架上尝试此操作,该框架允许许多开箱即用的重采样策略、调整控制方法和算法参数调整。有很多learners already implemented, with several different evaluation metrics to choose from.

在你的具体问题中,试试这个例子:

library(mlr)
iris.task = classif.task = makeClassifTask(id = "iris-example", data = iris, target = "Species")
resamp = makeResampleDesc("CV", iters = 10L)

lrn = makeLearner("classif.rpart")

control.grid = makeTuneControlGrid() 
#you can pass resolution = N if you want the algorithm to 
#select N tune params given upper and lower bounds to a NumericParam
#instead of a discrete one
ps = makeParamSet(
  makeDiscreteParam("cp", values = seq(0,0.1,0.01)),
  makeDiscreteParam("minsplit", values = c(10,20))
)

#you can also check all the tunable params
getParamSet(lrn)

#and the actual tuning, with accuracy as evaluation metric
res = tuneParams(lrn, task = iris.task, resampling = resamp, control = control.grid, par.set = ps, measures = list(acc,timetrain))
opt.grid = as.data.frame(res$opt.path)
print(opt.grid)

mlr 用途广泛:包装器方法允许将学习器与调整策略、预处理、过滤和插补步骤等融合在一起。