个人信用风险评估项目

1.2数据读取
import pandas as pd

#读取数据
credit = pd.read_csv("credit.csv")  
#查看前5行
credit_5 = credit.head()
print(credit_5)
1.3 查看数据基本情况
import pandas as pd

#查看数据的基本信息
credit_info = credit.info()
1.4 查看数据基本统计信息
import pandas as pd

#查看数据基本统计信息
credit_desc = credit.describe(include = 'all')
print(credit_desc)
2.2 违约与未违约数量柱状图
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure(figsize=(7,5))
#绘制柱状图,查看违约与未违约的取值分布情况
sns.countplot(x = 'default', data = credit, palette = 'Set3')
plt.xlabel('是否违约',fontsize=10)
plt.ylabel('数量',fontsize=10)
plt.title('违约与未违约数量柱状图',fontsize=13)
plt.box(False)

Seaborn中的countplot()函数主要参数如下:

  • x:在x轴方向指定绘图的字段,即绘制柱状图,不能与y同时使用
  • y:在y轴方向指定绘图的字段,即绘制条形图,不能与x同时使用
  • hue:按照指定的字段进行分组
  • data:传入DataFrame对象,用于绘图的数据框
  • color:设置颜色
  • palette:使用不同调色板
  • ax:指定子图索引
2.3 贷款持续时间违约率条形图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

months = (0,6,12,18,24,30,36,42,48,54,72)
#对'months_loan_duration'进行离散化
months_cut = pd.cut(x = credit['months_loan_duration'], bins = months)
#groupby操作计算各个分组的违约率
months_rate = credit.groupby(months_cut)['default'].apply(lambda x:x.sum()/len(x))
#将各个分组的违约率绘制条形图进行展示
fig = plt.figure(figsize=(7,5))
sns.barplot(x = months_rate.values, y = months_rate.index, palette="Set2")
plt.xlabel('违约率',fontsize=10)
plt.ylabel('贷款持续时间',fontsize=10)
plt.title('贷款持续时间违约率条形图',fontsize=13)
plt.box(False)

Pandas中的cut()函数可以进行等距离散化,主要参数有:

  • x:需要离散化的数据对象,可以传入列表、一维NumPy数组或Series对象
  • bins:输入整数,表示将x划分为多少个等距的区间,输入序列,表示将x按照指定区间进行离散化,列表中的元素表示分点,若不在区间范围内的数据,则表示为Nan
  • right: 是否包含右分点
  • labels:是否用标签来代替返回的值
  • include_lowest:是否包含左分点

Seaborn的barplot()函数可以绘制条形图,主要参数有:

  • x:x轴数据,柱状图时为标签名称,条形图时为数值
  • y:y轴数据,柱状图时为数值,条形图时为标签名称
  • hue:按照指定的字段进行分组
  • data:传入DataFrame对象,用于绘图的数据框
  • color:设置颜色
  • palette:使用不同调色板
  • ax:指定子图索引
2.4 违约与未违约贷款金额分布分组条形图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

interval = (0,2000, 4000, 6000,8000,10000,12000,14000,16000,20000)
#对amount进行分组
amount_cut = pd.cut(credit['amount'], bins = interval)
#绘制柱状图
fig = plt.figure(figsize=(7,5))
sns.countplot(y = amount_cut, hue = 'default', data=credit, palette='Set2')
plt.xlabel('数量',fontsize=10)
plt.ylabel('贷款金额',fontsize=10)
plt.title('违约与未违约贷款金额分布分组条形图',fontsize=13)
plt.box(False)
2.5 信用记录违约率条形图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

#分组,并计算违约率
credit_history_rate = credit.groupby('credit_history')['default'].apply(lambda x:x.sum()/len(x))
#绘制条形图
fig = plt.figure(figsize=(7,5))
sns.barplot(x = credit_history_rate.values, y = credit_history_rate.index, palette="Set3")
plt.xlabel('违约率',fontsize=10)
plt.ylabel('信用记录',fontsize=10)
plt.title('信用记录违约率条形图',fontsize=13)
plt.box(False)
2.7 连续型特征与目标特征相关性
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

feature_int = credit.dtypes[credit.dtypes=='int64'].index[:-1]
#定义SelectKBest对象
selector = SelectKBest(score_func = f_classif, k  = len(feature_int))
#使用fit进行训练
selector.fit(credit[feature_int], credit['default'])
#将相关性大小绘制条形图
fig = plt.figure(figsize=(7,5))
sns.barplot(x = selector.scores_, y = feature_int, palette="Set3")
plt.xlabel('相关性',fontsize=10)
plt.ylabel('连续型字段',fontsize=10)
plt.title('连续型字段与标签相关性柱状图',fontsize=13)
plt.box(False)

Sklearn中的SelectKBest()方法可用于特征选择,根据给定的方法,选择出前k个与目标最相关的特征,其主要参数如下:

  • score_func:用于计算相关性的函数,函数接受两个数组X和y,并返回一对数组(scores,pvalue)或带scores的单个数组,scores表示得分,得分越高相关性越强,pvalue表示检验的P值,值越小表示相关性越强,默认值为f_classif,表示计算方差分析的F值,其它取值如下:

    • 1.f_regression:计算相关系数的F值,适用于连续型与连续型的相关性计算
    • 2.chi2:计算卡方统计量,适用于离散型与离散型的相关性计算
    • 3.mutual_info_classif:离散型与离散型的互信息计算
    • 4.mutual_info_regression:连续型与连续型的互信息计算
  • k:需要选择的最佳特征个数,默认值为10。

  • SelectKBest()方法调用fit()方法,传入X和y两组特征,计算它们之间的相关性,调用SelectKBest()方法的score_属性得到相关性得分,调用pvalues_属性得到检验的P值

2.8 离散型特征与目标特征相关性
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

#得到离散型特征列名
feature_obj = credit.dtypes[credit.dtypes=='object'].index
#数字编码
for col in feature_obj:
    credit.loc[:,col] = LabelEncoder().fit_transform(credit[col])
#定义SelectKBest对象
selector=SelectKBest(score_func = chi2, k = len(feature_obj))
#使用fit进行训练
selector.fit(credit[feature_obj], credit['default'])
#将相关性大小绘制条形图
fig = plt.figure(figsize=(7,5))
sns.barplot(x = selector.scores_, y = feature_obj, palette='Set2')
plt.xlabel('相关性',fontsize=10)
plt.ylabel('离散型字段',fontsize=10)
plt.title('离散型字段与标签相关性柱状图',fontsize=13)
plt.box(False)
3.2 训练集测试集划分
from sklearn.model_selection import train_test_split

y = credit['default'].values
X  =  credit.drop('default',axis=1)
#训练集测试集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, 
test_size = .25, random_state = 10, stratify = y)

print(X_train.shape)
print(X_test.shape)

在Sklearn中的model_selection模块,train_test_split()函数可以进行训练集和测试集的划分。
train_test_split(X, y, test_size=None, random_state=None,stratify=y)
其中:

  • X,y:分别为预测所需的所有特征以及需要预测的特征(即违约情况default)。

  • test_size:测试集比例,例如test_size=0.25表示划分25%的数据作为测试集。

  • random_state:随机种子,因为划分过程是随机的,为了每次划分都得到相同的训练集和测试集,需要设置一个随机种子数,使结果重现。

  • stratify:使用分层采样,保证训练集和测试集中违约和未违约客户的比例相同,并且与总体数据中的比例保持一致。

  • 函数最终将返回四个值,分别为训练集特征、测试集特征、训练集标签和测试集标签。

3.3 标准化和数值编码
import pandas as pd
from sklearn.preprocessing import StandardScaler

# 标准化
scaler = StandardScaler()
#训练并转换数据
X_train.loc[:,feature_int] = scaler.fit_transform(X_train[feature_int])
#转换数据
X_test.loc[:,feature_int] = scaler.fit_transform(X_test[feature_int])

#One-Hot编码
all_onehot = pd.get_dummies(pd.concat([X_train[feature_obj], X_test[feature_obj]]).astype('object'),drop_first=False)
#合并标准化和One-Hot编码后的数据
X_train = pd.concat([all_onehot.iloc[:X_train.shape[0],:],X_train[feature_int]],axis=1)
X_test = pd.concat([all_onehot.iloc[X_train.shape[0]:,:],X_test[feature_int]],axis=1)

print(X_train.head())

在Sklearn的preprocessing模块中,StandardScaler()类可以对连续型数据进行Z-socre标准化,可调用的主要方法有:

  • fit: 用于计算训练数据的均值和方差,后面用均值和方差来转换数据。
  • transform: 按照保存的均值和方差转换数据。
  • fit_transform: 不仅计算训练数据的均值和方差,还会基于计算出来的均值和方差来转换数据。

Pandas中的get_dummies()函数可以进行One-Hot编码,主要参数如下:

  • data:输入的数据,Series或DataFrame对象。
  • prefix:One-Hot编码后,新特征列名的前缀,默认为None。
  • prefix_sep:新特征列名的中间的分隔符,默认为’_'。
  • columns:指定需要实现One-Hot编码的列名。
  • drop_first:去除第一个二元特征,K个取值转换成K-1个二元特征,相当于进行哑编码。
3.4 逻辑回归模型训练
from sklearn.linear_model import LogisticRegression
#新建模型对象
model_lr_base = LogisticRegression(class_weight='balanced', random_state=10)
#模型训练
model_lr_base.fit(X_train, y_train)

LogisticRegression模型参数如下:

  • penalty:正则化项,也称为惩罚项,可选参数为l1和l2,默认为l2。如果在调参时主要目的是解决过拟合,一般会选择l2正则化。但是当预测结果不好时,可选用l1正则化。
  • C:正则化系数\lambdaλ的倒数,float类型,默认为1.0,必须是正浮点数类型,数值越小则反应正则化越强。
  • fit_intercept:是否拟合截距,默认为True,布尔类型。
  • class_weight:类别权重,可以是字典或者字符串,默认值为None也就是不考虑权重。如果选择balanced,会根据训练样本类别占比分配类别权重,某种类型的样本量越多,则权重越低,样本量越少,则权重越高。
  • random_state:随机种子,默认为None,仅在优化方法为sag或liblinear时有效。
  • solver:逻辑回归的优化方法。 liblinear:使用开源的liblinear库实现,使用坐标轴下降法来迭代优化损失函数。 lbfgs:拟牛顿法的一种,利用损失函数二阶导数也即Hessian矩阵来迭代优化损失函数。 newton-cg:利用损失函数二阶导数也即Hessian矩阵来迭代优化损失函数。 sag:随机平均梯度下降,与普通梯度下降法的区别是每次迭代仅仅用一部分的样本来计算梯度。
  • max_iter:算法收敛的最大迭代次数,默认为100。仅在正则优化算法为newton-cg、sag和lbfgs时有效。
  • multi_class:面对多分类问题的分类方式,默认为’auto。’
3.5 逻辑回归模型评估
from sklearn.metrics import classification_report,roc_auc_score,average_precision_score

#预测标签
model_lr_base_prelabel = model_lr_base.predict(X_test)
#预测概率,并取正类概率
model_lr_base_prob = model_lr_base.predict_proba(X_test)[:,1]
#输出分类报告
print(classification_report(y_true = y_test, y_pred = model_lr_base_prelabel))
#输出AP值
print('LogisticRegression '+' AP:',average_precision_score(y_test, model_lr_base_prob))
print('LogisticRegression '+' AUC:',roc_auc_score(y_test, model_lr_base_prob))

在Sklearn的metric模块中,classification_report函数可输出分类报告,内容包括Precision、Recall和F1-score(Precision和Recall的调和平均值),其主要参数为:

  • y_true:真实标签
  • y_pred:预测标签

函数average_precision_score可用于计算AP,其主要参数为:

  • y_true:真实标签
  • y_score:正类预测概率
  • pos_label:指定正类标签

函数roc_auc_score可用于计算AUC值,其主要参数为:

  • y_true:真实标签
  • y_score:正类预测概率
3.6 XGBoost模型训练
from xgboost import XGBClassifier

#新建模型对象
model_xgb_base = XGBClassifier(n_estimators=50, learning_rate=0.1,
gamma=0.65, random_state=10, n_jobs=1 ,eval_metric=['logloss','auc','error'])
#模型训练
model_xgb_base.fit(X_train, y_train)

XGBClassifier模型主要参数如下:
常规参数:

  • booster:gbtree 树模型做为基分类器(默认),gbliner 线性模型做为基分类器
  • scale_pos_weight:正样本的权重,在二分类任务中,当正负样本比例失衡时,设置正样本的权重,模型效果更好。例如,当正负样本比例为1:10时,scale_pos_weight=10。

模型参数:

  • n_estimatores:基模型的个数
  • early_stopping_rounds:在测试集上,当连续n次迭代,评价分数没有提高后,提前终止训练,防止过拟合。
  • max_depth:树的深度,默认值为6,典型值为3-10,值越大,越容易过拟合;值越小,越容易欠拟合。
  • min_child_weight:最小叶节点样本权重,默认值为1,值越大,越容易欠拟合;值越小,越容易过拟合。
  • subsample:训练每棵树时,使用的数据占全部训练集的比例,默认值为1,典型值为0.5-1,防止过拟合。
  • colsample_bytree:训练每棵树时,使用的特征占全部特征的比例,默认值为1,典型值为0.5-1,防止过拟合。

学习任务参数:

  • learning_rate:学习率,控制每次迭代更新权重时的步长,默认为0.3,值越小,训练越慢,典型值为0.01-0.2。
  • objective 目标函数: 回归任务:reg:linear (默认)或logistic 。 二分类: binary:logistic(概率)或logitraw(类别)。 多分类:multi:softmax num_class=n(返回类别)softprob num_class=n(返回概率)。rank:pairwise 。
  • eval_metric: 回归任务(默认rmse),rmse均方根误差,mae平均绝对误差。 分类任务(默认error),auc-roc曲线下面积,error错误率(二分类),merror错误率(多分类),logloss负对数似然函数(二分类),mlogloss负对数似然函数(多分类)。
  • gamma:惩罚项系数,指定节点分裂所需的最小损失函数下降值。
  • alpha:L1正则化系数,默认为1。
  • lambda:L2正则化系数,默认为1。
3.7 XGBoost模型评估
from sklearn.metrics import classification_report,roc_auc_score,average_precision_score

#预测标签
model_xgb_base_prelabel = model_xgb_base.predict(X_test)
#预测概率,取正类概率
model_xgb_base_prob = model_xgb_base.predict_proba(X_test)[:, 1]
#输出分类报告
print(classification_report(y_test, model_xgb_base_prelabel))
#输出AP值
print('XGBoost '+' AP:',average_precision_score(y_test, model_xgb_base_prob))
#输出AUC值
print('XGBoost '+' AUC:',roc_auc_score(y_test, model_xgb_base_prob))

函数average_precision_score计算AP,其主要参数为:

  • y_true:真实标签
  • y_score:正类预测概率
  • pos_label:指定正类标签

函数roc_auc_score计算AUC值,其主要参数为:

  • y_true:真实标签
  • y_score:正类预测概率
4.2 WOE编码
from category_encoders import WOEEncoder

#WOE编码
credit = WOEEncoder(cols=feature_obj).fit_transform(credit, credit['default'])

print(credit.head())

从category_encoders库中导入WOEEncoder,可以进行WOE编码。
WOEEncoder常用参数:

  • cols:对指定列进行编码,如果未指定则将对所有列进行编码。
  • drop_invariant:布尔型,是否删除方差为0的列。
  • regularization:正则化,浮点型,正则化的主要目的是防止被零除。

可调用的主要方法:

  • fit: 用于计算训练数据的WOE值,后面用其来转换数据。
  • transform: 按照保存的WOE值转换数据。
  • fit_transform: 不仅计算训练数据的WOE值,还会基于计算出来的WOE值来转换数据。
4.3 数据标准化
import pandas as pd
from sklearn.preprocessing import StandardScaler

#对进行WOE编码后的训练集和测试集进行标准化
scaler = StandardScaler()
X_train.loc[:,feature_int] = scaler.fit_transform(X_train[feature_int])
X_test.loc[:,feature_int] = scaler.transform(X_test[feature_int])

StandardScaler()类可以对连续型数据进行Z-socre标准化,可调用的主要方法有:

  • fit: 用于计算训练数据的均值和方差,后面就会用均值和方差来转换训练数据。
  • transform: 只是进行转换,只是把训练数据转换成标准的正态分布。
  • fit_transform: 不仅计算训练数据的均值和方差,还会基于计算出来的均值和方差来转换训练数据,从而把数据转换成标准的正态分布。
4.4 逻辑回归模型训练
from sklearn.linear_model import LogisticRegression

#新建模型对象
model_lr = LogisticRegression(class_weight='balanced', random_state=10)
#模型训练
model_lr.fit(X_train, y_train)
4.5 逻辑回归模型评估
from sklearn.metrics import classification_report,roc_auc_score,average_precision_score,plot_precision_recall_curve,plot_roc_curve

#预测标签
model_lr_prelabel = model_lr.predict(X_test)
#预测概率,并取正类的概率
model_lr_prob = model_lr.predict_proba(X_test)[:,1]
#输出分类报告
print(classification_report(y_test, model_lr_prelabel))
#输出AP值
print('LogisticRegression '+' AP:',average_precision_score(y_test, model_lr_prob))
#输出AUC值
print('LogisticRegression '+' AUC:',roc_auc_score(y_test, model_lr_prob))
#画出PR曲线
plot_precision_recall_curve(estimator=model_lr, X = X_test, y = y_test, pos_label = 1)
#画出ROC曲线
plot_roc_curve(estimator=model_lr, X = X_test, y = y_test, pos_label = 1)
4.6 XGBoost模型训练
from xgboost import XGBClassifier

#新建模型对象
model_xgb = XGBClassifier(n_estimators=50, learning_rate=0.1, gamma=0.65, random_state=10, n_jobs=1
,eval_metric=['logloss','auc','error'])
#模型训练
model_xgb.fit(X_train, y_train)
4.7 XGBoost模型评估
from sklearn.metrics import classification_report,roc_auc_score,average_precision_score,plot_precision_recall_curve,plot_roc_curve

#预测标签
model_xgb_prelabel = model_xgb.predict(X_test)
#预测概率,并取正类的概率
model_xgb_prob = model_xgb.predict_proba(X_test)[:,1]
#输出分类报告
print(classification_report(y_test, model_xgb_prelabel))
#输出AP值
print('XGBoost'+' AP:',average_precision_score(y_test, model_xgb_prob))
#输出AUC值
print('XGBoost'+' AUC:',roc_auc_score(y_test, model_xgb_prob))
#画出PR曲线
plot_precision_recall_curve(estimator=model_xgb, X = X_test, y = y_test, pos_label = 1)
#画出ROC曲线
plot_roc_curve(estimator=model_xgb, X = X_test, y = y_test, pos_label = 1)
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值