我一直在运行不同的算法,根据其他几个参数来预测Facebook帖子的性能。我正在尝试的最后一种方法是XG-Boost。
即使在重新检查我的代码和包文档后,我也不断收到错误。我的训练和测试数据都已清理,所有因子都已转换为带有 1 和 0 的列。
处理测试和训练数据
temp.treat <- prepare(treatplan,temp, varRestriction = newvars)
test.treat <- prepare(treatplan,test, varRestriction = newvars)
训练模型
cv <- xgb.cv(data = as.matrix(temp.treat),
label = temp$Reach,
objective = "reg:linear",
nrounds = 400, nfold = 5, eta = 0.3, depth = 6)
获取预测
test$pred <- predict(cv, as.matrix(test.treat))
数据训练时不会引发错误,但是当我运行预测命令的那一刻,我得到了错误 -
使用方法("预测"(中的错误: 没有适用于"预测"的方法应用于类"xgb.cv.sync"的对象
谁能告诉我我做错了什么?
正如JMichaelJ所建议的那样,这是正在发生的事情:
您正在使用xgboost
包中的xgb.cv()
函数。xgb.cv()
函数运行初步建模,以帮助您确定要指定的适当nrounds
(树(数等信息。这可以在调用xgb.cv()
后提取
cv <- xgb.cv(data = as.matrix(temp.treat),
label = temp$Reach,
objective = "reg:linear",
nrounds = 400, nfold = 5, eta = 0.3, depth = 6)
elog <- as.data.frame(cv$evaluation_log)
(nrounds <- which.min(elog$test_rmse_mean)) #this will print the number of trees you need
请务必记住,到目前为止,此步骤仅帮助您确定需要为模型指定的树数(nrounds(。现在你需要使用xgboost()
实际构建它:
nrounds <- #Whatever number it told you above
model <- xgboost(data = as.matrix(data.treat),
label = data$outcome,
nrounds = nrounds, # this is where the xgb.cv() results matter
objective = "reg:linear", #or whatever type you need
eta = 0.3,
depth = 6)
假设您已经为测试数据集构建了处理计划,您现在可以根据存储在上述model
中的输出使用predict()
:
test$predictions <- predict(model, as.matrix(test.treat))
看起来您可能正在使用数据营地课程中的示例代码。这就是我正在使用的。我有同样的问题。希望此解决方案也适合您。
你应该使用该函数xgboost()
在包中。
xgb.cv()
只能帮助您获取有关以下方面的$evaluation表