python稳健性检验_风控模型6大核心指标(附代码)
欢迎各位同学学习python金融风控评分卡模型和数据分析微专业课
在我们开发完信用分模型后,经常需要计算如下的一些指标:● 区分度的指标:○ AUC○ KS○ GINI● 稳定性的指标:○ PSI● 分数分布:○ 总人数比例○ 坏用户比例接下来,本文从如下5个模块为读者朋友们介绍如何利用Python实现这些指标数据。目录
Part 1. 生成样本
Part 2. 计算AUC、KS、GINI
Part 3. PSI
Part 4. 分数分布
Part 5. 完整工程代码
致谢
01.生成样本
首先,本文用以示例,故使用代码创造的一些假样本。
import numpy as np
import pandas as pd
n_sample = 1000
df_score = pd.DataFrame({
'user_id': [u for u in range(n_sample)],
'label':np.random.randint(2, size=n_sample),
'score': 900*np.random.random(size=n_sample),
'term': 20201+np.random.randint(5, size=n_sample)
})
然后我们统计下分term的总人数,坏人数和坏人比例:
df_score.groupby('term').agg(total=('label', 'count'),
bad=('label', 'sum'),
bad_rate=('label', 'mean'))
02
区分度指标
计算区分度指标KS、AUC、GINI的helper function如下:
from sklearn.metrics import roc_auc_score, roc_curve
def get_auc(ytrue, yprob):
auc = roc_auc_score(ytrue, yprob)
if auc < 0.5:
auc = 1 - auc
return auc
def get_ks(ytrue, yprob):
fpr, tpr, thr = roc_curve(ytrue, yprob)
ks = max(abs(tpr - fpr))
return ks
def get_gini(ytrue, yprob):
auc = get_auc(ytrue, yprob)
gini = 2 * auc - 1
return gini
这里对原有sklearn的auc计算做了一点修改,如果AUC<0.5的话会返回1-AUC, 这样能忽略区分度的方向性。
然后对每个term做区分度的计算:
df_metrics = pd.DataFrame({
'auc': df_score.groupby('term').apply(lambda x: get_auc(x['label'], x['score'])),
'ks': df_score.groupby('term').apply(lambda x: get_ks(x['label'], x['score'])),
'gini': df_score.groupby('term').apply(lambda x: get_gini(x['label'], x['score']))
})
03.稳定性指标
这里先分成2步:
简单对随机生成的信用分按固定分数区间分段;
按照分段计算PSI:使用pivot_table把数据按照term进行排列计算每个term上的人数比例。
df_score['score_bin'] = pd.cut(df_score['score'], [0, 500, 700, 800, 900])
df_total = pd.pivot_table(df_score,
values='user_id',
index='score_bin',
columns=['term'],
aggfunc="count",
margins=True)
last = df_ratio.iloc[0:-1, idx-1]+eps
cur = df_ratio.iloc[0:-1, idx]+eps
根据人数比例计算PSI再放回表格内
根据人数比例计算PSI再放回表格内
eps = np.finfo(np.float32).eps
lst_psi = list()
for idx in range(1, len(df_ratio.columns)-1):
last, cur = df_ratio.iloc[0, -1: idx-1]+eps, df_ratio.iloc[0, -1: idx]+eps
psi = sum((cur-last) * np.log(cur / last))
lst_psi.append(psi)
df_ratio.append(pd.Series([np.nan]+lst_psi+[np.nan],
index=df_ratio.columns,
name='psi'))
04.分数分布
统计总人数分布和坏用户比例的分布,其实在上面计算PSI的时候已经计算出人数分布,就是上面的df_ratio:
df_total = pd.pivot_table(df_score,
values='user_id',
index='score_bin',
columns=['term'],
aggfunc="count",
margins=True)
df_ratio = df_total.div(df_total.iloc[-1, :], axis=1)
可以使用seaborn的stacked line和stacked bar来做出总用户的分布和坏用户的比列分布。
4.1.总人数分布:
import seaborn as sns
colormap = sns.diverging_palette(130, 20, as_cmap=True)
df_ratio.drop('All').T.plot(kind='bar', stacked=True, colormap=colormap)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
4.2.坏人比例分布:
colormap = sns.diverging_palette(130, 20, as_cmap=True)
df_bad_rate.drop('All').T.plot(kind='line', colormap=colormap)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
05.完整Python代码
至此,本文已经把信用风控模型6大核心指标的计算过程都展示出来了。最后附上完整工程Python代码,供FALers学习使用。
import numpy as np
import pandas as pd
n_sample = 1000
df_score = pd.DataFrame({
'user_id': [u for u in range(n_sample)],
'label':np.random.randint(2, size=n_sample),
'score': 900*np.random.random(size=n_sample),
'term': 20201+np.random.randint(5, size=n_sample)
})
df_score.groupby('term').agg(total=('label', 'count'),
bad=('label', 'sum'),
bad_rate=('label', 'mean'))
#KS,GINI,AUC
from sklearn.metrics import roc_auc_score, roc_curve
def get_auc(ytrue, yprob):
auc = roc_auc_score(ytrue, yprob)
if auc < 0.5:
auc = 1 - auc
return auc
def get_ks(ytrue, yprob):
fpr, tpr, thr = roc_curve(ytrue, yprob)
ks = max(abs(tpr - fpr))
return ks
def get_gini(ytrue, yprob):
auc = get_auc(ytrue, yprob)
gini = 2 * auc - 1
return gini
df_metrics = pd.DataFrame({
'auc': df_score.groupby('term').apply(lambda x: get_auc(x['label'], x['score'])),
'ks': df_score.groupby('term').apply(lambda x: get_ks(x['label'], x['score'])),
'gini': df_score.groupby('term').apply(lambda x: get_gini(x['label'], x['score']))
})
#PSI
df_score['score_bin'] = pd.cut(df_score['score'], [0, 500, 700, 800, 900])
df_total = pd.pivot_table(df_score,
values='user_id',
index='score_bin',
columns=['term'],
aggfunc="count",
margins=True)
last = df_ratio.iloc[0:-1, idx-1]+eps
cur = df_ratio.iloc[0:-1, idx]+eps
eps = np.finfo(np.float32).eps
lst_psi = list()
for idx in range(1, len(df_ratio.columns)-1):
last, cur = df_ratio.iloc[0, -1: idx-1]+eps, df_ratio.iloc[0, -1: idx]+eps
psi = sum((cur-last) * np.log(cur / last))
lst_psi.append(psi)
df_ratio.append(pd.Series([np.nan]+lst_psi+[np.nan],
index=df_ratio.columns,
name='psi'))
#总人数比例和坏客户比例
df_total = pd.pivot_table(df_score,
values='user_id',
index='score_bin',
columns=['term'],
aggfunc="count",
margins=True)
df_ratio = df_total.div(df_total.iloc[-1, :], axis=1)
df_bad = pd.pivot_table(df_score[df_score['label']==1],
values='user_id',
index='score_bin',
columns=['term'],
aggfunc="count",
margins=True)
df_bad_rate = df_bad/df_total
#做图
import seaborn as sns
colormap = sns.diverging_palette(130, 20, as_cmap=True)
df_ratio.drop('All').T.plot(kind='bar', stacked=True, colormap=colormap)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
colormap = sns.diverging_palette(130, 20, as_cmap=True)
df_bad_rate.drop('All').T.plot(kind='line', colormap=colormap)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
转载:https://mp.weixin.qq.com/s/9o-u7zRM0mv-3wXPTv8oAQ
欢迎各位同学学习python信用评分卡建模视频系列教程(附代码, 博主录制) :
python稳健性检验_风控模型6大核心指标(附代码)相关推荐
- python稳健性检验_浅谈使用python处理数据的日常经验
- TFPraw.dta - TFPtrans2single.dta - TFPresult0909.dta - getTFP.py - balabala... 这个示例是一个典型的工作时产生的数据集 ...
- python稳健性检验_利用Python检验你的策略参数是否过拟合
过拟合现象 一般来说,量化研究员在优化其交易策略参数时难免会面临这样一个问题:优化过后的策略在样本内表现一般来说均会超过其在样本外的表现,即参数过拟合.对于参数优化来说,由于优化时存在噪音,过拟合是不 ...
- python稳健性检验_有哪些比较好的做异常值检测的方法?
最近很多小伙伴都比较关注异常值检测的方法,接下来小编就为大家介绍几种,希望能帮到大家!! 摘要: 本文介绍了异常值检测的常见四种方法,分别为Numeric Outlier.Z-Score.DBSCA以 ...
- 树莓派python实例_使用Python实现树莓派WiFi断线自动重连实例(附代码)
实现 WiFi 断线自动重连,原理是用 Python 监测网络是否断线,如果断线则重启网络服务.接下来给大家分享实现代码,需要的朋友参考下 1.Python 代码 autowifi.py,放在 /ho ...
- 风控建模 python 知乎_风控建模基本要求及面试问题小结
(本文是写给风控入门同学的建议!) 一 准备工作 根据核心职业CD法则,找工作前,你得先清楚自己有什么,自己要什么:面试单位有什么,面试单位要什么.就笔者近一年的学习及工作经验总结而言: 科班同学,最 ...
- arima模型 白噪声检验_白噪声模型
arima模型 白噪声检验 White noise are variations in your data that cannot be explained by any regression mod ...
- lda主题模型python实现篇_主题模型TopicModel:通过gensim实现LDA
使用python gensim轻松实现lda模型. gensim简介 gemsim是一个免费python库,能够从文档中有效地自动抽取语义主题.gensim中的算法包括:LSA(Latent Sema ...
- 风控策略和模型的区别_风控模型之产品赢利分析与策略优化
欢迎加入全国风控微信群组:免费加入,详情可添加管理Vivian:wmyd80回复微信群组 之前我们说过,产品上线后并不是一成不变的,而是需要后续赢利分析数据表现不断调整,其风控模型策略也是不断优化的. ...
- 如何浅显得理解风控模型中的特征筛选|附实操细节(全)
今天我们综合了星球同学的一些需求,给大家梳理了这样一篇风控建模中特征筛选,希望对所有的风控人员在模型开发上都有所启发. 本文,我们会跟大家介绍特征选择的内容,包括其中的重点问题跟注意的细节. 因为完整 ...
最新文章
- hive根据已有表创建新表_Hive基础之创建表
- 初步了解qemu虚拟机
- iconv 判断字符编码_GBK 和 UTF8编码
- 体验式培训之“铁人七项”
- 021-PHP常用的数值类型判断函数
- UVA10679 I Love Strings!!【字符串匹配】
- 摄像机跟随以及注视旋转和角度变化
- java对日期设置时间和对日期加减周
- 计算机万能知识,电脑知识讲解ppt课件.ppt
- Github注册中,邮箱验证通不过解决办法
- 晶振电路电容选取的计算方法
- pythonqq机器人酷q_NoneBot+酷Q,打造QQ机器人
- bert获取词向量做textcnn文本分类
- 微信小程序制作天气查询系统
- h20r1203功率管参数_电磁炉功率管H20R1353可以用H20R1203代换吗
- PS获取图片三种方式
- 18年华为没有1项原创发明
- 笔记本计算机风扇声音大怎么办,笔记本电脑噪音大怎么办 全解决方法
- scss 转换成css,如何将scss转换为css
- 算法问题:什么是P问题、NP问题和NPC问题zz