逻辑回归模型:案例实战-银行客户违约预警模型
数据
(客户信息及违约表现.xlsx)
包含 特征变量:收入,年龄,性别,历史授信额度,历史违约次数,以及目标变量:是否违约。
工具
jupyter notebook
代码
导入相关库
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
1.读取数据(客户信息及违约表现.xlsx)
data=pd.read_excel('客户信息及违约表现.xlsx')
data.head()
2.划分特征变量和目标变量
X = data.drop(['是否违约'],axis=1)
y = data['是否违约']
3.划分训练集和测试集
# 设置random_state使得每次划分的数据一样
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1)
# 显示训练集X_train的前5行,在别的代码编辑器里需要通过print()函数打印查看
X_train.head()
# 显示训练集y_train的前5行,在别的代码编辑器里需要通过print()函数打印查看
y_train.head()
# 显示测试集X_test的前5行,在别的代码编辑器里需要通过print()函数打印查看
X_test.head()
# 显示测试集y_test的前5行,在别的代码编辑器里需要通过print()函数打印查看
y_test.head()
4.模型搭建
model = LogisticRegression()
model.fit(X_train,y_train)
5.模型使用 1- 预测数据结果
y_pred = model.predict(X_test)
# 打印预测内容的前100个看看
print(y_pred[:100])
将预测值和实际值放到一个DataFrame里进行查看比对
a = pd.DataFrame()
a['预测值'] = list(y_pred)
a['实际值'] = list(y_test)
# 可以看到此时前5个预测准确度为80%
a.head(5)
# 查看全部的预测准确度
from sklearn.metrics import accuracy_score
score = accuracy_score(y_pred,y_test)
print(score)
另外一种查看模型预测准确度的方法
model.score(X_test,y_test)
6.模型使用2 - 预测概率,并显示5行
y_pred_proba = model.predict_proba(X_test)
y_pred_proba[0:5]
# 另一种查看概率的方式,并显示5行
a = pd.DataFrame(y_pred_proba, columns = ['不违约概率','违约概率'])
a.head()
# 只查看流失的概率(也即y=1概率,即上面二维数组的第二列)
y_pred_proba[:,1]
7.查看各个特征变量的系数:系数和截距项
model.coef_
model.intercept_
#通过公式获取流失概率,这里演示前5条测试集数据的预测流失的概率
for i in range(5):
print(1/(1+np.exp(-(np.dot(X_test.iloc[i], model.coef_.T) + model.intercept_))))
模型评估 - ROC曲线与KS曲线
导入相关模块
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
1.计算ROC曲线需要的假警报率(fpr)、命中率(tpr)及阈值(thres)
fpr,tpr,thres = roc_curve(y_test,y_pred_proba[:,1])
2.创建一个空DataFrame ,查看前5条假警报率(fpr)、命中率(tpr)及阈值(thres)
a = pd.DataFrame()
a['阈值'] = list(thres)
a['假警报率'] = list(fpr)
a['命中率'] = list(tpr)
a.head()
3.绘制ROC曲线
fpr,tpr,thres = roc_curve(y_test,y_pred_proba[:,1])
a = pd.DataFrame()
a['阈值'] = list(thres)
a['假警报率'] = list(fpr)
a['命中率'] = list(tpr)
import matplotlib.pyplot as plt
plt.plot(fpr, tpr)
plt.show()
4.求出模型的AUC值
score = roc_auc_score(y_test,y_pred_proba[:,1])
score