支持向量回归

Machine LearningMachine LearningBeginner
立即练习

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

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

简介

在本实验中,我们将使用支持向量回归(Support Vector Regression,SVR),通过线性、多项式和径向基函数(Radial Basis Function,RBF)内核为一维数据集拟合模型。我们将使用 Python 的 scikit-learn 库来执行 SVR。

虚拟机使用提示

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/svm("Support Vector Machines") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/svm -.-> lab-49310{{"支持向量回归"}} ml/sklearn -.-> lab-49310{{"支持向量回归"}} end

生成样本数据

首先,我们生成一个由40个介于0到5之间的随机值组成的样本数据集。然后,我们计算每个值的正弦函数,并每隔5个值添加一些噪声。

import numpy as np

## 生成样本数据
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()

## 给目标值添加噪声
y[::5] += 3 * (0.5 - np.random.rand(8))

拟合回归模型

接下来,我们使用线性、多项式和径向基函数(RBF)内核为我们的样本数据集拟合一个支持向量回归(SVR)模型。我们为每个模型设置超参数,并在我们的样本数据集上对它们进行训练。

from sklearn.svm import SVR

## 拟合回归模型
svr_rbf = SVR(kernel="rbf", C=100, gamma=0.1, epsilon=0.1)
svr_lin = SVR(kernel="linear", C=100, gamma="auto")
svr_poly = SVR(kernel="poly", C=100, gamma="auto", degree=3, epsilon=0.1, coef0=1)

svrs = [svr_rbf, svr_lin, svr_poly]

for svr in svrs:
    svr.fit(X, y)

可视化结果

最后,我们通过将支持向量回归(SVR)模型的结果与样本数据集进行对比绘图,来可视化这些结果。我们还绘制了支持向量和其他训练数据。

import matplotlib.pyplot as plt

## 查看结果
lw = 2

内核标签 = ["RBF", "线性", "多项式"]
模型颜色 = ["m", "c", "g"]

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10), sharey=True)

for ix, svr in enumerate(svrs):
    axes[ix].plot(
        X,
        svr.predict(X),
        color=模型颜色[ix],
        lw=lw,
        label="{} 模型".format(内核标签[ix])
    )
    axes[ix].scatter(
        X[svr.support_],
        y[svr.support_],
        facecolor="none",
        edgecolor=模型颜色[ix],
        s=50,
        label="{} 支持向量".format(内核标签[ix])
    )
    axes[ix].scatter(
        X[np.setdiff1d(np.arange(len(X)), svr.support_)],
        y[np.setdiff1d(np.arange(len(X)), svr.support_)],
        facecolor="none",
        edgecolor="k",
        s=50,
        label="其他训练数据"
    )
    axes[ix].legend(
        loc="upper center",
        bbox_to_anchor=(0.5, 1.1),
        ncol=1,
        fancybox=True,
        shadow=True
    )

fig.text(0.5, 0.04, "数据", ha="center", va="center")
fig.text(0.06, 0.5, "目标", ha="center", va="center", rotation="vertical")
fig.suptitle("支持向量回归", fontsize=14)
plt.show()

总结

在本实验中,我们学习了如何使用支持向量回归(Support Vector Regression,SVR),通过线性、多项式和径向基函数(RBF)内核为一维数据集拟合模型。我们生成了样本数据,使用 scikit-learn 拟合回归模型,并可视化了结果。