開始使用免費開始

以決策樹作為基學習器

現在該動手建立一個用來預測房價的 XGBoost 模型了——這次不是課程影片中的麻薩諸塞州波士頓,而是愛荷華州的艾姆斯(Ames, Iowa)!這個房價資料集已經預先載入為名為 df 的 DataFrame。你可以在 Shell 中探索它,會看到包含房屋與其在城市中位置等各式各樣的特徵。

在這個練習中,你的目標是使用樹作為基學習器。XGBoost 預設就使用樹作為基學習器,因此這裡不必另外用 booster="gbtree" 指定要使用樹。

xgboost 已匯入為 xgb,而特徵與目標的陣列分別已在 Xy 中可用。

本練習屬於課程

使用 XGBoost 的極端梯度提升

檢視課程

練習說明

  • df 切分為訓練集與測試集,保留 20% 作為測試集。random_state 設為 123
  • XGBRegressor 建立為 xg_regseed 設為 123。指定 objective 為 "reg:squarederror",並使用 10 棵樹。注意:不必指定 booster="gbtree",因為這是預設值。
  • xg_reg 擬合到訓練資料,並預測測試集的標籤。將預測結果存成變數 preds
  • 使用 np.sqrt() 與已預先匯入自 sklearn.metricsmean_squared_error() 函式計算 rmse

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create the training and test sets
X_train, X_test, y_train, y_test = ____(____, ____, ____=____, random_state=123)

# Instantiate the XGBRegressor: xg_reg
xg_reg = ____

# Fit the regressor to the training set
____

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

# Compute the rmse: rmse
rmse = ____(____(____, ____))
print("RMSE: %f" % (rmse))
編輯並執行程式碼