【金融风控系列】_[1]_贷款违约预测
本文围绕天池贷款违约预测赛题,介绍零基础入门金融风控的实现过程。使用超过120万条贷款记录数据,对比多种数据不平衡处理方法,以CatBoost为基分类器,经5折交叉验证,结合过采样的模型线上表现较好(AUC 0.7347),SMOTE和BalanceCascade效果欠佳,为相关任务提供参考。
![【金融风控系列】_[1]_贷款违约预测 - 游乐网](https://static.youleyou.com/uploadfile/2025/0721/20250721060056284.webp)
零基础入门金融风控-贷款违约预测
该赛题来自 TIANCHI 零基础入门系列,仅用作学习交流
该数据来自某信贷平台的贷款记录,总数据量超过120w,包含47列变量信息,其中15列为匿名变量。为了保证比赛的公平性,将会从中抽取80万条作为训练集,20万条作为测试集A,20万条作为测试集B,同时会对employmentTitle、purpose、postCode和title等信息进行脱敏。
免费影视、动漫、音乐、游戏、小说资源长期稳定更新! 👉 点此立即查看 👈
字段表
参考:
[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算法SPE算法SMOTE(Synthetic Minority Oversampling Technique),合成少数类过采样技术.它是基于随机过采样算法的一种改进方案,为了克服随机过采样算法泛化能力差的缺点,SMOTE算法的对少数类样本近邻进行采样,根据少数类样本人工合成新样本添加到数据集中。
过采样算法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 warningswarnings.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 nptrain=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.columnstestA = 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=2020, 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_foldssub['isDefault']=cat_presub.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=2020, 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_presub.to_csv('金融预测.csv',index=False)登录后复制 总结
本项目主要以CBT算法为基分类器对比了几种常用的数据不平衡的处理效果,关于数据特征构建的知识可以查看开头参考文献。
数据的对比提交结果如下:
imbalanced-ensemble库中包含了许多其他的非平衡算法,有兴趣的同学可以关注参考文献[3]
此外,在训练中,随着基模型数量的增加此数据上的分类表现有所下降,这可能是由于此数据失衡仅4:1,不足以体现算法优势。
游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。
同类文章
逼AI当山顶洞人!Claude防话痨插件爆火,网友:受够了AI废话
新智元报道编辑:元宇【新智元导读】一个让AI像原始人一样说话的插件,在HN上一夜爆火,冲破2w星。它的核心只是一条简单粗暴的prompt:删掉冠词、客套和一切废话,号称能省下75%的输出token。
季度利润翻 8 倍,最赚钱的「卖铲人」财报背后,内存涨价狂潮如何收场?
AI 时代最赚钱的公司,可能从来不是做 AI 的那个。作者|张勇毅编辑|靖宇淘金热里最稳赚的人,从来不是淘金的,是卖铲子的。这句老话在 2026 年的科技行业又应验了一次。只不过这次卖铲子的不是英伟
Claude Code Harness+龙虾科研团来了!金字塔分层架构+多智能体
Claw AI Lab团队量子位 | 公众号 QbitAI你还在一个人做科研吗?科研最难的,从来不是问题本身,而是一个想法从文献到实验再到写作,只能靠自己一点点往前推。一个人方向偏了没人提醒,遇到歧
让离线强化学习从「局部描摹」变「全局布局」丨ICLR'26
面对复杂连续任务的长程规划,现有的生成式离线强化学习方法往往会暴露短板。它们生成的轨迹经常陷入局部合理但全局偏航的窘境。它们太关注眼前的每一步,却忘了最终的目的地。针对这一痛点,厦门大学和香港科技大
美国犹他州启动新试点项目:AI为患者开具精神类药物处方
IT之家 4 月 5 日消息,据外媒 PC Mag 当地时间 4 月 4 日报道,美国医疗机构 Legion Health 在犹他州获得监管批准,启动一项试点项目,允许 AI 系统为患者开具精神类药
- 日榜
- 周榜
- 月榜
1
2
3
4
5
6
7
8
9
10
相关攻略
2015-03-10 11:25
2015-03-10 11:05
2021-08-04 13:30
2015-03-10 11:22
2015-03-10 12:39
2022-05-16 18:57
2025-05-23 13:43
2025-05-23 14:01
热门教程
- 游戏攻略
- 安卓教程
- 苹果教程
- 电脑教程
热门话题

