识别最优树深度
现在,您将调优决策树的 max_depth 参数,找出既能降低过拟合又能保持良好模型指标的取值。您将通过 for 循环遍历多个 max_depth 取值,为每个取值拟合一棵决策树,然后计算性能指标。
我们已为您加载了包含候选参数的列表 depth_list。数组 depth_tuning 也已为您构建,包含 2 列:第一列已填入深度候选值,第二列为召回率的占位符。此外,特征和目标变量已分别作为训练数据 train_X、train_Y,以及测试数据 test_X、test_Y 供您使用。numpy 与 pandas 库分别以 np 与 pd 的名称加载。
本练习是课程的一部分
Python 营销中的机器学习
练习说明
- 对列表
depth_list的长度范围,从 0 到该长度,运行一个for循环。 - 针对每个深度候选值,初始化并拟合一个决策树分类器,并在测试数据上预测流失。
- 针对每个深度候选值,使用
recall_score()函数计算召回率,并将其存入depth_tunning的第二列。 - 使用合适的列名,将
depth_tuning转换为一个pandasDataFrame。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Run a for loop over the range of depth list length
for index in ___(0, len(depth_list)):
# Initialize and fit decision tree with the `max_depth` candidate
mytree = DecisionTreeClassifier(___=depth_list[index])
mytree.fit(___, train_Y)
# Predict churn on the testing data
pred_test_Y = mytree.predict(___)
# Calculate the recall score
depth_tuning[index,1] = ___(test_Y, ___)
# Name the columns and print the array as pandas DataFrame
col_names = ['Max_Depth','Recall']
print(pd.DataFrame(depth_tuning, columns=___))