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

相关推荐
鹿角片ljp8 分钟前
LeetCode 22:括号生成|回溯dfs、剪枝与 char[] 覆盖代替撤销
算法·深度优先
sylviiiiiia24 分钟前
leetcode hot100
python·算法·leetcode
纪伊路上盛名在37 分钟前
Kabsch算法的Julia实现
开发语言·算法·julia·序列分析·蛋白质·rmsd
裕晟资质规划1 小时前
军工保密资质二级申报的四个可量化硬条件:条文位置、数值口径与西安配套企业实务要点
java·服务器·网络·数据库·算法
LuminousCPP1 小时前
数据结构-排序(一):基础排序算法横向对比|冒泡、插入、希尔、堆与双向选择,详解二分 / Knuth 增量
c语言·数据结构·笔记·算法·排序算法
统计学小王子1 小时前
数学建模国赛倒计时 3 天 ——《统计模型精讲(分位数回归R语言实现二)》
数学建模·回归·r语言
Nil2081 小时前
leetcode 46全排列
算法·leetcode·职场和发展
辰烨chenye1 小时前
LeetCode Hot 100 题解 · 动态规划篇
算法·leetcode·动态规划
青山木2 小时前
Hot 100 --- 买卖股票的最佳时机
java·数据结构·算法·leetcode·贪心算法
wlkdb2 小时前
大模型/Agent 时代下的视觉算法
图像处理·算法·计算机视觉