按照惯例,在写一篇自嗨的文章之前,总要酝酿一下前戏,哦不,是前言,是为下:众所周知,传统金融领域在制作信用卡评分模型时,最常用的是logistic,简单直观且比较容易做业务上的特征解释。自互联网金融兴起后,构建评分模型的特征变量呈现几何级数增长,包括金融属性相关的强变量(如人行征信报告,黑名单,共债等),以及非金融属性相关的弱变量(如客群特征,互联网消费行为等),因此单纯靠只具备线性特征的logistic模型,已经无法提升预测准确性,机器学习算法便应运而生,其中比较典型的包括两类:一类是以bagging为代表的机器学习算法,randomforest是其中代表;另外一类以boosting为代表,包括adboost;GBDT和XGBoosting,就预测精度和使用广泛性而言,XGBoosting最具有代表性,本文即以XGBoosting(下简称XGB)实现评分模型制作。主要步骤包括:
1. XGB模型训练
2. XGB模型验证
3. XGB模型文件格式化
4. XGB输出概率工程化
4. XGB输出概率的校正
5. 在线部署流程
废话不多,直接上代码。
1. XGB模型训练
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn import datasets
from pandas import DataFrame
from scipy import stats
from sklearn.linear_model import LogisticRegression
import statsmodels.formula.api as smf
np.random.seed(2)
n=100
df = pd.DataFrame({'x1':np.random.randn(n),
'x2': np.random.randn(n),
'x3': np.random.randn(n),
'label': np.random.randint(0,2,n)})
X = DataFrame(df[['x1','x2','x3']])
y = DataFrame(df['label'])
yt = len(df[df['label']==1])
print (float(yt/n))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
dtrain=xgb.DMatrix(X_train,label=y_train)
dtest=xgb.DMatrix(X_test)
params={'booster':'gbtree',
'objective': 'binary:logistic',
'eval_metric': 'auc',
'max_depth':4,
'lambda':10,
'subsample':1,
'colsample_bytree':1,
'min_child_weight':2,
'eta': 0.025,
'seed':0,
'nthread':8,
'silent':1}
watchlist = [(dtrain,'train')]
bst=xgb.train(params,dtrain,num_boost_round=10,evals=watchlist) #此处round设置为10只是为了说明后面的模型文件,一般最好设置为100左右</