开始使用免费开始使用

XGBoost:拟合/预测

现在是创建您的第一个 XGBoost 模型的时候了!正如 Sergey 在视频中演示的,您可以使用 scikit-learn 的 .fit() / .predict() 范式来构建 XGBoost 模型,因为 xgboost 库提供了与 scikit-learn 兼容的 API!

这里,您将使用流失(churn)数据。该数据集包含一个网约车应用的虚拟数据,记录了用户在注册后第 1 个月的使用行为,覆盖一组虚构城市,并标注了用户在注册后第 5 个月是否仍然使用该服务。数据已为您预加载到名为 churn_data 的 DataFrame 中——请在 Shell 中探索它!

您的目标是使用第 1 个月的数据来预测用户在第 5 个月是否仍会使用该服务。这是一个典型的流失预测问题。为此,您将把数据拆分为训练集和测试集,在训练集上拟合一个小型的 xgboost 模型,并通过计算在测试集上的准确率来评估其性能。

pandasnumpy 已分别以 pdnp 导入,train_test_split 也已从 sklearn.model_selection 导入。此外,特征和目标对应的数组已分别创建为 Xy

本练习是课程的一部分

使用 XGBoost 的极端梯度提升

查看课程

练习说明

  • xgboostxgb 的别名导入。
  • 创建训练集和测试集,使 20% 的数据用于测试。使用 random_state123
  • XGBoostClassifier 实例化为 xg_cl,调用 xgb.XGBClassifier()。将 n_estimators 设为 10objective 设为 'binary:logistic'。先不必关心其含义,您将在本课程后续内容中学习这些参数。
  • 使用 .fit() 方法将 xg_cl 拟合到训练集(X_train, y_train)。
  • 使用 .predict() 方法预测测试集(X_test)的标签,然后点击 "提交答案" 以打印准确率。

交互式实操练习

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

# 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))
编辑并运行代码