【金融风控系列】_[1]_贷款违约预测


本文围绕天池贷款违约预测赛题,介绍零基础入门金融风控的实现过程。使用超过120万条贷款记录数据,对比多种数据不平衡处理方法,以CatBoost为基分类器,经5折交叉验证,结合过采样的模型线上表现较好(AUC 0.7347),SMOTE和BalanceCascade效果欠佳,为相关任务提供参考。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

【金融风控系列】_[1]_贷款违约预测 -

零基础入门金融风控-贷款违约预测

该赛题来自 TIANCHI 零基础入门系列,仅用作学习交流

该数据来自某信贷平台的贷款记录,总数据量超过120w,包含47列变量信息,其中15列为匿名变量。为了保证比赛的公平性,将会从中抽取80万条作为训练集,20万条作为测试集A,20万条作为测试集B,同时会对employmentTitle、purpose、postCode和title等信息进行脱敏。

字段表

Field Description
id 为贷款清单分配的唯一信用证标识
loanAmnt 贷款金额
term 贷款期限(year)
interestRate 贷款利率
installment 分期付款金额
grade 贷款等级
subGrade 贷款等级之子级
employmentTitle 就业职称
employmentLength 就业年限(年)
homeOwnership 借款人在登记时提供的房屋所有权状况
annualIncome 年收入
verificationStatus 验证状态
issueDate 贷款发放的月份
purpose 借款人在贷款申请时的贷款用途类别
postCode 借款人在贷款申请中提供的邮政编码的前3位数字
regionCode 地区编码
dti 债务收入比
delinquency_2years 借款人过去2年信用档案中逾期30天以上的违约事件数
ficoRangeLow 借款人在贷款发放时的fico所属的下限范围
ficoRangeHigh 借款人在贷款发放时的fico所属的上限范围
openAcc 借款人信用档案中未结信用额度的数量
pubRec 贬损公共记录的数量
pubRecBankruptcies 公开记录清除的数量
revolBal 信贷周转余额合计
revolUtil 循环额度利用率,或借款人使用的相对于所有可用循环信贷的信贷金额
totalAcc 借款人信用档案中当前的信用额度总数
initialListStatus 贷款的初始列表状态
applicationType 表明贷款是个人申请还是与两个共同借款人的联合申请
earliesCreditLine 借款人最早报告的信用额度开立的月份
title 借款人提供的贷款名称
policyCode 公开可用的策略_代码=1新产品不公开可用的策略_代码=2
n系列匿名特征 匿名特征n0-n14,为一些贷款人行为计数特征的处理

参考:

[1] https://github.com/caozichuan/TianChi_loadDefault/blob/main/GitHub_loadDefault/model/xgb_github.ipynb

[2] https://tianchi.aliyun.com/notebook-ai/detail?spm=5176.21852664.0.0.4f70379c1gFeCt&postId=129321

[3] https://imbalanced-ensemble.readthedocs.io/en/latest/index.html

[4] https://blog.csdn.net/qq_31367861/article/details/111145816?spm=5176.21852664.0.0.22686e12UZfkmZ

文献4方法线上提交分数为0.7391

       

[5] https://blog.csdn.net/qq_44694861/article/details/109753004?spm=5176.21852664.0.0.667f4288swn2OQ

本项目主要是对金融风控中常见的数据不平衡方法进行对比,以及对 self-paced-ensemble 包进行学习

使用的方法如下:

  • 无处理
  • SMOTE算法

SMOTE(Synthetic Minority Oversampling Technique),合成少数类过采样技术.它是基于随机过采样算法的一种改进方案,为了克服随机过采样算法泛化能力差的缺点,SMOTE算法的对少数类样本近邻进行采样,根据少数类样本人工合成新样本添加到数据集中。

简小派 简小派

简小派是一款AI原生求职工具,通过简历优化、岗位匹配、项目生成、模拟面试与智能投递,全链路提升求职成功率,帮助普通人更快拿到更好的 offer。

简小派 123 查看详情 简小派
  • SPE算法

Liu Z , Cao W , Gao Z , et al. Self-paced Ensemble for Highly Imbalanced Massive Data Classification[J]. 2019.

  • 过采样算法

重复正样本,使得正样本与负样本比例接近 1 : 1

  • 欠采样算法

从数量多的样本里面随机选择样本进行抛弃,为了避免随机性影响,我们独立训练多个模型进行简单平均

  • BalanceCascade算法

Liu, X. Y., Wu, J., & Zhou, Z. H. “Exploratory undersampling for class-imbalance learning.” IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics) 39.2 (2008): 539-550

注意事项

  • 运行主要有两部分,数据处理 和 模型选择 ,根据注释部分,自己进行数据处理和算法组合。默认CBT模型+过采样算法。
In [1]
#!pip install pandas --user#!pip install lightgbm --user#!pip install xgboost --user!pip install catboost --user
!pip install joblib --user
!pip install scikit-learn --user
!pip install imblearn --user
!pip install imbalanced-ensemble --user
!pip self-paced-ensemble --user
    In [2]
import pandas as pdimport datetimeimport warnings
warnings.filterwarnings('ignore')from sklearn.model_selection import StratifiedKFold#warnings.filterwarnings('ignore')#%matplotlib inlinefrom sklearn.metrics import roc_auc_score## 数据降维处理的from sklearn.model_selection import train_test_split  
from catboost import CatBoostClassifierimport imbalanced_ensemble as imbensfrom collections import Counterfrom imbalanced_ensemble.sampler.over_sampling import     SMOTE 
import numpy as np
train=pd.read_csv("./data/data53042/train.csv")
testA=pd.read_csv("./data/data53042/testA.csv")

numerical_fea = list(train.select_dtypes(exclude=['object']).columns)
category_fea = list(filter(lambda x: x not in numerical_fea,list(train.columns)))
label = 'isDefault'numerical_fea.remove(label)#按照中位数填充数值型特征train[numerical_fea] = train[numerical_fea].fillna(train[numerical_fea].median())
testA[numerical_fea] = testA[numerical_fea].fillna(testA[numerical_fea].median())#按照众数填充类别型特征train[category_fea] = train[category_fea].fillna(train[category_fea].mode())
testA[category_fea] = testA[category_fea].fillna(testA[category_fea].mode())def make_fea(data):
    data['issueDate'] = pd.to_datetime(data['issueDate'],format='%Y-%m-%d')
    startdate = datetime.datetime.strptime('2007-06-01', '%Y-%m-%d')    #构造时间特征
    data['issueDateDT'] = data['issueDate'].apply(lambda x: x-startdate).dt.days

    data['grade'] = data['grade'].map({'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7})
    data['subGrade'] = data['subGrade'].map({'E2':1,'D2':2,'D3':3,'A4':4,'C2':5,'A5':6,'C3':7,'B4':8,'B5':9,'E5':10,        'D4':11,'B3':12,'B2':13,'D1':14,'E1':15,'C5':16,'C1':17,'A2':18,'A3':19,'B1':20,        'E3':21,'F1':22,'C4':23,'A1':24,'D5':25,'F2':26,'E4':27,'F3':28,'G2':29,'F5':30,        'G3':31,'G1':32,'F4':33,'G4':34,'G5':35})

    data = pd.get_dummies(data, columns=['subGrade', 'homeOwnership', 'verificationStatus', 'purpose', 'regionCode'], drop_first=True)
    data['employmentLength'] = data['employmentLength'].map({'NaN':-1,'1 year':1,'2 years':2,'3 years':3,'4 years':4,'5 years':5,'6 years':6,'7 years':7,'8 years':8,'9 years':9,'10+ years':10,'< 1 year':0})
    data['earliesCreditLine'] = data['earliesCreditLine'].apply(lambda s: int(s[-4:]))    for item in ['n0','n1','n2','n2.1','n4','n5','n6','n7','n8','n9','n10','n11','n12','n13','n14']:
        data['grade_to_mean_' + item] = data['grade'] / data.groupby([item])['grade'].transform('mean')
        data['grade_to_std_' + item] = data['grade'] / data.groupby([item])['grade'].transform('std')
    data['n15']=data['n8']*data['n10']    return data# 特征工程 简单处理train = make_fea(train)
testA = make_fea(testA)print(train.shape)print(testA.shape)print("数据预处理完成!")  
sub=testA[['id']].copy()
sub['isDefault']=0testA=testA.drop(['id','issueDate'],axis=1)
data_x=train.drop(['isDefault','id','issueDate'],axis=1)

data_y=train[['isDefault']].copy()

col=['grade','subGrade','employmentTitle','homeOwnership','verificationStatus','purpose','postCode','regionCode',     'initialListStatus','applicationType','policyCode']for i in data_x.columns:    if i in col:
        data_x[i] = data_x[i].astype('str')for i in testA.columns:    if i in col:
        testA[i] = testA[i].astype('str')

answers = []
mean_score = 0n_folds = 5sk = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=2019)print(data_x.shape)print(testA.shape)# 在测试集中有部分特征训练集中没有,进行处理COLNAME = data_x.columns
testA = testA[COLNAME]# 处理INF NAN ,替换成 -1 注意:np.inf和-np.inf是不同的两个值,这里经常遇到忘记处理后者引发错误data_x.replace([np.inf, -np.inf, np.nan], -1, inplace=True)
testA.replace([np.inf, -np.inf, np.nan], -1, inplace=True)#  -----重复正样本,因为原始数据比例约为3:1 因此对正样本重复三次拼接到原始数据中-----a = [i for i, x in enumerate(data_y.values) if x[0]==1]
all_1 = data_x.iloc[a]
all_y = pd.DataFrame(np.ones(all_1.shape[0],dtype=int),columns=['isDefault'])print(all_y.shape)print(data_x.shape,data_y.shape)for i in range(3):
    data_y= pd.concat([data_y,all_y],axis=0)
    data_x = pd.concat([data_x,all_1],axis=0)    print(data_x.shape,data_y.shape)
data_x.reset_index(drop=True,inplace =True)
data_y.reset_index(drop=True,inplace =True)'''
# -----使用SMOTE算法对负样本进行扩充-----
sm = SMOTE(random_state=42)
data_x, data_y = sm.fit_resample(data_x, data_y)
print('Resampled dataset' , data_y.value_counts())
'''
   

基础模型定义及训练

使用CatBoost分类模型作为基准模型

In [ ]
model=CatBoostClassifier(
            loss_function="Logloss",
            eval_metric="AUC",
            task_type="CPU",
            learning_rate=0.1,
            iterations=500,
            random_seed=2025,
            verbose=500,
            depth=7)for train, test in sk.split(data_x, data_y):
    x_train = data_x.iloc[train]
    y_train = data_y.iloc[train]
    x_test = data_x.iloc[test]
    y_test = data_y.iloc[test]    '''
    # -----使用SPE 算法对不平衡数据进行处理-----
    clf = imbens.ensemble.SelfPacedEnsembleClassifier(
        base_estimator = model,#基准分类模型 可以自定义,需要模型包含fit等方法,具体信息请查看参考文献3
        n_estimators = 5,
        random_state=49
    ).fit(x_train, y_train)
    '''
    # -----使用BalanceCascade 算法对不平衡数据进行处理-----
    '''
    clf = imbens.ensemble.BalanceCascadeClassifier(        
        base_estimator = model,#基准分类模型 可以自定义,需要模型包含fit等方法,具体信息请查看参考文献3
        n_estimators = 5,
        random_state=49
    ).fit(x_train, y_train)
    '''

    # 基准分类模型
    clf = model.fit(x_train,y_train)#, eval_set=(x_test,y_test),cat_features=col)

    yy_pred_valid=clf.predict_proba(x_test)[:,-1]    print('cat验证的auc:{}'.format(roc_auc_score(y_test, yy_pred_valid)))
    mean_score += roc_auc_score(y_test, yy_pred_valid) / n_folds
    y_pred_valid = clf.predict_proba(testA)[:,-1]
    answers.append(y_pred_valid)print('mean valAuc:{}'.format(mean_score))
cat_pre=sum(answers)/n_folds
sub['isDefault']=cat_pre
sub.to_csv('金融预测.csv',index=False)
   

欠采样模型训练

In [ ]
model=CatBoostClassifier(
            loss_function="Logloss",
            eval_metric="AUC",
            task_type="CPU",
            learning_rate=0.1,
            iterations=500,
            random_seed=2025,
            verbose=500,
            depth=7)#----- 欠采样模型 -----a = [i for i, x in enumerate(data_y.values) if x[0]==1]
all_1 = data_x.iloc[a]
all_y1 = pd.DataFrame(np.ones(all_1.shape[0]),columns=['isDefault'])
all_y0 = pd.DataFrame(np.ones(all_y.shape[0]),columns=['isDefault'])print(all_y1.shape)#for i in range(4): # 数据比1:4+i= 0all_0 = data_x.iloc[i*all_y1.shape[0]:(i+1)*all_y1.shape[0],:]
data_y_= pd.concat([all_y1,all_y0],axis=0)
data_x_ = pd.concat([all_1,all_0],axis=0)print(data_x_.shape,data_y_.shape,all_0.shape)for train, test in sk.split(data_x, data_y):
    x_train = data_x.iloc[train]
    y_train = data_y.iloc[train]
    x_test = data_x.iloc[test]
    y_test = data_y.iloc[test]    # 基准分类模型
    #clf = model.fit(x_train,y_train)#, eval_set=(x_test,y_test),cat_features=col)

    clf = imbens.ensemble.SelfPacedEnsembleClassifier(
        base_estimator = model,#基准分类模型 可以自定义,需要模型包含fit等方法,具体信息请查看参考文献3
        n_estimators = 5,
        random_state=49
    ).fit(x_train, y_train)
    yy_pred_valid=clf.predict_proba(x_test)[:,-1]    print('cat验证的auc:{}'.format(roc_auc_score(y_test, yy_pred_valid)))
    mean_score += roc_auc_score(y_test, yy_pred_valid) / n_folds
    y_pred_valid = clf.predict_proba(testA)[:,-1]
    answers.append(y_pred_valid)print('mean valAuc:{}'.format(mean_score))
cat_pre=sum(answers)/(n_folds) # 数据比1:4sub['isDefault']=cat_pre
sub.to_csv('金融预测.csv',index=False)
   

总结

  • 本项目主要以CBT算法为基分类器对比了几种常用的数据不平衡的处理效果,关于数据特征构建的知识可以查看开头参考文献。

数据的对比提交结果如下:

数据集 TIANCHI-贷款违约预测(ONLine)
比例 4.01(80W)
指标 AUC(线下五折验证/线上)
CaTBoost+SPE(5) 0.7348/0.7328
CaTBoost 0.7354/0.7338
CaTBoost+SMOTE 0.9334/0.6949
CaTBoost+过采样 0.7477/0.7346
CaTBoost+欠采样 0.7354/0.7338
CaTBoost+BalanceCascade(5) 0.6052/0.6032
CaTBoost+SPE(5)+过采样 0.7485/0.7347

imbalanced-ensemble库中包含了许多其他的非平衡算法,有兴趣的同学可以关注参考文献[3]

  • 此外,在训练中,随着基模型数量的增加此数据上的分类表现有所下降,这可能是由于此数据失衡仅4:1,不足以体现算法优势。

以上就是【金融风控系列】_[1]_贷款违约预测的详细内容,更多请关注其它相关文章!


# cad  # qq  # ai  # yy  # red  # descript  # git  # 广东省整合网络营销推广  # 网站建设优化公司  # 林西网站推广  # 武侯网站推广哪家好  # 商城网站建设基础设计  # 镇江网站优化与推广  # 谷歌seo操作流程  # 网站推广能干啥用啊  # 普通电商网站建设费用  # 上海建设网站手机  # 之子  # 安装包  # 对不  # 一键  # 数据处理  # 中文网  # 请查看  # 不平衡  # 自定义  # 线上  # type 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 优化推广96088 】 【 技术知识133117 】 【 IDC资讯59369 】 【 网络运营7196 】 【 IT资讯61894 】


相关推荐: 中国AI公有云市场2025年逆势蓬勃增长,增速高达80.6%  Dubbo负载均衡策略之 一致性哈希  当人工智能开始写高考作文?作家陈崇正、朱山坡谈文学与未来  无需标注数据,「3D理解」进入多模态预训练时代!ULIP系列全面开源,刷新SOTA  爱设计 AI 一键生成 PPT 工具上线:输入标题即可生成 PPT  华为4G5G通信物联网收费标准公布,多年研发成果,十年花费近万亿  报告称 70% 程序员已使用各种 AI 工具编程  微软新出热乎论文:Transformer扩展到10亿token  掌阅科技对话式AI应用“阅爱聊”开启内测  马斯克:将来机器人比人类多!特斯拉机器人亮相人工智能大会  OpenAI 已全面开放 GPT-3.5 Turbo、DALL-E 及 Whisper API  “直击”AI新世界,智能机器人再次“火出圈”了  央视报道!星纪魅族集团车载人机交互技术成世界移动通信大会焦点  苹果式 AI 哲学:不着一字,处处落子  微软bing聊天推出AI购物工具 可进行比价并查看历史最低价  OpenAI夺冠:人工智能为云计算带来新变革  抖音在Android平台获得VR|直播|软件著作权  无需照相馆,AI证件照生成软件即将推出  兆讯传媒率先全面拥抱AI 数智广告内容焕发新生机  亲身体验鸿蒙4:AI大模型带来的便利,告别单纯的旁观者状态  联想举办2025创新开放日,展出260余项算力及AI产品技术  探索人工智能在居家养老方面的应用  史玉柱谈AI:国内最缺是计算数学人才,曾给浙大数学系捐五千万  会模仿笔迹的AI,为你创造专属字体  字节团队提出猞猁Lynx模型:多模态LLMs理解认知生成类榜单SoTA  自研4D激光雷达L1 + GPT大语言模型 宇树Unitree Go2四足机器人有啥黑科技?  亚马逊确认今年不会举办 re:MARS 机器人和人工智能大会  央广车联网亮相2025世界人工智能大会  掌阅科技申请阅爱聊商标 掌阅科技申请AI相关商标  国内阅读行业首款对话式AI应用“阅爱聊”封闭内测  阿里达摩院发布免费开放100项AI专利许可的动机是什么?  研究预测HPC支持的人工智能增长迅速  云米Smart 2E AI立式空调开启预售:新三级能效,到手价3899元  鸿蒙OS 4将实现AI大模型集成,余承东表示坚持AI辅助而非AI取代  V社回应拒绝上架含 AI 生成内容的游戏:审核政策正在调整中  AI大举入侵内容行业,哪些上市*及动漫公司进行了布局?  1.6亿美元收购Singularity AI,昆仑万维布局通用人工智能  商业智能决策技术助力降本增效,世界人工智能大会举办商业AI高峰论坛  云南首例达芬奇机器人微创心脏手术成功开展  人工智能在服务优化方面优缺点有哪些  三个全球首创,青岛西海岸新区“海元宇宙”亮相世界人工智能大会  OpenAI 向所有付费 API 用户开放 GPT-4  当一个网站的内容被 AI 完全接管  AI 模型 Stable Diffusion 升级:正常生成五指、图像更逼真  高通发布长期产品计划,为工业和企业物联网产品提供全新组合方案  十个AI算法常用库J*a版  AI新视野,增长新势能,伙伴云受邀出席笔记侠创业讲真话AI峰会  国内首家,360智脑通过中国信通院可信AIGC大语言模型功能评估  日本学校探索引入 AI 和无人机:提高安保效率,节省劳动力  谷歌旗下 DeepMind 开发出 RoboCat AI 模型,能控制多种机器人执行一系列任务 

 2025-07-21

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

运城市盐湖区信雨科技有限公司


运城市盐湖区信雨科技有限公司

运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。

 8156699

 13765294890

 8156699@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.