美文网首页
电信用户流失预测

电信用户流失预测

作者: 小鱼普拉斯 | 来源:发表于2021-03-22 15:51 被阅读0次

    做个数据分析项目

    项目背景:为了做分类任务在kaggle上找了这个数据集(https://www.kaggle.com/blastchar/telco-customer-churn),顺手尝试数据探索分析(EDA),期待能发现一些有意思的结论。此数据集共包含7031条数据,20个输入特征,1个目标特征。此项目主要分为数据处理、EDA和建模预测三部分,为了找出影响电信用户流失的关键因素,并最后给出相应的运营建议。

    1.数据处理

    1.1倒入数据
    #导入数据
    telecom = pd.read_csv("./Telco-Customer-Churn.csv")
    #查看数据格式,表头名称
    print(telecom.shape)
    print(telecom.columns)
    #显示全部列
    pd.set_option('display.max_columns', None)
    telecom.head()
    
    telecomHead.png
    #查看用户流失比例
    plt.figure(figsize=[9,7])
    telecom['Churn'].value_counts().plot.pie(autopct="%.2f%%")
    plt.show()
    
    电信用户流失比例.png
    1.2数据清洗

    修正数据类型、去空值、去重

    #查看数据信息
    telecom.info()
    #此处发现明显错误,totalcharge格式不应为object,遂将其改为float格式
    telecom.TotalCharges = pd.to_numeric(telecom.TotalCharges,errors='coerce')
    
    #查看是否具有空置
    telecom.drop_duplicates('customerID')
    #存在11个空置,由于数量非常小,因此选择全部删除/否则应根据数据分布形态选择填充方式
    telecom.dropna(inplace=True)
    #删除重复值
    telecom.drop_duplicates('customerID')
    #监测连续型数据是否存在异常值
    telecom.describe()
    

    2.数据探索性分析

    数据暂时处理完毕,待建模预测前再进行one-hot编码处理。

    2.1明确分析思路

    其实提到电信用户流失的原因,不是用户自身的原因,就是用户觉得服务商有这样那样的问题。结合本案例中具体20条输入特征,我将全部特征主要分为以下三个部分:用户相关特征、服务相关特征、合约相关特征。


    featureOfTelecom.png
    2.2用户相关特征分析

    如下图所示:
    性别对流失与否几乎无影响。
    老年用户、未婚用户、无小孩用户流失率更高。
    流失用户的在网时间呈偏左分布,普遍在10个月以下。

    fig,axes=plt.subplots(2,2,figsize=(12,12))
    sns.countplot(x='gender',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[0,0])
    sns.countplot(x='SeniorCitizen',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[0,1])
    sns.countplot(x='Partner',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[1,0])
    sns.countplot(x='TechSupport',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[1,1])
    
    sns.boxplot( x=telecom["Churn"], y=telecom["tenure"])
    
    2.3服务相关特征分析

    手机服务对流失并无明显影响。而没有设备保护的用户流失率明显更高。
    拥有使用光缆、无网络安全、无在线备份、无技术支持特征的用户流失率更高。
    是否多线路、以及是否使用流电视、流电影对用户流失率无明显影响。

    services = ['PhoneService','MultipleLines','InternetService','OnlineSecurity',
               'OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies']
    
    fig, axes = plt.subplots(nrows = 3,ncols = 3,figsize = (15,12))
    for i, item in enumerate(services):
        if i < 3:
            sns.countplot(x=item,hue='Churn',data=telecom,ax=axes[i,0])
            
        elif i >=3 and i < 6:
            sns.countplot(x=item,hue='Churn',data=telecom,ax=axes[i-3,1])
            
        elif i < 9:
            sns.countplot(x=item,hue='Churn',data=telecom,ax=axes[i-6,2])
    
    2.4合约相关特征分析

    如下图所示,合约签约时间越短流失率越高,其中月签约用户流失率超过30%;使用纸质账单的用户流失率更高;
    使用电子支付的用户流失率高达45%,其他支付方式的用户流失率都与整体流失率无明显差别。
    流失率随着费用增大而增大,在月费用80-100之间用户流失最严重。

    fig,axes=plt.subplots(3,1,figsize=(10,10))
    sns.countplot(x='Contract',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[0])
    sns.countplot(x='PaperlessBilling',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[1])
    sns.countplot(x='PaymentMethod',hue='Churn',data=telecom,hue_order=['Yes','No'],ax=axes[2])
    
    fig,axes=plt.subplots(1,2,figsize=(15,6))
    ax1=sns.kdeplot(telecom.MonthlyCharges[(telecom["Churn"] == 'No') ],
                    color="Red", shade = True,ax=axes[0])
    ax1= sns.kdeplot(telecom.MonthlyCharges[(telecom["Churn"] == 'Yes') ],
                    color="Blue", shade= True,ax=ax1)
    ax1.legend(["Not Churn","Churn"],loc='upper right')
    ax1.set_ylabel('Density')
    ax1.set_xlabel('tenure')
    ax1.set_title('Distribution of Monthly Charges by churn')
    
    ax2=sns.kdeplot(telecom.TotalCharges[(telecom["Churn"] == 'No') ],
                    color="Red", shade = True,ax=axes[1])
    ax2= sns.kdeplot(telecom.TotalCharges[(telecom["Churn"] == 'Yes') ],
                    color="Blue", shade= True,ax=ax2)
    ax2.legend(["Not Churn","Churn"],loc='upper right')
    ax2.set_ylabel('Density')
    ax2.set_xlabel('tenure')
    ax2.set_title('Distribution of Total Charges by churn')
    
    telecom[['MonthlyCharges', 'TotalCharges']].plot.scatter(x = 'MonthlyCharges',y='TotalCharges')
    

    从下图可以发现:
    用户流失率、月均消费、总消费总体均随着使用时间增大而增长;
    当用户使用时长超过70个月之后,用户价值得到极大的提升,说明长期来看,相比拉新、引导用户升级套餐,降低用户流失率能给公司带来更大的收益。

    telecom_clv=telecom.copy()
    itelcom=telecom_clv.loc[Telco_Data_LTV.tenure==0].index
    telecom_clv.loc[IDXtelco,'tenure']=1
    telecom_clv['ChurnRate']=telecom_clv.groupby('tenure')['Churn'].agg(np.mean)
    telecom_clv['MonthlyChargesAvg']=telecom_clv.groupby('tenure')['MonthlyCharges'].agg(np.mean)
    telecom_clv['TotalChargesAvg']=telecom_clv.groupby('tenure')['TotalCharges'].agg(np.mean)
    telecom_clv['CLV']=telecom_clv['TotalChargesAvg']/telecom_clv['ChurnRate']
    fig,ax=plt.subplots(2,2,figsize=(10,10))
    telecom_clv.ChurnRate.plot(ax=ax[0,0],title='ChurnRate')
    telecom_clv.MonthlyChargesAvg.plot(ax=ax[0,1],title='MonthlyChargesAvg')
    telecom_clv.TotalChargesAvg.plot(ax=ax[1,0],title='TotalChargesAvg')
    telecom_clv.CLV.plot(ax=ax[1,1],title='CLV ')
    
    2.5总结

    拥有以下特征的用户流失率更高:
    用户层面:老年、未婚、无子、已使用时长小于10个月
    服务层面:未使用设备保护、网络安全、在线备份、技术支持、以及使用光缆
    合约层面:按月签约、电子支付、月费用在80-100之间

    3.建模预测

    3.1 数据处理
    #处理目标特征,对输入特征进行one-hot编码
    telecom['Churn'].replace(to_replace='Yes', value=1 , inplace=True)
    telecom['Churn'].replace(to_replace='No', value=0, inplace=True)
    telecom_dummies = pd.get_dummies(telecom.iloc[:,1:])
    telecom_dummies.head()
    
    #查看各变量与label的相关性
    plt.figure(figsize=(15,8))
    telecom_dummies.corr()['Churn'].sort_values(ascending=False).plot(kind='bar')
    
    相关性系数.png
    3.2逻辑回归预测

    从逻辑回归与SVM模型得出的前十相关性来看,与EDA得出的影响用户流失的因素基本相吻合。除了流电视、流电影两类,从模型中相关性系数来看,这两类特征会增加用户流失率。但是单看这两类特征中的用户分布,使用流媒体的用户流失率是要低于未使用者的。

    #连续型变量归一化
    from sklearn.preprocessing import MinMaxScaler
    
    y=telecom_dummies['Churn'].values
    x=telecom_dummies.drop(columns='Churn')
    
    ss = MinMaxScaler()
    scale_features = x.columns.values
    x[scale_features] = ss.fit_transform(x[scale_features])
    
    #数据集拆分
    from sklearn.model_selection import train_test_split
    from sklearn.feature_selection import SelectFromModel
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=None)
    
    #逻辑回归
    from sklearn.linear_model import LogisticRegression
    model = LogisticRegression()
    result=model.fit(x_train,y_train)
    
    from sklearn import metrics
    prediction_test = model.predict(x_test)
    
    print (metrics.accuracy_score(y_test, prediction_test))
    

    预测结果:0.8024164889836531

    weights = pd.Series(model.coef_[0],
                     index=x.columns.values)
    print (weights.sort_values(ascending = False)[:10].plot(kind='bar'))
    
    相关性
    3.3支持向量机预测
    from sklearn.svm import SVC
    
    model.svm = SVC(kernel='linear') 
    model.svm.fit(x_train,y_train)
    preds = model.svm.predict(x_test)
    print(metrics.accuracy_score(y_test, preds))
    
    weights = pd.Series(model.coef_[0],
                     index=x.columns.values)
    print (weights.sort_values(ascending = False)[:10].plot(kind='bar'))
    

    预测结果:0.7995735607675906


    相关性

    4.运营建议

    (1)在用户层面,对于老年、未婚、无亲属、已在网时间小于10个月的用户,可以尝试推出一些限时优惠活动。可以进一步查看该类用户在各类服务上的使用情况,查看是否存在流失率不同的情况。如果存在,可针对该类用户尝试推出一些定制化套餐。
    (2)在服务层面需要注意的是,使用光缆的用户有很高的流失率,应该对该产品的质量问题和客户对该产品的满意度进行检查。对于其他类似网络安全、在线备份等技术,同样进行客户满意度调查,进一步查看是否存在对其价格不满的情况。后续可以尝试限时优惠或者限时赠送的活动。
    (3)在合约层面,首先应该鼓励用户签订长期合同。其次,对于电子支付、无纸化流程进行检查,是否存在使用不便问题。毕竟考虑到目前的电子支付发展情况,不应该导致这么明显的用户流失率。

    相关文章

      网友评论

          本文标题:电信用户流失预测

          本文链接:https://www.haomeiwen.com/subject/kigzcltx.html