利用逻辑回归模型预测贷款违约行为

贷款违约预测是现代金融机构信用风险管理的基础。金融机构审批贷款时会收集客户的个人信息,包括年龄、收入、学历、职业、家庭情况和借贷历史等,在对各项信息综合考虑的基础上决定是否审批贷款。为了避免贷款违约,金融机构在对借款人发放贷款的时候必须对借款人的信用程度进行评估打分,预测贷款违约的概率,并做出是否发放贷款的判断。
本案例利用逻辑回归模型预测贷款人是否会发生违约行为。通过贷款数据(包括个人信息、财务状况和贷款状态等)来训练模型,通过模型分析贷款人的偿还能力,预测贷款申请人是否会发生违约。
点击此处下载相关数据集
# 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%
在这里插入图片描述

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 导入必要的库和数据 首先,我们需要导入必要的库和数据。在这里,我们使用的是scikit-learn内置的贷款违约数据集。 ```python import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 导入数据集 data = pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/german.csv', header=None) # 设置列名 data.columns = ['checking_account', 'duration', 'credit_history', 'purpose', 'credit_amount', 'savings_account', 'employment', 'installment_rate', 'personal_status', 'other_debtors', 'residence_since', 'property', 'age', 'other_installment_plans', 'housing', 'existing_credits', 'job', 'num_dependents', 'own_telephone', 'foreign_worker', 'class'] # 查看前5行数据 print(data.head()) ``` 输出: ``` checking_account duration credit_history purpose credit_amount \ 0 A11 6 A34 A43 1169 1 A12 48 A32 A43 5951 2 A14 12 A34 A46 2096 3 A11 42 A32 A42 7882 4 A11 24 A33 A40 4870 savings_account employment installment_rate personal_status other_debtors \ 0 A65 A75 4 A93 A101 1 A61 A73 2 A92 A101 2 A61 A74 2 A93 A101 3 A61 A74 2 A93 A103 4 A61 A73 3 A93 A101 ... property age other_installment_plans housing existing_credits job \ 0 ... A121 67 A143 A152 2 A173 1 ... A121 22 A143 A152 1 A173 2 ... A121 49 A143 A152 1 A172 3 ... A122 45 A143 A153 1 A173 4 ... A124 53 A143 A153 2 A173 num_dependents own_telephone foreign_worker class 0 1 A192 A201 1 1 1 A191 A201 2 2 2 A191 A201 1 3 2 A191 A201 1 4 2 A191 A201 2 [5 rows x 21 columns] ``` 2. 数据预处理 接下来,我们需要对数据进行预处理,包括将分类变量进行编码、将样本分为训练集和测试集等。 ```python # 将分类变量进行编码 data = pd.get_dummies(data, columns=['checking_account', 'credit_history', 'purpose', 'savings_account', 'employment', 'personal_status', 'other_debtors', 'property', 'other_installment_plans', 'housing', 'job', 'own_telephone', 'foreign_worker']) # 将类别变量class转换为0和1 data['class'] = data['class'].apply(lambda x: 0 if x == 2 else 1) # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(data.drop('class', axis=1), data['class'], test_size=0.2, random_state=42) ``` 3. 训练模型 接下来,我们使用逻辑回归模型贷款人的违约风险进行分类。我们使用scikit-learn的LogisticRegression类。 ```python # 训练模型 model = LogisticRegression() model.fit(X_train, y_train) ``` 4. 预测并评估模型 最后,我们使用测试集对模型进行评估,并计算模型的准确性。 ```python # 预测并评估模型 y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print('Accuracy:', accuracy) ``` 输出: ``` Accuracy: 0.775 ``` 这意味着我们的模型可以正确地分类贷款人的违约风险约77.5%的时间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值