开始使用免费开始使用

线性基学习器

您已经在 XGBoost 中使用了树作为基模型,接下来试试另一种可用的基模型——线性学习器。虽然它在 XGBoost 中并不常用,但借助 XGBoost 强大的学习 API,您可以构建带正则化的线性回归。不过,由于它不常见,您需要使用 XGBoost 自有、与 scikit-learn 不兼容的函数来构建模型,例如 xgb.train()

为此,您需要创建一个参数字典,用来描述要使用的 booster 类型(类似于您在第 1 章使用 xgb.cv() 时创建的字典:https://campus.datacamp.com/courses/extreme-gradient-boosting-with-xgboost/10555?ex=9)。用于定义 booster 类型(基模型)的键值对是 "booster":"gblinear"

创建好模型后,您可以像之前一样使用模型的 .train().predict() 方法。

此处数据已分为训练集和测试集,您可以直接创建 XGBoost 学习 API 所需的 DMatrix 对象。

本练习是课程的一部分

使用 XGBoost 的极端梯度提升

查看课程

练习说明

  • 创建两个 DMatrix 对象:训练集用 DM_train(由 X_trainy_train 组成),测试集用 DM_test(由 X_testy_test 组成)。
  • 创建参数字典,定义将使用的 "booster" 类型("gblinear")以及要最小化的 "objective""reg:squarederror")。
  • 使用 xgb.train() 训练模型。需要为以下参数提供参数值:paramsdtrainnum_boost_round。使用 5 轮 boosting。
  • 使用 xg_reg.predict() 在测试集上进行预测,传入 DM_test,并将结果赋给 preds
  • 点击 "提交答案" 查看 RMSE!

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Convert the training and testing sets into DMatrixes: DM_train, DM_test
DM_train = ____
DM_test =  ____

# Create the parameter dictionary: params
params = {"____":"____", "____":"____"}

# Train the model: xg_reg
xg_reg = ____.____(____ = ____, ____=____, ____=____)

# Predict the labels of the test set: preds
preds = ____

# Compute and print the RMSE
rmse = np.sqrt(mean_squared_error(y_test,preds))
print("RMSE: %f" % (rmse))
编辑并运行代码