为何需要逻辑回归

使用 Python 中的 statsmodels 进行回归入门

Maarten Van den Broeck

Content Developer at DataCamp

银行客户流失数据集

has_churned time_since_first_purchase time_since_last_purchase
0 0.3993247 -0.5158691
1 -0.4297957 0.6780654
0 3.7383122 0.4082544
0 0.6032289 -0.6990435
... ... ...
response length of relationship recency of activity
1 https://www.rdocumentation.org/packages/bayesQR/topics/Churn
使用 Python 中的 statsmodels 进行回归入门

流失 vs. 近期性:线性模型

mdl_churn_vs_recency_lm = ols("has_churned ~ time_since_last_purchase",
                              data=churn).fit()

print(mdl_churn_vs_recency_lm.params)
Intercept                   0.490780
time_since_last_purchase    0.063783
dtype: float64
intercept, slope = mdl_churn_vs_recency_lm.params
使用 Python 中的 statsmodels 进行回归入门

可视化线性模型

sns.scatterplot(x="time_since_last_purchase",
                y="has_churned",
                data=churn)

plt.axline(xy1=(0, intercept), slope=slope) plt.show()

客户是否流失与上次购买以来时间的散点图。所有点在 y=0 或 y=1 上。线性趋势线显示,随时间增加流失概率上升。

使用 Python 中的 statsmodels 进行回归入门

拉远视角

sns.scatterplot(x="time_since_last_purchase",
                y="has_churned",
                data=churn)

plt.axline(xy1=(0,intercept),
           slope=slope)

plt.xlim(-10, 10) plt.ylim(-0.2, 1.2)
plt.show()

同一散点图。坐标范围放大,显示线性趋势线延伸到 y<0 与 y>1,这是不可能的。

使用 Python 中的 statsmodels 进行回归入门

什么是逻辑回归?

  • 广义线性模型的另一种类型。
  • 当响应变量为逻辑型时使用。
  • 响应遵循逻辑(S 形)曲线。
使用 Python 中的 statsmodels 进行回归入门

使用 logit() 进行逻辑回归

from statsmodels.formula.api import logit
mdl_churn_vs_recency_logit = logit("has_churned ~ time_since_last_purchase",
                                   data=churn).fit()

print(mdl_churn_vs_recency_logit.params)
Intercept                  -0.035019
time_since_last_purchase    0.269215
dtype: float64
使用 Python 中的 statsmodels 进行回归入门

可视化逻辑模型

sns.regplot(x="time_since_last_purchase",
            y="has_churned",
            data=churn,
            ci=None,
            logistic=True)
plt.axline(xy1=(0,intercept),
           slope=slope,
           color="black")

plt.show()

客户是否流失与上次购买以来时间的散点图。显示线性与逻辑趋势线,二者都随时间增加而流失概率上升。除在较大时间处外,两条趋势线非常接近。

使用 Python 中的 statsmodels 进行回归入门

拉远视角

同一散点图及两条趋势线。坐标范围放大,显示逻辑趋势线始终在 0 到 1 的流失范围内。

使用 Python 中的 statsmodels 进行回归入门

开始练习!

使用 Python 中的 statsmodels 进行回归入门

Preparing Video For Download...