Environment
Python 3.14.6, pandas 2.3.3, lifelines 0.30.3, LightGBM 4.7.0, scikit-learn 1.9.1, Matplotlib 3.11.2.
Overview
By the time a customer cancels, they may already have decided to switch providers. This article introduces Chapter 7, “Predicting Churn,” of Marketing Science in Theory and Practice . Following the book, we cover the churn problem, survival analysis, churn scoring in Python, and separate checks of an action’s effect and profitability.
Setup code (imports and display settings)
import platform
from importlib.metadata import version
from pathlib import Path
from pprint import pprint
import lightgbm as lgb
import matplotlib.pyplot as plt
import matplotlib_fontja
import numpy as np
import pandas as pd
from IPython.display import Latex, SVG, display
from lifelines import CoxPHFitter, KaplanMeierFitter
from lifelines.statistics import proportional_hazard_test
from matplotlib.ticker import FuncFormatter, ScalarFormatter
from scipy.stats import norm
from sklearn.metrics import (
average_precision_score, f1_score, precision_recall_curve,
precision_score, recall_score, roc_auc_score, roc_curve,
)
from sklearn.model_selection import train_test_split
print(f"環境: wa-src(3.14.6) / Python {platform.python_version()}")
for package in (
"numpy", "pandas", "scipy", "matplotlib", "matplotlib-fontja",
"lifelines", "lightgbm", "scikit-learn",
):
print(f"{package}: {version(package)}")
# リポジトリ内と、ダウンロードしたフォルダーの両方に対応する。
repo = next(
(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "doc/07/07_main.tex").exists()),
None,
)
output_dir = repo / "blog/07" if repo else Path.cwd()
image_dir = output_dir / "07_nb_files"
image_dir.mkdir(parents=True, exist_ok=True)
data_path = output_dir / "data/Telco-Customer-Churn.csv"
def sig3(value):
"""表示だけを有効数字3桁にし、計算値は丸めない。"""
return format(float(value), "#.3g")
np.set_printoptions(formatter={"float_kind": sig3})
pd.set_option("display.float_format", sig3)
plt.rcParams.update({
"font.size": 11, "axes.spines.top": False, "axes.spines.right": False,
"svg.fonttype": "path", "svg.hashsalt": "blog07",
})
BLUE, ORANGE, GREEN = "#2c5f8a", "#b96532", "#3b795d"
def show_math(expression):
# 重要な式の \(...\) を表示用の $$...$$ に変換する。
# 出力はtext/latexであり、HTML内にインライン用の区切りを残さない。
display(Latex(expression.replace(r"\(", "$$").replace(r"\)", "$$")))
def save_svg(fig, filename):
"""小数目盛りを3桁にそろえ、SVGを保存して出力欄に埋め込む。"""
def tick_label(value, _):
return str(int(value)) if value == int(value) else sig3(value)
for ax in fig.axes:
for axis in (ax.xaxis, ax.yaxis):
if isinstance(axis.get_major_formatter(), ScalarFormatter):
axis.set_major_formatter(FuncFormatter(tick_label))
ax.grid(alpha=0.180)
ax.set_axisbelow(True)
fig.tight_layout()
path = image_dir / filename
fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
display(SVG(filename=str(path)))
plt.close(fig)
環境: wa-src(3.14.6) / Python 3.14.6
numpy: 2.4.6
pandas: 2.3.3
scipy: 1.18.1
matplotlib: 3.11.2
matplotlib-fontja: 1.1.0
lifelines: 0.30.3
lightgbm: 4.7.0
scikit-learn: 1.9.1
1. Whom should we contact, and when?
Acquiring new customers may not grow the customer base if existing customers keep leaving. The chapter considers how signs such as fewer logins or late payments could identify people before they cancel.
“Will this customer cancel within 30 days?” is a classification question. “How many months will they remain after signup?” is a survival-analysis question. Let $T_i$ be time to cancellation and $\mathbf{x}_i^{(t)}$ the information available at current time $t$. The prediction target is the following conditional probability.
show_math(r"\(p_{\mathrm{churn},i}=P(t<T_i\le t+\Delta t\mid T_i>t,\mathbf{x}_i^{(t)})\)")
$$p_{\mathrm{churn},i}=P(t<T_i\le t+\Delta t\mid T_i>t,\mathbf{x}_i^{(t)})$$
2. Analyze retention time with survival analysis
2.1 Include customers who are still active
For customers still active when observation ends, cancellation time is unknown. Treat this right censoring as information that they remained active until then, rather than proof that they will never leave. Let $C_i$ be the available observation duration, $t_i$ the observed duration, and $\delta_i$ the cancellation indicator. Time starts at each customer’s contract start date.
show_math(r"\(t_i=\min(T_i,C_i),\qquad\delta_i=\begin{cases}1&T_i\le C_i\\0&T_i>C_i\end{cases}\)")
# 6人の説明用データ。×は解約、縦線は右打ち切りを示す。
toy_time = np.array([2, 3, 5, 6, 8, 9])
toy_event = np.array([1, 0, 1, 0, 1, 0])
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
for i, (duration, event) in enumerate(zip(toy_time, toy_event)):
axes[0].hlines(i, 0, duration, color=BLUE, linewidth=2)
axes[0].plot(duration, i, "x" if event else "|",
color=ORANGE if event else BLUE, markersize=11, markeredgewidth=2)
axes[0].set(yticks=range(6), yticklabels=list("ABCDEF"), xlabel="契約からの月数",
title="図1a 観測期間(説明用)", xlim=(-0.200, 10))
axes[0].invert_yaxis()
toy_km = KaplanMeierFitter().fit(toy_time, toy_event, label="6人の継続率")
toy_km.plot_survival_function(ax=axes[1], ci_show=False, show_censors=True, color=BLUE)
axes[1].set(xlabel="契約からの月数", ylabel="生存確率", ylim=(0, 1.05),
title="図1b 打ち切りだけでは下がらない")
save_svg(fig, "01_censoring.svg")
$$t_i=\min(T_i,C_i),\qquad\delta_i=\begin{cases}1&T_i\le C_i\\0&T_i>C_i\end{cases}$$
2.2 Kaplan–Meier curves
The survival function $S(t)=P(T>t)$ is the probability of remaining active beyond $t$. At each cancellation time $t_j$, the Kaplan–Meier estimate multiplies the proportion remaining after $d_j$ cancellations among the $n_j$ customers at risk immediately beforehand. Censoring must be independent of cancellation under the relevant conditions.
In the book’s example, month 1 starts with 1,000 customers: 50 cancel and 10 are censored. Month 2 starts with 940, of whom 80 cancel. Censoring affects the next month’s denominator.
show_math(r"""\(\begin{aligned}
\widehat S(t)&=\prod_{j:t_j\le t}\left(1-\frac{d_j}{n_j}\right)\\
\widehat S(1)&=1-\frac{50}{1000}=\frac{950}{1000}=0.950\\
n_2&=1000-50-10=940\\
\widehat S(2)&=\frac{950}{1000}\left(1-\frac{80}{940}\right)
=\frac{950}{1000}\frac{860}{940}\approx0.869
\end{aligned}\)""")
survival = np.cumprod(1 - np.array([50, 80]) / np.array([1000, 940]))
pprint({"1か月後": sig3(survival[0]), "2か月後": sig3(survival[1])})
$$\begin{aligned} \widehat S(t)&=\prod_{j:t_j\le t}\left(1-\frac{d_j}{n_j}\right)\\ \widehat S(1)&=1-\frac{50}{1000}=\frac{950}{1000}=0.950\\ n_2&=1000-50-10=940\\ \widehat S(2)&=\frac{950}{1000}\left(1-\frac{80}{940}\right) =\frac{950}{1000}\frac{860}{940}\approx0.869 \end{aligned}$$
{'1か月後': '0.950', '2か月後': '0.869'}
2.3 Hazards and the Cox model
The hazard $h(t)$ describes the instantaneous cancellation rate among customers who have remained until time $t$. It is not itself a probability. In continuous time, assume $S(0)=1$ and work where $S(t)>0$. Here $f(t)$ is the density of cancellation time and $H(t)$ the cumulative hazard.
show_math(r"""\(\begin{aligned}
h(t)&=\lim_{\Delta t\to0}\frac{P(t<T\le t+\Delta t\mid T>t)}{\Delta t}\\
&=\lim_{\Delta t\to0}\frac{S(t)-S(t+\Delta t)}{S(t)\Delta t}
=-\frac{S'(t)}{S(t)}=\frac{f(t)}{S(t)}\\
\frac{d}{dt}\log S(t)&=-h(t)\\
\log S(t)-\log S(0)&=-\int_0^t h(u)\,du=-H(t)\\
S(t)&=\exp[-H(t)]
\end{aligned}\)""")
show_math(r"""\(\begin{aligned}
P(t<T\le t+\Delta t\mid T>t)
&=\frac{S(t)-S(t+\Delta t)}{S(t)}\\
&=1-\frac{S(t+\Delta t)}{S(t)}\\
&=1-\exp\left[-\int_t^{t+\Delta t}h(u)\,du\right]
\end{aligned}\)""")
# 一定ハザードを仮定した説明用の曲線。実データの推定値ではない。
months = np.linspace(0, 36, 181)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
for rate, color in [(0.0400, BLUE), (0.0800, ORANGE)]:
label = f"h = {sig3(rate)} / 月"
axes[0].plot(months, np.full_like(months, rate), color=color, label=label)
axes[1].plot(months, np.exp(-rate * months), color=color, label=label)
axes[0].set(title="図2a 一定のハザード(説明用)", ylabel="ハザード(月当たり)", ylim=(0, 0.100))
axes[1].set(title="図2b 対応する生存関数", ylabel="生存確率", ylim=(0, 1.05))
for ax in axes:
ax.set_xlabel("契約からの月数")
ax.legend()
save_svg(fig, "02_hazard_survival.svg")
$$\begin{aligned} h(t)&=\lim_{\Delta t\to0}\frac{P(t<T\le t+\Delta t\mid T>t)}{\Delta t}\\ &=\lim_{\Delta t\to0}\frac{S(t)-S(t+\Delta t)}{S(t)\Delta t} =-\frac{S’(t)}{S(t)}=\frac{f(t)}{S(t)}\\ \frac{d}{dt}\log S(t)&=-h(t)\\ \log S(t)-\log S(0)&=-\int_0^t h(u)\,du=-H(t)\\ S(t)&=\exp[-H(t)] \end{aligned}$$
$$\begin{aligned} P(t<T\le t+\Delta t\mid T>t) &=\frac{S(t)-S(t+\Delta t)}{S(t)}\\ &=1-\frac{S(t+\Delta t)}{S(t)}\\ &=1-\exp\left[-\int_t^{t+\Delta t}h(u)\,du\right] \end{aligned}$$
The Cox model multiplies a baseline hazard $h_0(t)$ by a factor determined by customer features $\mathbf{x}_i$. The vector $\mathbf{b}$ contains the coefficients. The baseline cancels when comparing two customers, giving the assumption that their hazard ratio is constant over time.
show_math(r"""\(\begin{aligned}
h(t\mid\mathbf{x}_i)&=h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_i)\\
\frac{h(t\mid\mathbf{x}_i)}{h(t\mid\mathbf{x}_j)}
&=\frac{h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_i)}
{h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_j)}\\
&=\exp[\mathbf{b}^{\mathsf T}(\mathbf{x}_i-\mathbf{x}_j)]\\
\mathrm{HR}_k&=\exp(b_k)
\end{aligned}\)""")
show_math(r"""\(\begin{aligned}
\mathcal R(t_j)&=\{k:t_k\ge t_j\}\\
L(\mathbf{b})&=\prod_{j:\delta_j=1}
\frac{\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_j)}
{\sum_{k\in\mathcal R(t_j)}\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_k)}\\
\log L(\mathbf{b})&=\sum_{j:\delta_j=1}\left[
\mathbf{b}^{\mathsf T}\mathbf{x}_j-
\log\sum_{k\in\mathcal R(t_j)}\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_k)\right]
\end{aligned}\)""")
$$\begin{aligned} h(t\mid\mathbf{x}_i)&=h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_i)\\ \frac{h(t\mid\mathbf{x}_i)}{h(t\mid\mathbf{x}_j)} &=\frac{h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_i)} {h_0(t)\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_j)}\\ &=\exp[\mathbf{b}^{\mathsf T}(\mathbf{x}_i-\mathbf{x}_j)]\\ \mathrm{HR}_k&=\exp(b_k) \end{aligned}$$
$$\begin{aligned} \mathcal R(t_j)&=\{k:t_k\ge t_j\}\\ L(\mathbf{b})&=\prod_{j:\delta_j=1} \frac{\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_j)} {\sum_{k\in\mathcal R(t_j)}\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_k)}\\ \log L(\mathbf{b})&=\sum_{j:\delta_j=1}\left[ \mathbf{b}^{\mathsf T}\mathbf{x}_j- \log\sum_{k\in\mathcal R(t_j)}\exp(\mathbf{b}^{\mathsf T}\mathbf{x}_k)\right] \end{aligned}$$
Holding other variables fixed, increasing $x_k$ by one multiplies the hazard by $\exp(b_k)$. It does not multiply the probability of cancellation over a period by the same amount. Coefficients are estimated from the partial likelihood $L$ using the risk set $\mathcal R(t_j)$ just before each event. The displayed formula assumes no tied event times; the implementation uses Efron’s method for ties in monthly data.
3. Examine retention and associated factors in Python
3.1 Prepare the data
As in the chapter, we use the 7,043-customer IBM Telco dataset. We treat tenure as observed months and Churn as the event indicator. Contract start and cancellation dates are unavailable, so we cannot verify how observation periods were constructed. This is a demonstration of the survival-analysis procedure. We do not discard the 11 rows with missing TotalCharges because the models here do not use that field.
use_cols = [
"customerID", "tenure", "Churn", "MonthlyCharges", "TotalCharges",
"Contract", "InternetService", "PaymentMethod", "SeniorCitizen",
"Partner", "TechSupport",
]
df = pd.read_csv(data_path, usecols=use_cols)
df["churn_flag"] = df["Churn"].eq("Yes").astype(int)
df["TotalCharges"] = pd.to_numeric(df["TotalCharges"], errors="coerce")
T = df["tenure"].to_numpy()
E = df["churn_flag"].to_numpy()
print(f"顧客数: {len(df):,}人 / 解約: {df['churn_flag'].sum():,}人")
print(f"解約割合: {sig3(100 * df['churn_flag'].mean())}%")
print(f"TotalChargesの欠損: {df['TotalCharges'].isna().sum()}件")
contracts = ["Month-to-month", "One year", "Two year"]
contract_labels = ["月次契約", "1年契約", "2年契約"]
contract_summary = df.groupby("Contract")["churn_flag"].agg(["size", "mean"]).reindex(contracts)
print(contract_summary.rename(columns={"size": "人数", "mean": "解約割合"}).to_string())
fig, ax = plt.subplots(figsize=(7, 3.5))
bars = ax.bar(contract_labels, 100 * contract_summary["mean"], color=[ORANGE, BLUE, GREEN])
ax.bar_label(bars, labels=[f"{sig3(v)}%" for v in 100 * contract_summary["mean"]], padding=4)
ax.set(title="図3 契約形態別の解約割合", ylabel="解約割合 (%)", ylim=(0, 50))
save_svg(fig, "03_churn_by_contract.svg")
顧客数: 7,043人 / 解約: 1,869人
解約割合: 26.5%
TotalChargesの欠損: 11件
人数 解約割合
Contract
Month-to-month 3875 0.427
One year 1473 0.113
Two year 1695 0.0283
3.2 Compare Kaplan–Meier curves
The aggregation in Figure 3 does not account for different customer tenures. We next plot survival curves overall and by contract type to compare customers at the same tenure. The overall band is a 95% confidence interval.
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
km = KaplanMeierFitter().fit(T, E, label="全顧客")
km.plot_survival_function(ax=axes[0], color=BLUE, ci_alpha=0.150)
for contract, label, color in zip(contracts, contract_labels, [ORANGE, BLUE, GREEN]):
group = df.loc[df["Contract"].eq(contract)]
group_km = KaplanMeierFitter().fit(group["tenure"], group["churn_flag"], label=label)
group_km.plot_survival_function(ax=axes[1], ci_show=False, color=color)
print(f"{label}: 12か月生存確率 = {sig3(group_km.predict(12))}")
for ax, title in zip(axes, ["図4a 全顧客", "図4b 契約形態別"]):
ax.set(title=title, xlabel="在籍月数", ylabel="生存確率", ylim=(0, 1.05))
save_svg(fig, "04_kaplan_meier.svg")
月次契約: 12か月生存確率 = 0.703
1年契約: 12か月生存確率 = 0.991
2年契約: 12か月生存確率 = 1.00
The monthly-contract curve falls from early in the period. This alone does not show that changing customers to long-term contracts would reduce churn. Customers already planning to stay may be more likely to choose long-term contracts.
3.3 Fit the Cox model
Convert contract types and other categorical features to indicator columns and add regularization to limit extreme coefficients. Figure 5 shows coefficients and 95% confidence intervals. Positive coefficients point toward higher hazards and negative coefficients toward lower hazards. Monthly contracts are the reference category.
cox_cols = [
"tenure", "churn_flag", "MonthlyCharges", "SeniorCitizen", "Contract",
"InternetService", "PaymentMethod", "Partner", "TechSupport",
]
cox_data = pd.get_dummies(
df[cox_cols], columns=["Contract", "InternetService", "PaymentMethod"],
drop_first=True, dtype=int,
)
for name in ["Partner", "TechSupport"]:
cox_data[name] = cox_data[name].eq("Yes").astype(int)
cox = CoxPHFitter(penalizer=0.100)
cox.fit(cox_data, duration_col="tenure", event_col="churn_flag")
ph = proportional_hazard_test(cox, cox_data, time_transform="rank")
ph_count = int(ph.summary["p"].lt(0.0500).sum())
print(f"比例ハザードの検定でp値が0.0500未満の項目: {ph_count}")
fig, ax = plt.subplots(figsize=(10, 5.2))
cox.plot(ax=ax, c=BLUE)
ax.set(title="図5 Coxモデルの係数と95%信頼区間", xlabel="係数(ハザード比の対数)")
save_svg(fig, "05_cox_coefficients.svg")
比例ハザードの検定でp値が0.0500未満の項目: 7
The proportional-hazards test gives $p<0.0500$ for seven variables. Read the coefficients as overall summaries for this period. In practice, examine changes over time and, if necessary, separate periods or customer groups. Check the proportional-hazards assumption before interpreting coefficients.
4. Rank target candidates with LightGBM
4.1 Train and evaluate
The dataset’s Churn label describes status at observation, not cancellation during a future 30-day window. Treat the output as a score distinguishing observed churn. Using the book’s features, split the data into 60% training, 20% validation, and 20% test sets. In practice, use information available by a cutoff date to predict later churn and evaluate on a later period.
# Cox用の数値化を再利用し、分類用に在籍月数と追加の特徴量を使う。
X = cox_data.drop(columns="churn_flag").copy()
X["is_early_tenure"] = X["tenure"].between(1, 3).astype(int)
X["is_month_to_month"] = df["Contract"].eq("Month-to-month").astype(int)
X["monthly_x_contract_monthly"] = X["MonthlyCharges"] * X["is_month_to_month"]
y = df["churn_flag"]
X_train, X_temp, y_train, y_temp = train_test_split(
X, y, test_size=0.400, random_state=42, stratify=y,
)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.500, random_state=42, stratify=y_temp,
)
print(f"学習 {len(X_train)}件 / 検証 {len(X_val)}件 / テスト {len(X_test)}件")
# 検証データだけを使って学習の停止時点を決める。
params = {
"objective": "binary", "metric": ["auc", "binary_logloss"],
"learning_rate": 0.0500, "num_leaves": 31, "min_child_samples": 20,
"feature_fraction": 0.800, "bagging_fraction": 0.800, "bagging_freq": 5,
"reg_alpha": 0.100, "reg_lambda": 0.100, "verbosity": -1,
"seed": 42, "num_threads": 1, "deterministic": True, "force_col_wise": True,
}
model = lgb.train(
params, lgb.Dataset(X_train, label=y_train), num_boost_round=500,
valid_sets=[lgb.Dataset(X_val, label=y_val)],
callbacks=[lgb.early_stopping(50, verbose=False)],
)
val_score = model.predict(X_val)
test_score = model.predict(X_test)
pprint({
"最適な学習回数": model.best_iteration,
"テストROC-AUC": sig3(roc_auc_score(y_test, test_score)),
"テストAP": sig3(average_precision_score(y_test, test_score)),
"無作為順位のAPの目安": sig3(y_test.mean()),
})
importance = pd.Series(model.feature_importance("gain"), index=X.columns).nlargest(8)
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
importance.sort_values().plot.barh(ax=axes[0], color=BLUE)
axes[0].set(title="図6a 特徴量重要度(Gain)", xlabel="分岐による改善量の合計")
false_positive, true_positive, _ = roc_curve(y_test, test_score)
axes[1].plot(false_positive, true_positive, color=BLUE, label="LightGBM")
axes[1].plot([0, 1], [0, 1], "--", color="0.500", label="無作為")
axes[1].set(title="図6b ROC曲線(テスト)", xlabel="偽陽性率", ylabel="真陽性率")
axes[1].legend()
save_svg(fig, "06_model_evaluation.svg")
学習 4225件 / 検証 1409件 / テスト 1409件
{'テストAP': '0.623', 'テストROC-AUC': '0.830', '最適な学習回数': 61, '無作為順位のAPの目安': '0.265'}
ROC-AUC measures how well churners rank above retained customers. Average precision (AP) summarizes the precision–recall relationship. The churn rate changes the benchmark for AP. Feature importance indicates use in prediction; it does not identify causes of churn or the direction of an effect.
4.2 Choose a threshold and target size
TP counts correctly selected churners, FP selected non-churners, and FN missed churners. F1 is the harmonic mean of precision and recall. Choose the threshold on validation data and keep it fixed for the test set.
show_math(r"""\(\begin{aligned}
P&=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}},\qquad
R=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}\\
F_1&=\frac{2}{1/P+1/R}
=\frac{2PR}{P+R}
=\frac{2\mathrm{TP}}{2\mathrm{TP}+\mathrm{FP}+\mathrm{FN}}
\end{aligned}\)""")
precision, recall, thresholds = precision_recall_curve(y_val, val_score)
denominator = precision[:-1] + recall[:-1]
f1 = np.divide(2 * precision[:-1] * recall[:-1], denominator,
out=np.zeros_like(denominator), where=denominator > 0)
best = int(np.argmax(f1))
threshold = thresholds[best]
test_selected = test_score >= threshold
pprint({
"検証で選んだ閾値": sig3(threshold),
"テスト適合率": sig3(precision_score(y_test, test_selected)),
"テスト再現率": sig3(recall_score(y_test, test_selected)),
"テストF1": sig3(f1_score(y_test, test_selected)),
"テストの対象候補数": int(test_selected.sum()),
})
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
axes[0].plot(recall, precision, color=BLUE)
axes[0].scatter(recall[best], precision[best], color=ORANGE, zorder=3, label="F1最大")
axes[0].set(title="図7a PR曲線(検証)", xlabel="再現率", ylabel="適合率")
for values, label, color in zip([precision[:-1], recall[:-1], f1],
["適合率", "再現率", "F1"], [BLUE, ORANGE, GREEN]):
axes[1].plot(thresholds, values, label=label, color=color)
axes[1].axvline(threshold, color="0.400", linestyle="--", label=f"閾値 {sig3(threshold)}")
axes[1].set(title="図7b 閾値と評価指標(検証)", xlabel="閾値", ylabel="指標")
for ax in axes:
ax.legend()
save_svg(fig, "07_threshold.svg")
# これは評価用の対象候補。actual_churnは運用時のリストには入れない。
evaluation = pd.DataFrame({
"customerID": df.loc[X_test.index, "customerID"],
"churn_score": test_score, "actual_churn": y_test,
}).sort_values("churn_score", ascending=False, kind="stable")
candidates = evaluation.loc[evaluation["churn_score"].ge(threshold)]
print(candidates.head(5).to_string(index=False, float_format=sig3))
$$\begin{aligned} P&=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}},\qquad R=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}\\ F_1&=\frac{2}{1/P+1/R} =\frac{2PR}{P+R} =\frac{2\mathrm{TP}}{2\mathrm{TP}+\mathrm{FP}+\mathrm{FN}} \end{aligned}$$
{'テストF1': '0.604',
'テストの対象候補数': 460,
'テスト再現率': '0.674',
'テスト適合率': '0.548',
'検証で選んだ閾値': '0.359'}
customerID churn_score actual_churn
9300-AGZNL 0.866 1
6567-HOOPW 0.863 1
7493-TPUWZ 0.860 1
2514-GINMM 0.860 1
0495-RVCBF 0.860 1
Maximizing F1 does not necessarily maximize profit. If capacity limits the number of contacts, check what share of churners is captured by the top-ranked customers. Cumulative gain is that share; lift compares it with random selection.
show_math(r"\(\mathrm{Gain}(k)=\frac{\text{上位}k\text{人に含まれる解約者数}}{\text{全解約者数}},\qquad\mathrm{Lift}(k)=\frac{\mathrm{Gain}(k)}{k/N}\)")
labels = evaluation["actual_churn"].to_numpy()
fraction = np.arange(1, len(labels) + 1) / len(labels)
gain = np.cumsum(labels) / labels.sum()
lift = gain / fraction
k = int(np.ceil(0.200 * len(labels)))
pprint({"上位約20%の人数": k, "解約者の捕捉割合": sig3(gain[k - 1]),
"リフト": sig3(lift[k - 1])})
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
axes[0].plot(np.r_[0, fraction * 100], np.r_[0, gain * 100], color=BLUE)
axes[0].plot([0, 100], [0, 100], "--", color="0.500", label="無作為")
axes[0].set(title="図8a 累積ゲイン(テスト)", ylabel="見つけた解約者の割合 (%)")
axes[1].plot(fraction * 100, lift, color=BLUE)
axes[1].axhline(1, color="0.500", linestyle="--", label="無作為")
axes[1].set(title="図8b リフト(テスト)", ylabel="無作為に対する倍率")
for ax in axes:
ax.axvline(fraction[k - 1] * 100, color=ORANGE, linestyle=":", label="上位約20%")
ax.set_xlabel("スコア上位から選ぶ顧客の割合 (%)")
ax.legend()
save_svg(fig, "08_gain_lift.svg")
$$\mathrm{Gain}(k)=\frac{\text{上位}k\text{人に含まれる解約者数}}{\text{全解約者数}},\qquad\mathrm{Lift}(k)=\frac{\mathrm{Gain}(k)}{k/N}$$
{'リフト': '2.39', '上位約20%の人数': 282, '解約者の捕捉割合': '0.479'}
4.3 Check the action’s effect and profitability
After selecting candidates, test separately whether contacting them reduces churn. In the book’s hypothetical A/B test, active candidates are randomly assigned to two groups of 1,000. Assume 200 cancellations over three months with usual treatment and 150 with the action. These are not results from the Telco data.
The churn-rate difference is five percentage points, corresponding to an estimated 50 additional retained customers. We do not count all 850 retained customers in the treatment group as caused by the action. A normal approximation for two independent proportions gives a 95% confidence interval.
show_math(r"""\(\begin{aligned}
\widehat r_C&=\frac{200}{1000}=0.200,\qquad
\widehat r_T=\frac{150}{1000}=0.150\\
\widehat{\Delta r}&=0.200-0.150=0.0500,\qquad
N\widehat{\Delta r}=1000\times0.0500=50\\
\mathrm{SE}&=\sqrt{\frac{0.200(1-0.200)}{1000}
+\frac{0.150(1-0.150)}{1000}}\approx0.0170\\
\mathrm{CI}_{95\%}&=\widehat{\Delta r}\pm z_{0.975}\mathrm{SE}
\approx[0.0168,\ 0.0832]
\end{aligned}\)""")
# 仮想実験の集計値から計算する。途中の値は丸めない。
n = 1000
rate_control, rate_treatment = 200 / n, 150 / n
delta = rate_control - rate_treatment
se = np.sqrt(rate_control * (1 - rate_control) / n
+ rate_treatment * (1 - rate_treatment) / n)
ci = delta + np.array([-1, 1]) * norm.ppf(0.975) * se
pprint({"改善幅の95%信頼区間(ポイント)": [sig3(v * 100) for v in ci]})
$$\begin{aligned} \widehat r_C&=\frac{200}{1000}=0.200,\qquad \widehat r_T=\frac{150}{1000}=0.150\\ \widehat{\Delta r}&=0.200-0.150=0.0500,\qquad N\widehat{\Delta r}=1000\times0.0500=50\\ \mathrm{SE}&=\sqrt{\frac{0.200(1-0.200)}{1000} +\frac{0.150(1-0.150)}{1000}}\approx0.0170\\ \mathrm{CI}_{95\%}&=\widehat{\Delta r}\pm z_{0.975}\mathrm{SE} \approx[0.0168,\ 0.0832] \end{aligned}$$
{'改善幅の95%信頼区間(ポイント)': ['1.68', '8.32']}
Assume the present value of additional gross profit per extra retained customer, $g$, is ¥20,000, and the cost per targeted customer, $c$, is ¥500. Gross profit covers the next 12 months and is not directly estimated from the three-month comparison. The action costs money for every targeted customer.
show_math(r"""\(\begin{aligned}
\Pi&=N\Delta r g-Nc\\
&=1000\times0.0500\times20000-1000\times500\\
&=1000000-500000=500000\ \mathrm{yen}\\
\Pi=0&\ \Longleftrightarrow\ N\Delta r g=Nc
\ \Longleftrightarrow\ \Delta r=\frac{c}{g}
=\frac{500}{20000}=0.0250
\end{aligned}\)""")
margin, cost = 20000, 500
profit = n * delta * margin - n * cost
profit_ci = n * ci * margin - n * cost
pprint({"利益の試算(円)": f"{profit:,.0f}",
"改善幅の区間に対応する利益の幅(万円)": [sig3(v / 10000) for v in profit_ci]})
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
bars = axes[0].bar(["通常対応", "施策あり"], [100 * rate_control, 100 * rate_treatment],
color=[BLUE, ORANGE])
axes[0].bar_label(bars, labels=["20.0%", "15.0%"], padding=4)
axes[0].set(title="図9a 仮想A/Bテスト", ylabel="3か月の解約率 (%)", ylim=(0, 25))
improvements = np.linspace(0, 0.100, 101)
axes[1].plot(100 * improvements, (n * improvements * margin - n * cost) / 10000, color=BLUE)
axes[1].errorbar(delta * 100, profit / 10000,
xerr=[[100 * (delta - ci[0])], [100 * (ci[1] - delta)]],
fmt="o", color=ORANGE, capsize=4, label="推定差と95%信頼区間")
axes[1].axhline(0, color="0.500", linestyle="--")
axes[1].axvline(100 * cost / margin, color=GREEN, linestyle=":", label="損益分岐 2.50ポイント")
axes[1].set(title="図9b 改善幅と利益の試算", xlabel="解約率の改善幅(ポイント)", ylabel="利益の増加額(万円)")
axes[1].legend(fontsize=9)
save_svg(fig, "09_ab_profit.svg")
$$\begin{aligned} \Pi&=N\Delta r g-Nc\\ &=1000\times0.0500\times20000-1000\times500\\ &=1000000-500000=500000\ \mathrm{yen}\\ \Pi=0&\ \Longleftrightarrow\ N\Delta r g=Nc \ \Longleftrightarrow\ \Delta r=\frac{c}{g} =\frac{500}{20000}=0.0250 \end{aligned}$$
{'利益の試算(円)': '500,000', '改善幅の区間に対応する利益の幅(万円)': ['-16.5', '116.']}
Estimated profit is ¥500,000, with break-even at a 2.50-percentage-point reduction in churn. Mapping the churn-rate interval to profit gives about −¥165,000 to ¥1.16 million. This range holds the gross-profit and cost assumptions fixed and does not establish a clearly positive profit. Reports of improved churn should also show costs for all targeted customers.
Conclusion
This article introduced a workflow for analyzing retention time, ranking candidates by churn scores, and separately checking an action’s effect and profitability.
Prediction accuracy alone cannot justify expanding an action. Chapter 7 covers censoring and model assumptions through the testing of customer interventions. Further explanation and the full code are available in the book and its Chapter 7 support notebook .
Data source: IBM, Telco Customer Churn (Apache License 2.0), using the CSV distributed with the book.