開始使用免費開始

XGBoost:訓練/預測

現在來建立你的第一個 XGBoost 模型!如同 Sergey 在影片中示範的,你可以使用自己已經熟悉的 scikit-learn .fit().predict() 範式來建構 XGBoost 模型,因為 xgboost 函式庫提供與 scikit-learn 相容的 API!

這裡你要處理的是流失(churn)資料。此資料集包含一個叫車 App 的虛構資料:使用者在註冊後第 1 個月於一組虛構城市中的使用行為,以及在註冊滿 5 個月時是否仍持續使用服務。系統已為你將它載入為名為 churn_data 的 DataFrame——到 Shell 裡探索看看!

你的目標是使用第 1 個月的資料,預測使用者在第 5 個月是否仍會繼續使用這項服務。這是典型的流失預測問題設定。為了達成這個目標,你將把資料切分為訓練集與測試集,在訓練集上擬合一個小型的 xgboost 模型,並在測試集上以準確率來評估其效能。

pandasnumpy 已分別以 pdnp 匯入,train_test_split 也已從 sklearn.model_selection 匯入。此外,已替你建立好特徵與目標的陣列,分別為 Xy

本練習屬於課程

使用 XGBoost 的極端梯度提升

檢視課程

練習說明

  • xgboostxgb 的別名匯入。
  • 建立訓練集與測試集,其中 20% 的資料作為測試集,並使用 random_state123
  • xgb.XGBClassifier() 建立 XGBoostClassifier,命名為 xg_cl。將 n_estimators 設為 10objective 設為 'binary:logistic'。先不用擔心這些參數的意義,你會在本課程後面學到。
  • 使用 .fit()xg_cl 擬合到訓練集(X_train, y_train)。
  • 使用 .predict() 預測測試集(X_test)的標籤,然後按下「Submit Answer」以列印準確率。

動手互動練習

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

# Import xgboost
____

# Create arrays for the features and the target: X, y
X, y = churn_data.iloc[:,:-1], churn_data.iloc[:,-1]

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

# Instantiate the XGBClassifier: xg_cl
xg_cl = ____.____(____='____', ____=____, seed=123)

# Fit the classifier to the training set
____

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

# Compute the accuracy: accuracy
accuracy = float(np.sum(preds==y_test))/y_test.shape[0]
print("accuracy: %f" % (accuracy))
編輯並執行程式碼