信用评分系统运行原理下篇
前言
信用评分系统运行原理上篇
信用评分系统运行原理中篇-分箱逻辑
绘制相关性系数热力图
corr = train.corr() # 计算各变量的相关性系数
xticks = ['x0','x1','x2','x3','x4','x5','x6','x7','x8','x9','x10'] # x轴标签
yticks = list(corr.index) # y轴标签
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1)
sns.heatmap(corr, annot=True, cmap='rainbow', ax=ax,
annot_kws={'size': 12, 'weight': 'bold', 'color': 'blue'}) # 绘制相关性系数热力图
ax.set_xticklabels(xticks, rotation=0, fontsize=12)
ax.set_yticklabels(yticks, rotation=0, fontsize=12)
plt.show()
上图可以看出变量之间的相关性都较小,但是 NumberOfOpenCreditLinesAndLoans 和 NumberRealEstateLoansOrLines 相对来说较大为0.43
将各个特征的IV值显示在柱状图上
ivlist = [ivx1, ivx2, ivx3, ivx4, ivx5, ivx6, ivx7, ivx8, ivx9, ivx10] # 各变量IV
index = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10'] # x轴的标签
fig1 = plt.figure(figsize=(8, 8))
ax1 = fig1.add_subplot(1, 1, 1)
x = np.arange(len(index)) + 1
ax1.bar(x, ivlist, width=0.4) # 生成柱状图
ax1.set_xticks(x)
ax1.set_xticklabels(index, rotation=0, fontsize=12)
ax1.set_ylabel('IV(Information Value)', fontsize=12)
# 在柱状图上添加数字标签
for a, b in zip(x, ivlist):
plt.text(a, b + 0.01, '%.4f' % b, ha='center', va='bottom', fontsize=10)
plt.show()
通过IV值判断变量预测能力的标准是:
< 0.02: unpredictive
0.02 to 0.1: weak
0.1 to 0.3: medium
0.3 to 0.5: strong
> 0.5: suspicious
DebtRatio、MonthlyIncome、NumberRealEstateLoansOrLines 和 NumberOfDependents 变量的IV值明显较低
WOE转换
证据权重(Weight of Evidence,WOE)转换可以将Logistic回归模型转变为标准评分卡格式
# 替换成woe函数
def replace_woe(series, cut, woe):
list = []
i = 0
while i < len(series):
value = series[i]
j = len(cut) - 2
m = len(cut) - 2
while j >= 0:
if value >= cut[j]:
j = -1
else:
j -= 1
m -= 1
list.append(woe[m])
i += 1
return list
train['RevolvingUtilizationOfUnsecuredLines'] = Series(
replace_woe(train['RevolvingUtilizationOfUnsecuredLines'], cutx1, woex1))
这段代码的意思是 获取每一行的值
依次和 0.75分位、0.5分位、0.25分位的值比较
要是当前值大于某一分位的值则记录该分位的值
交叉验证可以进行模型选择
概念
将训练数据集划分为K份,K一般为10
依次取其中一份为验证集,其余为训练集训练分类器,测试分类器在验证集上的精度
取K次实验的平均精度为该分类器的平均精度
导入库
# 导入逻辑回归
from sklearn.linear_model import LogisticRegression
# 导入分类器
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier
# k最近邻分类
from sklearn.neighbors import KNeighborsClassifier
创建分类器实例
knMod = KNeighborsClassifier(n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2,
metric='minkowski', metric_params=None)
lrMod = LogisticRegression(penalty='l1', dual=False, tol=0.0001, C=1.0, fit_intercept=True,
intercept_scaling=1, class_weight=None, random_state=None, solver='liblinear', max_iter=100,
multi_class='ovr', verbose=2)
adaMod = AdaBoostClassifier(base_estimator=None, n_estimators=200, learning_rate=1.0)
gbMod = GradientBoostingClassifier(loss='deviance', learning_rate=0.1, n_estimators=200, subsample=1.0,
min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_depth=3,
init=None, random_state=None, max_features=None, verbose=0)
rfMod = RandomForestClassifier(n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2,
min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto',
max_leaf_nodes=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None,
verbose=0)
使用分类算法cross_val_score
# 入参是训练数据信息
def cvDictGen(functions, scr, X_train=X_train, Y_train=Y_train, cv=10, verbose=1):
cvDict = {}
for func in functions:
# cross_val_score将交叉验证的整个过程连接起来,不用再进行手动的分割数据
# cv参数用于规定将原始数据分成多少份
cvScore = cross_val_score(func, X_train, Y_train, cv=cv, verbose=verbose, scoring=scr)
cvDict[str(func).split('(')[0]] = [cvScore.mean(), cvScore.std()]
return cvDict
cvD = cvDictGen(functions=[knMod, lrMod, adaMod, gbMod, rfMod], scr='roc_auc')
def cvDictNormalize(cvDict):
cvDictNormalized = {}
for key in cvDict.keys():
for i in cvDict[key]:
cvDictNormalized[key] = ['{:0.2f}'.format((cvDict[key][0] / cvDict[list(cvDict.keys())[0]][0])),
'{:0.2f}'.format((cvDict[key][1] / cvDict[list(cvDict.keys())[0]][1]))]
return cvDictNormalized
cvDictNormalize(cvD)
得到
cvD:
'KNeighborsClassifier': [0.5887365163416062, 0.011300179653818953], 'LogisticRegression': [0.8500902765971645, 0.0036164412715674102], 'AdaBoostClassifier': [0.8583319753215507, 0.004050825383307547], 'GradientBoostingClassifier': [0.8639129158346284, 0.003503053433053003], 'RandomForestClassifier': [0.7803945135123486, 0.010025212199131]}
平均值、方差
标准化处理结果:
{'KNeighborsClassifier': ['1.00', '1.00'], 'LogisticRegression': ['1.44', '0.33'], 'AdaBoostClassifier': ['1.46', '0.36'], 'GradientBoostingClassifier': ['1.47', '0.31'], 'RandomForestClassifier': ['1.33', '0.87']}
最优化超参数
导入库
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
AdaBoost模型
- 训练参数
ada_param = {'n_estimators': [10, 50, 100, 200, 400],
'learning_rate': [0.1, 0.05]}
- 模型训练
randomizedSearchAda = RandomizedSearchCV(estimator=adaMod, param_distributions=ada_param, n_iter=5,
scoring='roc_auc', cv=None, verbose=2).fit(X_train, Y_train)
RandomizedSearchCV参数说明,clf1设置训练的学习器
param_dist字典类型,放入参数搜索范围
scoring = 'roc_auc',精度评价方式设定为“roc_auc“
n_iter=300,训练300次,数值越大,获得的参数精度越大,但是搜索时间越长
n_jobs = -1,使用所有的CPU进行训练,默认为1,使用1个CPU
模型训练情况:
Fitting 5 folds for each of 5 candidates, totalling 25 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[CV] n_estimators=10, learning_rate=0.1 ..............................
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.5s remaining: 0.0s
[CV] ............... n_estimators=10, learning_rate=0.1, total= 0.5s
[CV] n_estimators=10, learning_rate=0.1 ..............................
[CV] ............... n_estimators=10, learning_rate=0.1, total= 0.5s
[CV] n_estimators=10, learning_rate=0.1
该算法返回:
randomizedSearchAda.best_params_, randomizedSearchAda.best_score_
best_params_ = {'n_estimators': 200, 'learning_rate': 0.1}
输出最优训练器的精度
best_score_ = 0.8583
GB模型
gbParams = {'loss': ['deviance', 'exponential'],'n_estimators': [10, 50, 100, 200, 400],'max_depth': randint(1, 5),'learning_rate': [0.1, 0.05]}
randomizedSearchGB = RandomizedSearchCV(estimator=gbMod, param_distributions=gbParams, n_iter=10,scoring='roc_auc', cv=None, verbose=2).fit(X_train, Y_train)
randomizedSearchGB.best_params_, randomizedSearchGB.best_score_
训练的过程
Fitting 5 folds for each of 1 candidates, totalling 5 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200
[CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200, total= 12.4s
[CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 12.4s remaining: 0.0s
[CV] learning_rate=0.1, loss=exponential, max_depth=2, n_estimators=200, total= 12.8s
randomizedSearchGB.best_params_, randomizedSearchGB.best_score_
best_params_= {'learning_rate': 0.1, 'loss': 'exponential', 'max_depth': 2, 'n_estimators': 200}
best_score_=0.8634
用最优的分类容再训练数据
bestGbModFitted = randomizedSearchGB.best_estimator_.fit(X_train, Y_train)
bestAdaModFitted = randomizedSearchAda.best_estimator_.fit(X_train, Y_train)
再评估模型
cvDictHPO = cvDictGen(functions=[bestGbModFitted, bestAdaModFitted], scr='roc_auc')
cvDictHPO: {'GradientBoostingClassifier': [0.8266652916225066, 0.0051271698988066315], 'AdaBoostClassifier': [0.8551661366453513, 0.003975186847574813]}
数据标准化
cvDictNormalize(cvDictHPO)
cvDictNormalized: {'GradientBoostingClassifier': ['1.00', '1.00'], 'AdaBoostClassifier': ['1.03', '0.78']}
画ROC曲线
代码
def plotCvRocCurve(X, y, classifier, nfolds=5):
# 导入roc_curve(roc曲线库)、auc面积库
from sklearn.metrics import roc_curve, auc
# 导入StratifiedKFold k折交叉拆分 分层采样,确保训练集,测试集中各类别样本的比例与原始数据集中相同
from sklearn.model_selection import StratifiedKFold
# 导入画图 pyplot库
import matplotlib.pyplot as plt
# cv = StratifiedKFold(y, n_folds=nfolds)
cv = StratifiedKFold(n_splits=4, random_state=0, shuffle=True)
mean_tpr = 0.0
# 在指定的间隔内返回均匀间隔的数字
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# 0-1之间 100个数字 均匀间隔的数字
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
# for i, (train, test) in enumerate(cv):
i = 0
# 分层拆分数据集 为 训练集和测试集 确保拆分后的数据集和原始数据中的比例相同
for train, test in cv.split(X, y):
# 使用 梯度提升树GradientBoostingClassifier算法 训练数据
# 使用测试数据进行预测
probas_ = classifier.fit(X.iloc[train], y.iloc[train]).predict_proba(X.iloc[test])
# 根据预测结果和实际结果计算阈值、fpr(实际样本中预测错误的样本比例)、tpr(等于recall 实际的样本中预测正确的样本所在比例)
# 假如阈值是 0.2 小于0.2的值 认为是错误的 大于0.2的值表示正确的 则就可以计算这个阈值下的tpr和fpr了
fpr, tpr, thresholds = roc_curve(y.iloc[test], probas_[:, 1])
# 一维线性插值.
# 返回离散数据的一维分段线性插值结果.
#
# 参数
# x: 数组
# 待插入数据的横坐标
# 横坐标是fpr 纵坐标tpr
mean_tpr += np.interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
i = i+1
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')
# mean_tpr /= len(cv)
mean_tpr /= cv.n_splits
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
plt.plot(mean_fpr, mean_tpr, 'k--',
label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('CV ROC curve')
plt.legend(loc="lower right")
fig = plt.gcf()
fig.set_size_inches(15, 5)
plt.show()
代码思路分析
1、将原始数据分层同比例拆分训练和测试集
比如将原始数据拆分成 5个训练集和5个测试集合
a 把数据集排成一串
b 然后依次按照元素顺序分割成K份子集
c然后每个子集充当一次测试集,这样可以使得每个样本都在测试集中出现
注意:
a 这种划分没有随机性,因为每一份测试集都是从前往后有序排列的
b 所以该方法使用之前需要将数据集执行打乱操作(KFold中设置shuffle=True即可)
c 注意:random_state参数默认为None,如果设置为整数,每次运行的结果是一样的。
2、通过训练数据训练模型 得到模型之后预测测试数据
3、根据实际测试数据的结果和测试数据的预测结果来计算每一个阈值的tpr和fpr
4、根据tpr和fpr画auc曲线
处理完一个分组中的训练和测试数据就会生成一个roc曲线
计算auc面积
最终的ROC曲线
其中的area就是auc面积
计算ROC曲线最佳位置
代码
def rocZeroOne(y_true, y_predicted_porba):
from sklearn.metrics import roc_curve
from scipy.spatial.distance import euclidean
fpr, tpr, thresholds = roc_curve(y_true, y_predicted_porba[:, 1])
best = [0, 1]
dist = []
for (x, y) in zip(fpr, tpr):
dist.append([euclidean([x, y], best)])
bestPoint = [fpr[dist.index(min(dist))], tpr[dist.index(min(dist))]]
bestCutOff1 = thresholds[list(fpr).index(bestPoint[0])]
bestCutOff2 = thresholds[list(tpr).index(bestPoint[1])]
print('\n' + 'ROC曲线最佳点位置: TPR = {:0.3f}%, FPR = {:0.3f}%'.format(bestPoint[1] * 100, bestPoint[0] * 100))
print('\n' + '最佳截止点: {:0.4f}'.format(bestCutOff1))
plt.plot(dist)
plt.xlabel('Index')
plt.ylabel('Euclidean Distance to the perfect [0,1]')
fig = plt.gcf()
fig.set_size_inches(15, 5)
原理分析
1、 该函数的2个入参数 一个是测试数据真实结果 一个是该测试数据的预测结果
2、计算ROC曲线上距离左上角最近的点 就是最好的位置
左上角的点是(0,1)
在数学中,欧几里得距离或欧几里得度量是欧几里得空间中两点间“普通”(即直线)距离
函数则对应 python库 scipy.spatial.distance import euclidean
逻辑回归
逻辑回归计算结果