绘制多项式和一对多逻辑回归

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

逻辑回归是一种分类算法,可用于二分类和多分类问题。在本实验中,我们将使用 scikit-learn 库绘制两个逻辑回归模型的决策面,即多项式逻辑回归和一对其余逻辑回归。我们将使用一个三分类数据集,并绘制这两个模型的决策边界以比较它们的性能。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/inspection("Inspection") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49203{{"绘制多项式和一对多逻辑回归"}} sklearn/inspection -.-> lab-49203{{"绘制多项式和一对多逻辑回归"}} sklearn/datasets -.-> lab-49203{{"绘制多项式和一对多逻辑回归"}} ml/sklearn -.-> lab-49203{{"绘制多项式和一对多逻辑回归"}} end

导入库

我们将首先导入本实验所需的库。我们将使用 scikit-learn 库来生成数据集并训练逻辑回归模型,使用 matplotlib 库来绘制决策边界。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import DecisionBoundaryDisplay

生成数据集

我们将使用 scikit-learn 中的make_blobs函数生成一个三分类数据集。我们将使用 1000 个样本,并将数据点集的中心设置为[-5, 0], [0, 1.5], [5, -1]。然后,我们将使用一个变换矩阵对数据集进行变换,以使数据集更难分类。

centers = [[-5, 0], [0, 1.5], [5, -1]]
X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
transformation = [[0.4, 0.2], [-0.4, 1.2]]
X = np.dot(X, transformation)

训练多项式逻辑回归模型

现在我们将使用 scikit-learn 中的LogisticRegression函数训练一个多项式逻辑回归模型。我们将求解器设置为sag,最大迭代次数设置为 100,随机数种子设置为 42,多分类选项设置为multinomial。然后我们将打印模型的训练分数。

clf = LogisticRegression(
        solver="sag", max_iter=100, random_state=42, multi_class="multinomial"
    ).fit(X, y)

print("training score : %.3f (%s)" % (clf.score(X, y), "multinomial"))

绘制多项式逻辑回归模型的决策边界

现在我们将使用 scikit-learn 中的DecisionBoundaryDisplay函数绘制多项式逻辑回归模型的决策面。我们将响应方法设置为"predict",颜色映射设置为"plt.cm.Paired",并绘制训练点。

_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("Decision surface of LogisticRegression (multinomial)")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

训练一对多逻辑回归模型

现在我们将使用与步骤 3 中相同的参数训练一个一对多逻辑回归模型,但多分类选项设置为"ovr"。然后我们将打印模型的训练分数。

clf = LogisticRegression(
        solver="sag", max_iter=100, random_state=42, multi_class="ovr"
    ).fit(X, y)

print("training score : %.3f (%s)" % (clf.score(X, y), "ovr"))

绘制一对多逻辑回归模型的决策边界

现在我们将使用与步骤 4 中相同的参数绘制一对多逻辑回归模型的决策面,但将对应于三个一对多分类器的超平面绘制为虚线。

_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("Decision surface of LogisticRegression (ovr)")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
coef = clf.coef_
intercept = clf.intercept_

def plot_hyperplane(c, color):
        def line(x0):
            return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]

        plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color)

for i, color in zip(clf.classes_, colors):
        plot_hyperplane(i, color)

可视化绘图

现在我们将并排可视化这两个绘图,以比较两个模型的决策边界。

plt.subplot(1,2,1)
_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("多项式逻辑回归")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

plt.subplot(1,2,2)
_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("一对多逻辑回归")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
coef = clf.coef_
intercept = clf.intercept_

def plot_hyperplane(c, color):
        def line(x0):
            return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]

        plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color)

for i, color in zip(clf.classes_, colors):
        plot_hyperplane(i, color)

plt.subplots_adjust(wspace=0.5)
plt.show()

总结

在本实验中,我们学习了如何绘制两个逻辑回归模型的决策面,即多项式逻辑回归和一对多逻辑回归。我们使用了一个三类数据集,并通过绘制它们的决策边界来比较这两个模型的性能。我们观察到,多项式逻辑回归模型的决策边界更平滑,而一对多逻辑回归模型对每个类别都有三个独立的决策边界。