加权数据集决策函数绘制

Beginner

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

简介

在本教程中,我们将学习如何使用 scikit-learn 绘制加权数据集的决策函数。我们还将学习如何为数据集中的样本分配不同的权重,以展示权重如何影响决策函数。

虚拟机使用提示

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

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

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

导入所需库

我们首先为项目导入必要的库。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model

创建加权数据集

我们使用 numpy 库创建一个加权数据集。我们生成 20 个具有随机值的点,并为最后 10 个样本分配更大的权重。

np.random.seed(0)
X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)]
y = [1] * 10 + [-1] * 10
sample_weight = 100 * np.abs(np.random.randn(20))
sample_weight[:10] *= 10

绘制加权数据集

我们使用 matplotlib 库绘制加权数据集。点的大小与其权重成正比。

xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500))
fig, ax = plt.subplots()
ax.scatter(
    X[:, 0],
    X[:, 1],
    c=y,
    s=sample_weight,
    alpha=0.9,
    cmap=plt.cm.bone,
    edgecolor="black",
)

拟合未加权模型

我们使用 scikit-learn 库中的 SGDClassifier 算法拟合一个未加权模型。然后,我们绘制未加权模型的决策函数。

clf = linear_model.SGDClassifier(alpha=0.01, max_iter=100)
clf.fit(X, y)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
no_weights = ax.contour(xx, yy, Z, levels=[0], linestyles=["solid"])

拟合加权模型

我们使用与步骤 4 中相同的算法来拟合一个加权模型,但这次我们将 sample_weight 参数传递给 fit 方法。然后,我们绘制加权模型的决策函数。

clf = linear_model.SGDClassifier(alpha=0.01, max_iter=100)
clf.fit(X, y, sample_weight=sample_weight)
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
samples_weights = ax.contour(xx, yy, Z, levels=[0], linestyles=["dashed"])

添加图例并显示图形

我们在图形中添加一个图例,以区分未加权模型和加权模型。然后,我们显示该图形。

no_weights_handles, _ = no_weights.legend_elements()
weights_handles, _ = samples_weights.legend_elements()
ax.legend(
    [no_weights_handles[0], weights_handles[0]],
    ["no weights", "with weights"],
    loc="lower left",
)

ax.set(xticks=(), yticks=())
plt.show()

总结

在本教程中,我们学习了如何使用 scikit-learn 绘制加权数据集的决策函数。我们还学习了如何为数据集中的样本分配不同的权重,以展示权重如何影响决策函数。