用决策树预测流失

Python 营销中的机器学习

Karolis Urbonas

Head of Analytics & Science, Amazon

决策树简介

泰坦尼克生存数据集的决策树规则

Python 营销中的机器学习

建模步骤

  1. 将数据划分为训练集和测试集
  2. 初始化模型
  3. 在训练集上拟合模型
  4. 在测试集上预测
  5. 在测试集上评估性能
Python 营销中的机器学习

拟合模型

导入决策树模块

from sklearn.tree import DecisionTreeClassifier

初始化决策树模型

mytree = DecisionTreeClassifier()

在训练集上拟合模型

treemodel = mytree.fit(train_X, train_Y)
Python 营销中的机器学习

评估模型准确率

from sklearn.metrics import accuracy_score

pred_train_Y = mytree.predict(train_X) pred_test_Y = mytree.predict(test_X)
train_accuracy = accuracy_score(train_Y, pred_train_Y) test_accuracy = accuracy_score(test_Y, pred_test_Y)
print('Training accuracy:', round(train_accuracy,4)) print('Test accuracy:', round(test_accuracy, 4))
训练集准确率: 0.9973
测试集准确率: 0.7196
Python 营销中的机器学习

评估精确率与召回率

from sklearn.metrics import precision_score, recall_score

train_precision = round(precision_score(train_Y, pred_train_Y), 4) test_precision = round(precision_score(test_Y, pred_test_Y), 4)
train_recall = round(recall_score(train_Y, pred_train_Y), 4) test_recall = round(recall_score(test_Y, pred_test_Y), 4)
print('Training precision: {}, Training recall: {}'.format(train_precision, train_recall)) print('Test precision: {}, Test recall: {}'.format(train_recall, test_recall))
训练集精确率: 0.9993,训练集召回率: 0.9906
测试集精确率: 0.9906,测试集召回率: 0.4878
Python 营销中的机器学习

树深度参数调优

depth_list = list(range(2,15))
depth_tuning = np.zeros((len(depth_list), 4))
depth_tuning[:,0] = depth_list

for index in range(len(depth_list)): mytree = DecisionTreeClassifier(max_depth=depth_list[index]) mytree.fit(train_X, train_Y) pred_test_Y = mytree.predict(test_X)
depth_tuning[index,1] = accuracy_score(test_Y, pred_test_Y) depth_tuning[index,2] = precision_score(test_Y, pred_test_Y) depth_tuning[index,3] = recall_score(test_Y, pred_test_Y)
col_names = ['Max_Depth','Accuracy','Precision','Recall'] print(pd.DataFrame(depth_tuning, columns=col_names))
Python 营销中的机器学习

选择最优深度

最大深度调优

Python 营销中的机器学习

选择最优深度

最大深度调优

Python 营销中的机器学习

让我们构建一个决策树!

Python 营销中的机器学习

Preparing Video For Download...