数学建模(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),从而消除不同特征之间的量纲差异。这对于许多机器学习算法来说都非常重要,尤其是使用梯度下降的算法,如逻辑回归、神经网络等。标准化可以加快收敛速度并提高模型性能。

相关推荐
巧克力味的桃子27 分钟前
学习笔记:查找数组第K小的数(去重排名)
笔记·学习·算法
星云POLOAPI31 分钟前
大模型API调用延迟过高?深度解析影响首Token时间的五大因素及优化方案
人工智能·python·算法·ai
88号技师36 分钟前
2026年1月一区SCI-波动光学优化算法Wave Optics Optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
明朝百晓生1 小时前
强化学习[chapter8] [page17] Value Function Methods
人工智能·算法
POLITE31 小时前
Leetcode 56.合并区间 JavaScript (Day 6)
算法·leetcode·职场和发展
历程里程碑2 小时前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode
ghie90902 小时前
使用直接节点积分法进行无网格法2D悬臂梁计算
算法
Helibo442 小时前
2025年12月gesp3级题解
数据结构·c++·算法
p&f°2 小时前
垃圾回收两种算法
java·jvm·算法
点云SLAM2 小时前
点云配准算法之- GICP算法点云配准概率模型推导和最大似然求解(MLE)
算法·机器人·slam·点云配准·最大似然估计·点云数据处理·gicp算法