使用XGBT构建——互联网金融客户流失模型

本文介绍如何利用XGBT算法构建一个互联网金融领域的客户流失预测模型,通过详细的数据分析和建模过程,帮助理解用户行为,降低客户流失率。

点击下载是所需数据

from pandas import DataFrame
from numpy import nan as NA
from pandas import Series
import os 
import pandas as pd
import numpy as  np
import math
import random
from matplotlib import pyplot
from pandas.tools.plotting import scatter_matrix
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm
from scipy.stats import chisquare
import numbers
import time
import datetime
from sklearn.preprocessing import LabelEncoder
import xgboost as xgb
from sklearn.metrics import accuracy_score
from xgboost import XGBClassifier
from sklearn.model_selection import KFold
from sklearn.cross_validation import cross_val_score
from sklearn.grid_search import GridSearchCV
from sklearn.model_selection import StratifiedKFold
#解决输出图片不能为含有中文
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

os.chdir('E://kaggle//risk')
bank_data=pd.read_csv('bankChurn_1.csv')
external_data=pd.read_csv('ExternalData_1.csv')
internal_dic=pd.read_csv('internal_dic.csv')
external_dic=pd.read_csv('external_dic.csv')
path='E://kaggle//risk//'

#观测单因子因素变量分布
#df--数据集
#col--需要研究的变量
#target--目标变量
#filepath--保存路径
#truncation-是否处理极端数据
def NumVarPerf(df,col,target,filepath,truncation=True):
    #塞选出有效数据集
    validDf = df.loc[df[col] == df[col]][[col,target]]
    #测算有效数据集百分比,这里乘以1.0是因为python整数与整数相除还是整数,此举可以让结果变成浮点数。
    validRcd=validDf.shape[0]*1.0/df.shape[0]
    #以百分好数字输出  
    validRcdFmt='%.2f%%' %(validRcd*100)
    #查看与提取一些统计量
    descStats=validDf[col].describe()
    mu='%.2e' % (descStats['mean'])
    std='%.2e' % (descStats['std'])
    maxVal= '%.2e' % (descStats['max'])
    minVal = '%.2e' % (descStats['min'])
    #类别型目标变量,不同类别所要研究自变量的数据,以下代码只适合两分类,且数字分别为0和1
    x=validDf.loc[validDf[target] == 1][col]
    y=validDf.loc[validDf[target] == 0][col]
    #设定每个值的权重
    xweights = 100*np.ones_like(x)/x.size
    yweights = 100*np.ones_like(y)/y.size
    #如果truncation为True,启用下方功能,主要作用是将超过95%分为点的数值改为95%分为点数值
    if  truncation == True:
        pcnt95=np.percentile(validDf[col],95)
        x=x.map(lambda x: min(x,pcnt95))
        y=y.map(lambda y: min(y,pcnt95))
    #使用matplotlib画图
    #创建图画对象
    flg1=pyplot.figure()
    ax=flg1.add_subplot(111)
    #画条形图
    ax.hist(x,weights=xweights,alpha=0.5,label='流失客户')
    ax.hist(y,weights=yweights,alpha=0.5,label='留存客户')
    titleText = '是'+merge_dic[col]+'的条形图'+'\n'+'有效数据收集百分比为:'+str(validRcdFmt)+','+'Mean='+str(mu)+','+'Std='+str(std)
    ax.set(title=titleText,ylabel='各数据分类百分比')
    ax.margins(0.05)
    ax.set_ylim(bottom=0)
    pyplot.legend(loc='upper right')
    figSavePath=filepath+str(merge_dic[col])+'--'+str(col)+'.png'
    pyplot.savefig(f
### XGBoost与GBDT的差异与联系 #### 差异 1. **目标函数** GBDT 是一种通用框架,允许使用任意可导损失函数进行优化。而 XGBoost 在目标函数中引入了正则化项,不仅考虑了预测误差,还对模型复杂度进行了惩罚[^1]。这使得 XGBoost 能够更有效地避免过拟合。 2. **分裂点选择** GBDT 通常通过贪心算法来选择最佳分裂点,计算量较大。XGBoost 提出了近似分裂方法,利用二阶导数信息(Hessian)和权重加权的直方图技术,显著提升了计算效率和精度[^2]。 3. **并行处理** GBDT 的训练过程本质上是串行的,因为每一棵树都依赖于前一棵树的残差。XGBoost 引入了列块预排序和缓存机制,支持多线程并行计算,从而大幅提高了训练速度[^3]。 4. **缺失值处理** XGBoost 内置了对缺失值的支持,在节点分裂时自动学习最优方向。而传统 GBDT 需要额外预处理或手动指定缺失值的处理方式[^4]。 5. **正则化** XGBoost 明确在目标函数中加入了 L1 和 L2 正则化项,而 GBDT 没有直接的正则化机制。这种改进增强了模型的泛化能力[^5]。 6. **自定义损失函数** XGBoost 支持用户自定义目标函数和评估指标,灵活性更高。GBDT 则需要开发者自行实现新的损失函数[^6]。 #### 联系 1. **核心思想** 两者都基于梯度提升的思想,通过迭代的方式构建多棵决策树,每棵树试图纠正前一棵树的误差[^7]。 2. **弱学习器** XGBoost 和 GBDT 都以决策树作为基本弱学习器,通过组合多棵树形成强学习器[^8]。 3. **加法模型** 两种方法均采用加法模型的形式,逐步叠加每棵树的贡献以逼近真实目标函数[^9]。 4. **适用场景** 它们广泛应用于分类、回归以及排序等任务,尤其在结构化数据上表现出色[^10]。 ```python import xgboost as xgb from sklearn.ensemble import GradientBoostingClassifier # 示例代码:XGBoost 训练 dtrain = xgb.DMatrix(X_train, label=y_train) param = {'max_depth': 6, 'eta': 0.1, 'objective': 'binary:logistic'} bst = xgb.train(param, dtrain, num_boost_round=100) # 示例代码:GBDT 训练 gbdt = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=6) gbdt.fit(X_train, y_train) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值