当前位置: 代码网 > it编程>前端脚本>Python > 数学建模(5)——逻辑回归

数学建模(5)——逻辑回归

2024年08月02日 Python 我要评论
【代码】数学建模(5)——逻辑回归预测模型。

一、二分类

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import standardscaler
from sklearn.linear_model import logisticregression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# 加载数据集
iris = datasets.load_iris()
x = iris.data[:, :2]  # 只使用前两个特征
y = (iris.target != 0) * 1  # 将标签转换为二分类问题

# 数据标准化
scaler = standardscaler()
x = scaler.fit_transform(x)

# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)

# 训练逻辑回归模型
clf = logisticregression()
clf.fit(x_train, y_train)

# 预测
y_pred = clf.predict(x_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"accuracy: {accuracy}")

# 分类报告
print("classification report:")
print(classification_report(y_test, y_pred))

# 混淆矩阵
print("confusion matrix:")
print(confusion_matrix(y_test, y_pred))

# 绘制决策边界
def plot_decision_boundary(clf, x, y):
    x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
    y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
                         np.arange(y_min, y_max, 0.01))
    z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    z = z.reshape(xx.shape)
    plt.contourf(xx, yy, z, alpha=0.8)
    plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', marker='o')
    plt.xlabel('feature 1')
    plt.ylabel('feature 2')
    plt.title('logistic regression decision boundary')
    plt.show()

plot_decision_boundary(clf, x, y)

二、算法介绍

        逻辑回归是一种二分类算法,它只能处理两个类别

        标准化的目的是将特征数据调整到一个标准的范围内(通常是均值为0,标准差为1),从而消除不同特征之间的量纲差异。这对于许多机器学习算法来说都非常重要,尤其是使用梯度下降的算法,如逻辑回归、神经网络等。标准化可以加快收敛速度并提高模型性能。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com