决策树
本练习中,您的任务是使用 scikit-learn 预置的 breast cancer 数据集,借助 DecisionTreeClassifier 构建一个简单的决策树。
该数据集包含来自乳腺活检的肿瘤个体在多个维度上的数值测量(例如周长、纹理等),以及单一的结果变量(肿瘤为恶性或良性)。
我们已将样本(各项测量)预加载到 X,并将每个肿瘤的目标值预加载到 y。现在,您需要将完整数据集拆分为训练集和测试集,然后训练一个 DecisionTreeClassifier。您将指定一个名为 max_depth 的参数。该模型还有许多其他可调整的参数,您可以在这里查看全部参数。
本练习是课程的一部分
使用 XGBoost 的极端梯度提升
练习说明
- 导入:
- 从
sklearn.model_selection导入train_test_split。 - 从
sklearn.tree导入DecisionTreeClassifier。
- 从
- 创建训练集和测试集,其中 20% 的数据用于测试。将
random_state设为123。 - 实例化名为
dt_clf_4的DecisionTreeClassifier,其max_depth设为4。该参数指定在到达叶节点前,最多允许连续的划分层数。 - 将分类器拟合到训练集,并预测测试集的标签。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the necessary modules
____
____
# Create the training and test sets
X_train, X_test, y_train, y_test = ____(____, ____, test_size=____, random_state=____)
# Instantiate the classifier: dt_clf_4
dt_clf_4 = ____
# Fit the classifier to the training set
____
# Predict the labels of the test set: y_pred_4
y_pred_4 = ____
# Compute the accuracy of the predictions: accuracy
accuracy = float(np.sum(y_pred_4==y_test))/y_test.shape[0]
print("accuracy:", accuracy)