【发布时间】:2023-02-04 00:48:18
【问题描述】:
我想根据两列预测客户流失。一个 - total_day_minutes,显示总分钟数(客户说话的时间)和流失 - 1:客户离开我们,0:客户没有离开我们。在探索我的约会对象期间,我遇到了一些异常值。 enter image description here。在第一张图中,您可以看到一些异常值,这些值没有对齐。我决定清理它们并使用以下代码进行逻辑回归:
不幸的是,当我制作一条 S 曲线并决定将其绘制在我的图表上作为一条垂直线时 - 它看起来很奇怪,因为阈值线位于 S 曲线的顶部。我究竟做错了什么?
我的 S 曲线截图和逻辑回归结果 - enter image description here
在这次观察结束时,我必须找出哪些客户可能很快就会离开我(基于这两列和逻辑回归)。应该是他们开始离开我的时候了。 (话多话少的人离我而去?)
提前致谢。
# cleaning outliers
Q1 = df_data['total_day_minutes'].quantile(0.25)
Q3 = df_data['total_day_minutes'].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 2 * IQR
upper_bound = Q3 + 2 * IQR
# filter the data within the bounds
df_filtered2 = df_data[(df_data['total_day_minutes'] >= lower_bound) &
(df_data['total_day_minutes'] <= upper_bound)]
# define the dependent and independent variables
y = df_filtered2['churn']
X = df_filtered2['total_day_minutes']
# add a constant term to X
X = sm.add_constant(X)
# transform the independent variable
#X['total_day_minutes'] = np.log(X['total_day_minutes'])
# fit the logistic regression model
result = sm.Logit(y, X).fit()
# print the model summary
print(result.summary())
# get the minimum and maximum values of X
x_min = X['total_day_minutes'].min()
x_max = X['total_day_minutes'].max()
# create a new range of values for X
X_new = pd.DataFrame({'total_day_minutes': np.linspace(x_min, x_max, 1000)})
X_new = X_new.astype(float)
# add a constant term to X_new
X_new = sm.add_constant(X_new)
# predict the probabilities of churn for X_new
y_pred = result.predict(X_new)
# plot the S-curve
plt.plot(X_new['total_day_minutes'], y_pred, label='S-curve')
plt.xlabel('Total Day Minutes')
plt.ylabel('Probability of Churn')
# calculate and plot the threshold value
threshold_value = np.exp(X_new.loc[y_pred[y_pred >= 0.5].index[0]]['total_day_minutes'])
print(threshold_value)
plt.axhline(y=threshold, color='black', linestyle='--', label='Threshold')
plt.legend()
plt.show()
【问题讨论】:
标签: python pandas regression logistic-regression curve