机器学习——逻辑回归实战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()
运行结果如下:

总结:

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

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

相关推荐
我没胡说八道20 小时前
高校论文AI检测优化工具对比研究与实测分析(2026)
人工智能·深度学习·机器学习·计算机视觉·aigc·论文
秦亚伟20 小时前
AI浪潮重塑融资租赁行业新格局
人工智能
love530love20 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
元启数宇20 小时前
喷淋AI布点实战:8小时人工布点→20分钟自动出图
人工智能
哈哈,柳暗花明20 小时前
人工智能专业术语详解(H)
人工智能·专业术语
圣殿骑士-Khtangc20 小时前
AI 编程工具 2026 实战横评:Cursor 3 vs Claude Code vs Copilot,开发者选型完全指南
人工智能·copilot
云器科技20 小时前
云器Lakehouse 2026年5月版本发布:拥抱 AI Agent,重塑数据智能开发新范式
人工智能
小鹰-上海鹰谷-电子实验记录本20 小时前
第六届党建引领科创生态座谈会 | 邓光辉博士出席分享AI赋能创新药科研新范式
人工智能·ai·电子实验记录本·药企合规
极客老王说Agent20 小时前
2026电信IDC机房巡检深度报告:人工巡检频次和深度够吗?实在Agent重塑智慧运维新范式
人工智能·ai·chatgpt
海兰20 小时前
【水浒传:第二篇】AI江湖 —项目详细设计指南(一)
jvm·人工智能·游戏