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

总结:

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

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

相关推荐
格林威5 小时前
机器视觉检测的光源基础知识及光源选型
人工智能·深度学习·数码相机·yolo·计算机视觉·视觉检测
今天也要学习吖5 小时前
谷歌nano banana官方Prompt模板发布,解锁六大图像生成风格
人工智能·学习·ai·prompt·nano banana·谷歌ai
Hello123网站5 小时前
glean-企业级AI搜索和知识发现平台
人工智能·产品运营·ai工具
AKAMAI5 小时前
Queue-it 为数十亿用户增强在线体验
人工智能·云原生·云计算
索迪迈科技5 小时前
INDEMIND亮相2025科技创变者大会,以机器人空间智能技术解锁具身智能新边界
人工智能·机器人·扫地机器人·空间智能·陪伴机器人
栒U6 小时前
一文从零部署vLLM+qwen0.5b(mac本地版,不可以实操GPU单元)
人工智能·macos·vllm
沫儿笙6 小时前
FANUC发那科焊接机器人铝材焊接节气
人工智能·机器人
THMAIL6 小时前
量化股票从贫穷到财务自由之路 - 零基础搭建Python量化环境:Anaconda、Jupyter实战指南
linux·人工智能·python·深度学习·机器学习·金融
~-~%%6 小时前
从PyTorch到ONNX:模型部署性能提升
人工智能·pytorch·python
xcnn_6 小时前
深度学习基础概念回顾(Pytorch架构)
人工智能·pytorch·深度学习