【问题标题】:Using XGBoost in R for regression based model在 R 中使用 XGBoost 进行基于回归的模型
【发布时间】:2017-07-20 16:11:11
【问题描述】:

我正在尝试使用XGBoost 代替gbm

我得到的分数很奇怪,所以我在想我的代码可能做错了什么。

我的数据包含几个因子变量,所有其他数字。

响应变量是表示房价的连续变量。

我知道为了使用XGBoost,我需要使用One Hot Enconding。我正在使用以下代码这样做:

Xtest <- test.data
Xtrain <- train.data
XSalePrice <- Xtrain$SalePrice
Xtrain$SalePrice <- NULL

# Combine data  
Xall <- data.frame(rbind(Xtrain, Xtest))

# Get categorical features names
ohe_vars <- names(Xall)[which(sapply(Xall, is.factor))]

# Convert them
dummies <- dummyVars(~., data = Xall)
Xall_ohe <- as.data.frame(predict(dummies, newdata = Xall))

# Replace factor variables in data with OHE
Xall <- cbind(Xall[, -c(which(colnames(Xall) %in% ohe_vars))], Xall_ohe)

之后,我将数据拆分回测试和训练集:

Xtrain <- Xall[1:nrow(train.data), ]
Xtest <- Xall[-(1:nrow(train.data)), ]

然后构建模型,并打印 RMSE 和 Rsquared:

# Model
xgb.fit <- xgboost(data = data.matrix(Xtrain), label = XSalePrice,
  booster = "gbtree", objective = "reg:linear",
  colsample_bytree = 0.2, gamma = 0.0,
  learning_rate = 0.05, max_depth = 6,
  min_child_weight = 1.5, n_estimators = 7300,
  reg_alpha = 0.9, reg_lambda = 0.5,
  subsample = 0.2, seed = 42,
  silent = 1, nrounds = 25)

xgb.pred <- predict(xgb.fit, data.matrix(Xtrain))
postResample(xgb.pred, XSalePrice)

问题是我对 RMSE 和 Rsxquare 感到非常失望:

        RMSE     Rsquared 
1.877639e+05 5.308910e-01 

这与我使用 GBM 时得到的结果相差甚远。

我在想我做错了什么,我最好的猜测可能是我不熟悉的 One Hot Encoding 阶段,所以使用谷歌搜索的代码对我的数据进行了调整。

谁能指出我做错了什么以及如何“修复”它?

更新:

查看@Codutie 的答案后,我的代码有一些错误:

Xtrain <- sparse.model.matrix(SalePrice ~. , data = train.data)
XDtrain <- xgb.DMatrix(data = Xtrain, label = "SalePrice")

xgb.DMatrix 产生:

Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) : 
  The length of labels must equal to the number of rows in the input data

train.data 是数据框,它有 1453 行。标签SalePrice还包含1453个值(无缺失值)

谢谢

【问题讨论】:

    标签: r regression decision-tree xgboost one-hot-encoding


    【解决方案1】:
    train <- dat[train_ind,]
    train.y <- train[,ncol(train_ind)]
    xgboost(data =data.matrix(train[,-1]), 
       label = train.y, 
       objective = "reg:linear", 
       eval_metric = "rmse",
       max.depth =15, 
       eta = 0.1, 
       nround = 15, 
       subsample = 0.5, 
       colsample_bytree = 0.5, 
       num_class = 12,
       nthread = 3
    )
    

    控制 XGB 进行回归的两条线索,

    1) eta:如果 eta 很小,模型往往会过拟合

    2) eval_metric:不确定 xgb 是否允许用户使用他们自己的 eval_metric。但是,当定量因变量包含异常值时,该度量就没有用了。检查 XGB 是否支持 hubber 损失函数。

    【讨论】:

      猜你喜欢
      • 2016-01-17
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多