机器学习——逻辑回归实战2——预测拖欠款

原理:

逻辑回归是一种用于分类问题的统计方法,尤其适用于二分类。它通过Sigmoid函数将线性回归的输出映射到[0,1]区间,表示样本属于某一类的概率。模型使用最大似然估计进行参数优化,常用梯度下降法求解。虽然名为"回归",但主要用于分类任务。

案例:

下面,我们利用逻辑回归的思想,实现一个预测拖欠款的案例:

1、导入相关库:
python 复制代码
import pandas as pd
import matplotlib.pyplot as plt
from pylab import mpl
import numpy as np
2、读取数据、绘制混淆矩阵:
python 复制代码
data=pd.read_csv('data.csv')
#绘制可视化混淆矩阵
def cm_plot(y,yp):
    from sklearn.metrics import confusion_matrix
    import  matplotlib.pyplot as plt

    cm = confusion_matrix(y,yp)
    plt.matshow(cm,cmap=plt.cm.Blues)
    plt.colorbar()
    for x in range(len(cm)):
        for y in range(len(cm)):
            plt.annotate(cm[x,y],xy=(y,x),horizontalalignment='center',
                         verticalalignment='center')
            plt.ylabel('True label')
            plt.xlabel('Predicted label')
    return plt
3、数据标准化:
python 复制代码
scaler = StandardScaler()
data['当前工作年限'] = scaler.fit_transform(data[['当前工作年限']])
data['家庭收入'] = scaler.fit_transform(data[['家庭收入']])
data['债务占收入比例'] = scaler.fit_transform(data[['债务占收入比例']])
data['其他负债'] = scaler.fit_transform(data[['其他负债']])
data['当前居住年限'] = scaler.fit_transform(data[['当前居住年限']])
data['年龄'] = scaler.fit_transform(data[['年龄']])

# data = data.drop(['年龄'], axis=1)  # 删除无用列
# data = data.drop(['当前居住年限'], axis=1)
4、划分数据集:
python 复制代码
from sklearn.model_selection import train_test_split

# 划分训练集和测试集
X = data.drop('还款拖欠情况', axis=1)
y = data.还款拖欠情况
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)
5、过采样扩充数据,并再次划分:
python 复制代码
from imblearn.over_sampling import SMOTE

oversampler =SMOTE(random_state=0)
os_x_train,os_y_train=oversampler.fit_resample(x_train,y_train)

new_x_train,new_x_test,new_y_train,new_y_test =\
    train_test_split(os_x_train,os_y_train,test_size = 0.3,random_state = 0)
6、获取最优逻辑回归门限值C
python 复制代码
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

scores=[]
c_param_range=[0.1,0.01,1,10,100]
for i in c_param_range:
    lr=LogisticRegression(C=i,penalty='l2',solver='lbfgs',max_iter=1000)
    score=cross_val_score(lr,new_x_train,new_y_train,cv=8,scoring='recall')
    score_mean=sum(score)/len(score)
    scores.append(score_mean)
    print(score_mean)

best_c=c_param_range[np.argmax(scores)]
注意:score 是一个包含 8 个召回率值的数组

使用 cross_val_score 对模型进行交叉验证

7、建立并训练模型:
python 复制代码
lr=LogisticRegression(C=best_c,penalty='l2',max_iter=1000)
lr.fit(os_x_train,os_y_train)
8、模型测试:
python 复制代码
from sklearn import metrics

train_predicted=lr.predict(new_x_train)
print(metrics.classification_report(new_y_train,train_predicted))
# cm_plot(new_y_train,train_predicted).show()

test_predicted=lr.predict(new_x_test)
print(metrics.classification_report(new_y_test,test_predicted))
# cm_plot(new_y_test,test_predicted).show()

test1_predicted=lr.predict(x_test)
print(metrics.classification_report(y_test,test1_predicted))
# cm_plot(y_test,test1_predicted).show()
运行结果如下:

总结:

在数据集的划分过程中,我们要注意训练集与测试集的划分,避免模型出现欠拟合与过拟合的状况

注:以上全为个人观点,若有错误,欢迎指正

相关推荐
IT_陈寒4 小时前
React状态更新后视图不刷新?我差点以为是灵异事件
前端·人工智能·后端
蓦然回首却已人去楼空4 小时前
深度学习进阶:自然语言处理|3.4 QA|共享权重与 `remove_duplicate` 详解
人工智能·深度学习·自然语言处理
searchforAI4 小时前
我用这款本土NotebookLM平替重构了知识库
人工智能·笔记·gpt·ai·音视频·知识图谱
不懂的浪漫4 小时前
01|从 Spring Boot 项目理解 RAG:ingest、query、rerank、trace 到 eval
java·人工智能·spring boot·后端·ai·rag
无心水4 小时前
【分布式利器:金融级】金融级分布式架构开源框架全景解读
人工智能·分布式·金融·架构·开源·wpf·金融级框架
在线打码4 小时前
从零打造“绘礼AI”:如何用AI重构婚礼策划全流程
人工智能·langchain·agent·婚礼策划
x-cmd4 小时前
[260520] x-cmd v0.9.5:x install 支持 skill 安装,新增 git ci 命令让 AI 帮你写 commit
人工智能·git·ci/cd·agent·install·x-cmd
晚霞的不甘4 小时前
CANN昇腾 MindSpore 适配深入解析:如何在 MindSpore 框架中充分发挥昇腾硬件性能的完整指南
人工智能·python·transformer
阿牛大牛中4 小时前
阿里-RecGPT-Mobile
大数据·人工智能·算法
晚霞的不甘4 小时前
CANN-昇腾NPU开发快速入门
人工智能·pytorch·python·深度学习