百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

信用评分系统运行原理下篇

toyiye 2024-06-21 12:26 8 浏览 0 评论

信用评分系统运行原理下篇

前言

信用评分系统运行原理上篇

信用评分系统运行原理中篇-分箱逻辑

绘制相关性系数热力图

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

逻辑回归

逻辑回归计算结果

模型预测 评估模型

计算评分

基础分

获取评分

计算评分

评分卡模型系统主流程

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码