当前位置:   article > 正文

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

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

一、二分类

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn import datasets
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.preprocessing import StandardScaler
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
  8. # 加载数据集
  9. iris = datasets.load_iris()
  10. X = iris.data[:, :2] # 只使用前两个特征
  11. y = (iris.target != 0) * 1 # 将标签转换为二分类问题
  12. # 数据标准化
  13. scaler = StandardScaler()
  14. X = scaler.fit_transform(X)
  15. # 划分训练集和测试集
  16. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
  17. # 训练逻辑回归模型
  18. clf = LogisticRegression()
  19. clf.fit(X_train, y_train)
  20. # 预测
  21. y_pred = clf.predict(X_test)
  22. # 计算准确率
  23. accuracy = accuracy_score(y_test, y_pred)
  24. print(f"Accuracy: {accuracy}")
  25. # 分类报告
  26. print("Classification Report:")
  27. print(classification_report(y_test, y_pred))
  28. # 混淆矩阵
  29. print("Confusion Matrix:")
  30. print(confusion_matrix(y_test, y_pred))
  31. # 绘制决策边界
  32. def plot_decision_boundary(clf, X, y):
  33. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
  34. y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
  35. xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
  36. np.arange(y_min, y_max, 0.01))
  37. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
  38. Z = Z.reshape(xx.shape)
  39. plt.contourf(xx, yy, Z, alpha=0.8)
  40. plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', marker='o')
  41. plt.xlabel('Feature 1')
  42. plt.ylabel('Feature 2')
  43. plt.title('Logistic Regression Decision Boundary')
  44. plt.show()
  45. plot_decision_boundary(clf, X, y)

二、算法介绍

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/876261
推荐阅读
相关标签
  

闽ICP备14008679号