開始使用免費開始

在 XGBoost 中使用正規化

你已在影片中看過 l1 正規化的範例。現在要變動 l2 正規化懲罰(也稱為 "lambda"),並觀察它對 Ames 房價資料集整體模型效能的影響。

本練習屬於課程

使用 XGBoost 的極端梯度提升

檢視課程

練習說明

  • 和先前一樣,從 Xy 建立 DMatrix
  • 建立初始參數字典,指定 "objective""reg:squarederror",以及 "max_depth"3
  • for 迴圈中使用 xgb.cv(),並透過傳入目前的 l2 值(reg)系統性地變動 "lambda"
  • 針對每個交叉驗證後的 xgboost 模型,將最後一次 boosting 回合的 "test-rmse-mean" 加入列表。
  • 按下「Submit Answer」即可查看結果。你觀察到什麼?

動手互動練習

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

# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)

reg_params = [1, 10, 100]

# Create the initial parameter dictionary for varying l2 strength: params
params = {"____":"____","____":____}

# Create an empty list for storing rmses as a function of l2 complexity
rmses_l2 = []

# Iterate over reg_params
for reg in reg_params:

    # Update l2 strength
    params["lambda"] = ____
    
    # Pass this updated param dictionary into cv
    cv_results_rmse = ____.____(dtrain=____, params=____, nfold=2, num_boost_round=5, metrics="rmse", as_pandas=True, seed=123)
    
    # Append best rmse (final round) to rmses_l2
    ____.____(____["____"].tail(1).values[0])

# Look at best rmse per l2 param
print("Best rmse as a function of l2:")
print(pd.DataFrame(list(zip(reg_params, rmses_l2)), columns=["l2", "rmse"]))
編輯並執行程式碼