Menu
CoddyTech

客户流失

本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 58 课,共 58 课。

一家套餐食材配送服务每周都会配送食材盒。subscribers.csv记录了 300 位客户,以及他们是否在两个月内取消订阅。跳过配送的食材盒是一个预警信号:

过去 3 个月内,按跳过配送的食材盒数量统计的取消订阅比例:跳过 0 次为 15%,跳过 1 次为 36%,跳过 2 次为 60%,跳过 3 次为 61%,跳过 4 次或更多为 86%

团队希望在客户离开之前联系有流失风险的客户。一个信号还不够,因此会用森林来综合评估所有信号。

它的深度需要调整,ROC 曲线可以显示风险评分对取消者的排序效果。

challenge icon

挑战

困难

prep 保存了各个处理流程;程序会将树的深度读入 depths。

  1. 分层划分出四分之一的数据作为测试集,使用 random_state=0。
  2. 在训练数据上,对 prep 加上由 100 棵树组成的森林(random_state=0)进行网格搜索,搜索范围为 depths,使用 5 折交叉验证。打印最佳深度和交叉验证准确率。
  3. 根据测试集上取消订阅的概率,打印 AUC 和呼叫名单:概率大于或等于 0.5 的客户。
  4. 将 ROC 曲线绘制为 forest,添加一条虚线的 coin toss 对角线和图例,然后显示图表。

换一个服务,并使用深度 3、5:

Best depth: 3 (CV accuracy 0.761)
Test AUC: 0.802
Call list: 21 customers, 15 of them really cancelled

标题为“谁会取消订阅?”的 ROC 曲线,实线森林曲线陡峭上升,高于虚线抛硬币对角线,并带有图例

然后 Coddy 会描述你的曲线。

亲手试试

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, roc_auc_score

subscribers = pd.read_csv("subscribers.csv")
numbers = ["months_subscribed", "boxes_skipped", "complaints", "monthly_price", "delivery_rating"]
text = ["plan", "channel"]
X = subscribers[numbers + text]
y = subscribers["churned"]

# 和 Prepare the Data 中一样的数据处理流程
number_steps = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
text_steps = make_pipeline(SimpleImputer(strategy="constant", fill_value="unknown"), OneHotEncoder())
prep = ColumnTransformer([("numbers", number_steps, numbers), ("words", text_steps, text)])

# 要尝试的树深度
n = int(input())
depths = []
for i in range(n):
    depths.append(int(input()))

fig, ax = plt.subplots()
ax.set_title("Who Will Cancel?")
ax.set_xlabel("False positive rate")
ax.set_ylabel("Recall")

# 在下方编写你的代码
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

监督学习中的所有课

自己练习: Python 在线编译器