贷款违约预测是现代金融机构信用风险管理的基础。金融机构审批贷款时会收集客户的个人信息,包括年龄、收入、学历、职业、家庭情况和借贷历史等,在对各项信息综合考虑的基础上决定是否审批贷款。为了避免贷款违约,金融机构在对借款人发放贷款的时候必须对借款人的信用程度进行评估打分,预测贷款违约的概率,并做出是否发放贷款的判断。
本案例利用逻辑回归模型预测贷款人是否会发生违约行为。通过贷款数据(包括个人信息、财务状况和贷款状态等)来训练模型,通过模型分析贷款人的偿还能力,预测贷款申请人是否会发生违约。
点击此处下载相关数据集
# coding = utf-8
# 导入必要的库
import pandas
import matplotlib.pyplot as plt
import seaborn
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 设置字体
plt.rcParams['font.sans-serif']=['SimSun']
plt.rcParams['axes.unicode_minus']=False
# 读取数据集
def get_data(path):
bank_data = pandas.read_csv(path)
x = bank_data.iloc[0:700, :8]
y = bank_data.iloc[0:700, 8]
return x, y
# 特征选择
def screening(x, y):
selector = SelectKBest(chi2, k=4) # 选择 4 个特征
selector.fit_transform(x, y)
cols = x.columns[selector.get_support(indices=True)]
print(cols) # 打印选择的特征
return cols
# 预测结果可视化
def test(x, y):
lr = LogisticRegression(solver='liblinear')
# 创建逻辑回归模型
lr.fit(x, y)
print('模型的准确率为{0}%'.format('%.2f'%(lr.score(x, y)*100)))
x_train, x_test, y_train, y_test = train_test_split(x, y) # 划分训练集和测试集
y_pred = lr.predict(x_test)
# 1.绘制散点图
plt.figure(figsize=(14, 12))
plt.subplots_adjust(hspace=.3) # 调整子图间的距离
plt.subplot(311)
plt.scatter(range(len(x_test)), y_test+0.5, c='g', s=2, label='test')
plt.scatter(range(len(x_test)), y_pred, c='r', s=2, label='pred')
plt.title('测试结果')
plt.yticks([0, 1], ['不违约', '违约'])
plt.legend()
plt.ylim([-0.5, 2.5])
# 2. 绘制小提琴图
data = pandas.concat([pandas.DataFrame(y_pred, columns=['pred']),
pandas.DataFrame(y_test.tolist(), columns=['test'])], axis=1)
data = data.stack().reset_index() # 合并并分类数据
data = data.drop(columns=[data.columns[0]]) # 删除无用的数据
data = data.rename(columns={data.columns[0]: 'labels', data.columns[1]:
'value'}) # 对每一列重命名
data['xzhou'] = 1
# 小提琴图
plt.subplot(312)
plt.title('测试结果')
seaborn.violinplot(data=data, x='xzhou', y='value', split=True, hue='labels')
plt.yticks([0, 1], ['不违约', '违约'])
plt.show()
return lr
# 主函数
def main():
path = './loan/bankloan.csv'
x, y = get_data(path)
cols = screening(x, y)
test(x[cols].values, y)
main()
Index([‘工龄’, ‘地址’, ‘负债率’, ‘信用卡负债’], dtype=‘object’)
模型的准确率为81.43%