利用python建立客户流失预警模型(下)——建立模型
前言
上一部分已经完成了对数据的整理与分析,接下来建立数据分析模型。
首先,建立分类模型来预测客户是否会流失。逻辑回归,决策树,随机森林,xgboost等可用于分类问题(也可用于回归问题)。由于不是所有模型在所有样本预测均为最优,可考虑使用模型融合。在建模时,通过交叉验证训练集来得到模型最优的参数。对于阈值的设置可考虑KS曲线的最大值。
其次是客户画像,在筛选后的变量中挑选少量综合性变量,通过样本间的聚类仿照RFM模型的想法得到客户大体的定位,比如重要价值客户、重要保持客户等,然后根据集中度、活跃度等给客户加小标签,根据总体的标签以及客户流失与否给出业务层面的意见。
客户流失预测模型
1、logistic回归
建立模型,通过交叉验证、网格搜索来寻求最优参数,用于拟合最优模型
#LogisticRegression
lr = LogisticRegression(n_jobs=-1,random_state=666,solver='saga',penalty='l1')
c_v=KFold(len(y_train),n_folds=10,random_state=666)
parameter_grid={'C':[0.1,1,10],'max_iter':[100,500,1000]} #参数可调
gridsearch_b=GridSearchCV(lr,param_grid=parameter_grid,cv=c_v,scoring='f1',n_jobs=-1)
gridsearch_b.fit(x_train,y_train)
best_param_b=gridsearch_b.best_params_
best_lr=LogisticRegression(n_jobs=-1,random_state=666,solver='saga',penalty='l1',C=0.1,max_iter=100)
用生成的最优模型在测试机上进行预测:
best_lr.fit(x_train,y_train)
yhat_test_lr=best_lr.predict(x_test) #预测结果
confusion_matrix(y_test,yhat_test_lr) #混淆矩阵
yp_test_lr=best_lr.predict_proba(x_test) #预测概率
衡量logistic回归进行分类的精度的指标:AUC,recall,precision等
fpr_lr,tpr_lr,threshold_lr=roc_curve(y_test,yp_test_lr[:,1])
auc(fpr_lr,tpr_lr) #AUC
accuracy_score(y_test,yhat_test_lr) #准确度
recall_score(y_test,yhat_test_lr) #recall
precision_score(y_test,yhat_test_lr) #precision
f1_score(y_test,yhat_test_lr) #f1
2、决策树(原始变量等权重决策树)
训练决策树模型,寻求参数拟合最优模型
dtc_unb=DecisionTreeClassifier(random_state=666)
c_v=KFold(len(y_train),n_folds=10,random_state=666)
#参数可调
parameter_grid={'max_depth':list(range(3,10)),'min_samples_split':list(range(10,81,10))}
gridsearch_unb=GridSearchCV(dtc_unb,param_grid=parameter_grid,cv=c_v,scoring='recall',n_jobs=-1)
gridsearch_unb.fit(x_train,y_train)
best_param_unb=gridsearch_unb.best_params_
best_dtc_unb=DecisionTreeClassifier(random_state=666,max_depth=3,min_samples_split=10)
best_dtc_unb.fit(x_train,y_train)
拟合的最有模型在测试集上进行预测:
yhat_test_unb=best_dtc_unb.predict(x_test) #预测结果
confusion_matrix(y_test,yhat_test_unb) #混淆矩阵
yp_test_unb=best_dtc_unb.predict_proba(x_test) #预测概率
评价模型结果:
fpr_unb,tpr_unb,threshold_unb=roc_curve(y_test,yp_test_unb[:,1])
roc_auc_unb=auc(fpr_unb,tpr_unb) #AUC值
accuracy_score(y_test,yhat_test_unb) #准确率
recall_score(y_test,yhat_test_unb) #recall
precision_score(y_test,yhat_test_unb) #precision
f1_score(y_test,yhat_test_unb) #f1
画出决策树,并保存为pdf格式的图片
dot_data=tree.export_graphviz(best_dtc_unb,out_file=None,
feature_names=list(train)[1:],
class_names=True,precision=5,
filled=True,impurity=True,
rounded=True,rotate=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf('dtcb.pdf')
3、随机森林
RF=RandomForestClassifier(random_state=666,max_depth=5,n_jobs=-1,max_features=0.6)
c_v=KFold(len(y_train),n_folds=10,random_state=666)
parameter_grid={'n_estimators':list(range(10,101,10))}
gridsearch_b=GridSearchCV(RF,param_grid=parameter_grid,cv=c_v,scoring='recall',n_jobs=-1)
gridsearch_b.fit(x_train,y_train)
best_param_b=gridsearch_b.best_params_
best_RF=RandomForestClassifier(n_estimators=10,random_state=666,max_depth=3,n_jobs=-1,max_features=0.6)
best_RF.fit(x_train,y_train)
训练出最优模型后,预测并评价模型:
yhat_test_RF=best_RF.predict(x_test) #预测结果
confusion_matrix(y_test,yhat_test_RF) #混淆矩阵
yp_test_RF=best_RF.predict_proba(x_test)#预测概率
fpr_RF,tpr_RF,threshold_RF=roc_curve(y_test,yp_test_RF[:,1])
auc(fpr_RF,tpr_RF) #AUC
accuracy_score(y_test,yhat_test_RF) #准确度
recall_score(y_test,yhat_test_RF) #recall
precision_score(y_test,yhat_test_RF) #precision
f1_score(y_test,yhat_test_RF) #f1
4、模型融合:
由于不是所有模型在所有样本预测均为最优,可考虑使用模型融合,当然最终看效果来定。一般使用一些普通模型作为一级基模型,得到的预测结果输入如xgboost这样的模型作为二级模型来起到模型融合提升的效果。
1)集成思想:将多个学习模型进行组合已获得更好的效率,使组合后的模型更具有泛化能力。
2)XGBoost(extreme gradient boosting极端梯度提升):是对GBDT的改进,以CART为基分类器,将模型上次预测产生的误差作为参考进行下一棵树的建立,是一种加法模型。既可用于分类也可用于回归。
3)模型融合——Stacking
思想:训练模型来学习使用底层学习器的预测结果,次学习器会基于基模型结果在训练
步骤:a、首先将数据集分为训练集和测试集;b、在训练集上进行交叉验证训练各个基学习器,再在测试集上做预测,结果取加权平均;c、基于每个基模型的预测结果作为特征,次学习器会训练如何给各个基学习器赋权重,使得最后的预测效果达到最佳。
特点:不需要太多的调参和特征选择;可通过添加正则项有效对抗过拟合;效果好。
#xgboost+stacking
xg=XGBClassifier(learning_rate=0.01,eval_metric='auc',gamma=0,
subsample=0.7,colsample_bytree=0.1,objective='binary:logistic',
random_state=666,silent=1,n_estimators=500)
SC = StackingClassifier(classifiers=[best_dtc_unb,best_RF,best_lr,best_RF_ada,
best_dtc_ada],meta_classifier=xg,use_probas=True)
c_v=StratifiedKFold(y_train,n_folds=10,random_state=666)
parameter_grid={'meta-xgbclassifier__max_depth':list(range(3,6)),
'meta-xgbclassifier__min_child_weight':list(range(1,4))}
gridsearch=GridSearchCV(SC,param_grid=parameter_grid,cv=c_v,scoring='recall',n_jobs=-1)
gridsearch.fit(x_train,y_train)
best_param=gridsearch.best_params_
拟合最优模型:
best_xg=XGBClassifier(learning_rate=0.01,eval_metric='auc',max_depth=3,
min_child_weight=1,gamma=0,subsample=0.6,
objective='binary:logistic',colsample_bytree=0.1,
random_state=666,silent=1,reg_alpha=0.01,reg_lambda=0.01,
n_estimators=500)
SC = StackingClassifier(classifiers=[best_dtc_unb,best_lr],
meta_classifier=best_xg,use_probas=True)
SC.fit(x_train, y_train)
模型预测与评价
yhat_SC=SC.predict(x_test)
confusion_matrix(y_test,yhat_SC)
yp_SC=SC.predict_proba(x_test)
fpr_xgl,tpr_xgl,threshold_xgl=roc_curve(y_test,yp_SC[:,1])
auc(fpr_xgl,tpr_xgl)
accuracy_score(y_test,yhat_SC)
recall_score(y_test,yhat_SC)
precision_score(y_test,yhat_SC)
f1_score(y_test,yhat_SC)
客户画像
思路:在筛选后的变量中挑选少量综合性变量,通过样本间的聚类仿照RFM模型的想法得到客户大体的定位,比如重要价值客户、重要保持客户等,然后根据集中度、活跃度等给客户加小标签,根据总体的标签以及客户流失与否给出业务层面的意见。(涉及到数据集的指标等信息,代码不在展示)