You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

gbm(广义提升模型)函数训练异常,预测未返回0/1值应如何解决?

问题原因
  • gbm包的predict()函数在未指定type参数时,针对伯努利分布的模型默认返回**对数优势比(log-odds)**结果,而非分类标签或概率值,因此你直接查看head(pred_boos)会得到正负不定的连续值,而非预期的0/1分类结果。
  • head(boos.model)查看的是gbm训练生成的模型对象本身的属性,本来就不会输出预测分类值,你要查看预测结果需要查看调用predict后生成的pred_boos对象。
修复方案
  1. 模型训练阶段无需将Y转为因子,gbm的伯努利分布原生支持0/1数值型响应变量,可简化训练代码
  2. 预测阶段添加type = "response"参数,先得到样本属于Y=1类别的概率
  3. 以0.5为默认阈值(可根据业务需求调整),将概率转换为0/1分类标签

修改后的完整可运行代码如下:

library("mltools")
library("caret") 
library("MASS")
library("MLmetrics") 
library("gbm")
library("mlbench")

data=data.frame()

for (i in 0:4){ 
  
  mu1=c(0+i,4) 
  Sigma= matrix(c(1,0.5,0.5,1),ncol=2)
  X1_distribution=mvrnorm(n=100,mu=mu1,Sigma=Sigma)
  
  
  mu2=c(5-i,1) 
  Sigma= matrix(c(1,0.5,0.5,1),ncol=2) 
  X2_distribution=mvrnorm(n=100,mu=mu2,Sigma=Sigma)
  
  X=rbind(X1_distribution,X2_distribution)
  Y=c(rep(1,100),
      rep(0,100)) 
  data.aux=data.frame(Y=Y,
                      X1=X[,1],
                      X2=X[,2])
  
  data=rbind(data,data.aux)
}

data.train=data[1:800,]
data.test=data[801:1000,]

# 训练代码简化,无需将Y转为factor
boos.model= gbm(form= Y ~ .,
data=data.train, 
distribution='bernoulli', 
n.trees=5000, 
interaction.depth = 4)

# 预测时指定type = "response"得到概率,再转0/1分类
pred_boos_prob = predict(boos.model, 
newdata=data.test, 
n.trees=5000,
type = "response")
pred_boos = ifelse(pred_boos_prob > 0.5, 1, 0)

# 此时查看结果就是0/1分类值
head(pred_boos)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:45:04