線性基學習器
既然你已經在 XGBoost 中使用過樹作為基模型,現在來試試另一種可用的基模型——線性學習器。這個模型雖然在 XGBoost 中不那麼常見,但能透過 XGBoost 強大的學習 API 建立正規化的線性迴歸。不過,因為較少使用,你需要改用 XGBoost 自有、與 scikit-learn 介面不相容的函式來建模,例如 xgb.train()。
為了做到這點,你必須建立一個參數字典,描述你要使用的提昇器(booster)種類(就像你在第 1 章使用 xgb.cv() 時建立字典一樣:連結)。定義提昇器型別(基模型)的鍵值配對是 "booster":"gblinear"。
建立模型之後,你可以像先前一樣使用模型的 .train() 與 .predict() 方法。
這裡的資料已經切分為訓練集與測試集,所以你可以直接著手建立 XGBoost 學習 API 所需的 DMatrix 物件。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 建立兩個
DMatrix物件——訓練集用的DM_train(X_train與y_train),以及測試集用的DM_test(X_test與y_test)。 - 建立一個參數字典,定義你要使用的
"booster"型別("gblinear")以及要最小化的"objective"("reg:squarederror")。 - 使用
xgb.train()訓練模型。你必須為下列參數指定引數:params、dtrain、num_boost_round。使用5次提昇迭代。 - 使用
xg_reg.predict()在測試集上進行預測,並傳入DM_test。指定給preds。 - 按下「Submit Answer」即可查看 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))