You need to enable JavaScript to run this app. R中用caret训练gbm报‘inputs must be factors’错误,同参数其他算法正常
优惠活动
大模型
产品
解决方案
定价
更多

R中用caret训练gbm报‘inputs must be factors’错误,同参数其他算法正常

gbm模型训练报错排查与修复方案

报错核心根因

同数据集同交叉验证配置下其他算法可正常运行,说明数据集本身的变量类型没有基础问题,报错由gbm专属的配置不匹配触发:

  • 分布参数与任务类型错配:当前交叉验证控制配置启用了twoClassSummary、ROC指标,明确为二分类任务,但代码中给gbm传入了distribution="gaussian"——该参数是回归任务的配置项。caret的gbm包装器检测到gaussian分布时,会自动将任务判定为回归场景,尝试把原本为因子类型的二分类响应变量转为连续值,后续内部类型校验就会抛出inputs must be factors的报错。
  • 公式写法兼容问题:响应位置使用pull(y) ~ ...的写法,对多数算法(如svmRadial)caret会自动补全因子属性校验,但gbm的内部参数传递逻辑与其他算法不同,直接传入pull导出的裸向量时,会丢失变量原本的因子元数据,进一步触发类型校验失败。
  • 参数拼写错误:代码中tuneLenth为拼写错误,正确参数名为tuneLength,会导致调参配置不生效。

分步修复操作

  • 替换gbm的分布参数:将distribution="gaussian"修改为distribution="bernoulli",匹配二分类任务与twoClassSummary的配置逻辑。
  • 调整公式写法:去掉响应位置的pull(y),直接使用y ~ ...即可,因为已在train()中指定data = train,caret会自动读取列的原始类型,避免因子元数据丢失。
  • 修正拼写错误:将tuneLenth改为tuneLength,保障调参配置正常生效。

修正后可直接运行的代码

fitCtrl_2 <- trainControl(
  method = "cv",
  number = 10,
  savePredictions = "final",
  classProbs = TRUE,
  summaryFunction = twoClassSummary
)

set.seed(123)
system.time(
  model_gbm <- train(
    y ~ duration + nr.employed + euribor3m + pdays + emp.var.rate + 
      poutcome.success + month.mar + cons.conf.idx + contact.telephone + 
      contact.cellular + previous + age + cons.price.idx + month.jun + job.retired,
    data = train, 
    method = "gbm",
    distribution = "bernoulli",
    metric = "ROC",
    bag.fraction = 0.75,
    tuneLength = 10,
    trControl = fitCtrl_2
  )
)

残留问题排查

若按上述修改后仍报错,可运行以下代码校验变量类型:

# 校验响应变量y的类型
class(train$y)
# 校验公式涉及的所有特征类型
sapply(train[, all.vars(as.formula("y ~ duration + nr.employed + euribor3m + pdays + emp.var.rate + poutcome.success + month.mar + cons.conf.idx + contact.telephone + contact.cellular + previous + age + cons.price.idx + month.jun + job.retired"))[-1]], class)

如果发现poutcome.success、month.mar、contact.telephone这类分类特征被误存为数值型(而非0/1编码的因子),可通过train$col_name <- factor(train$col_name)将其转换为因子类型后重新运行。


内容的提问来源于stack exchange,提问作者ViSa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.20 09:45:03