我已经找到了解决这个问题的方法,但是我发现的一切都让我相信这是我的操作系统或我的RStudio / R版本的问题。我正在尝试为XGBoost创建自定义目标函数。但是,它看起来像一组参数有效,而另一组则没有:
require(xgboost)
data(agaricus.train, package='xgboost')
data(agaricus.test, package='xgboost')
dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
watchlist <- list(eval = dtest, train = dtrain)
num_round <- 2
huberobj <- function(preds, dtrain) {
d <- getinfo(dtrain, "label") - preds
h <- 1
scale <- 1+(d/h)^2
scale_sqrt <- scale^(1/2)
grad <- d/scale_sqrt
hess <- 1/scale/scale_sqrt
return(list(grad = grad, hess = hess))
}
evalerror <- function(preds, dtrain) {
d <- getinfo(dtrain, "label") - preds
h <- 1
scale <- 1 + (d / h)^2
err <- sum(sqrt(scale))
return(list(metric = "error", value = err))
}
xgbParam <- list( max_depth=2
, eta=1
, nthread = 2
, silent = 1
, objectve=huberobj
, eval_metric=evalerror
)
param <- list( max_depth=2
, eta=1
, nthread = 2
, silent=1
, objective=huberobj
, eval_metric=evalerror
)
bst <- xgb.train(param, dtrain, num_round, watchlist)
bst <- xgb.train(xgbParam, dtrain, num_round, watchlist)
在param上训练的模型可以工作,但是在xgbParam上训练的模型会引发以下错误:
Error in as.character(x) :
cannot coerce type 'closure' to vector of type 'character'
我将错误追溯到XGBoost中的以下函数:
`xgb.parameters<-` <- function(object = handle, value = NULL) {
if (length(value) == 0) return(object)
p <- as.list(value)
if (is.null(names(p)) || any(nchar(names(p)) == 0)) {
stop("parameter names cannot be empty strings")
}
names(p) <- gsub("\\.", "_", names(p))
p <- lapply(p, function(x) as.character(x)[1])
handle <- xgb.get.handle(object)
for (i in seq_along(p)) {
.Call(XGBoosterSetParam_R, handle, names(p[i]), p[[i]])
}
if (is(object, 'xgb.Booster') && !is.null(object$raw)) {
object$raw <- xgb.save.raw(object$handle)
}
object
}
然而,当我手动完成此功能时,我没有收到错误。还有其他人得到同样的错误吗?如果没有,有谁知道可能导致它的原因?任何对此的见解都将非常感激。