为什么需要逻辑回归

R 中的回归入门

Richie Cotton

Data Evangelist 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
R 中的回归入门

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

mdl_churn_vs_recency_lm <- lm(has_churned ~ time_since_last_purchase, data = churn)
Call:
lm(formula = has_churned ~ time_since_last_purchase, data = churn)

Coefficients:
             (Intercept)  time_since_last_purchase  
                 0.49078                   0.06378 
coeffs <- coefficients(mdl_churn_vs_recency_lm)
intercept <- coeffs[1]
slope <- coeffs[2]
R 中的回归入门

可视化线性模型

ggplot(
  churn, 
  aes(time_since_last_purchase, has_churned)
) +
  geom_point() +
  geom_abline(intercept = intercept, slope = slope)

"预测"是流失概率,而非流失量。

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

R 中的回归入门

放大视图

ggplot(
  churn, 
  aes(days_since_last_purchase, has_churned)
) +
  geom_point() +
  geom_abline(intercept = intercept, slope = slope) +
  xlim(-10, 10) +
  ylim(-0.2, 1.2)

客户是否流失与上次购买距今时间的散点图。坐标轴相较之前放大范围,显示趋势线延伸到 y<0 和 y>1,这在逻辑上不应发生。

R 中的回归入门

什么是逻辑回归?

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

使用 glm() 的线性回归

glm(has_churned ~ time_since_last_purchase, data = churn, family = gaussian)
Call:  glm(formula = has_churned ~ time_since_last_purchase, family = gaussian, 
    data = churn)

Coefficients:
             (Intercept)  time_since_last_purchase  
                 0.49078                   0.06378  

Degrees of Freedom: 399 Total (i.e. Null);  398 Residual
Null Deviance:        100 
Residual Deviance: 98.02     AIC: 578.7
R 中的回归入门

逻辑回归:glm() 与二项分布族

mdl_recency_glm <- glm(has_churned ~ time_since_last_purchase, data = churn, family = binomial)
Call:  glm(formula = has_churned ~ time_since_last_purchase, family = binomial, 
    data = churn)

Coefficients:
             (Intercept)  time_since_last_purchase  
                -0.03502                   0.26921  

Degrees of Freedom: 399 Total (i.e. Null);  398 Residual
Null Deviance:        554.5 
Residual Deviance: 546.4     AIC: 550.4
R 中的回归入门

可视化逻辑模型

ggplot(
  churn, 
  aes(time_since_last_purchase, has_churned)
) +
  geom_point() +
  geom_abline(
    intercept = intercept, slope = slope
  ) +
  geom_smooth(
    method = "glm", 
    se = FALSE, 
    method.args = list(family = binomial)
  )

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

R 中的回归入门

放大视图

客户是否流失与上次购买距今时间的散点图,包含两条趋势线。坐标轴相较之前放大范围,显示逻辑趋势线始终不超出0到1的流失区间。

R 中的回归入门

Passons à la pratique !

R 中的回归入门

Preparing Video For Download...