如何在 sklearn Python 中绘制 SVM 决策边界?

新手上路,请多包涵

将 SVM 与 sklearn 库一起使用,我想用每个代表其颜色的标签绘制数据。我不想给点上色,而是用颜色填充区域。

我现在有了 :

 d_pred, d_train_std, d_test_std, l_train, l_test

d_pred 是预测的标签。我会用形状为 d_train_std 的 d_pred 绘制:(70000,2) 其中 X 轴是第一列,Y 轴是第二列。

谢谢你。

原文由 anthonya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 849
2 个回答

您无法将许多特征的决策面可视化。这是因为维度太多了,没有办法可视化一个 N 维的表面。

但是,您可以使用 2 个特征并绘制漂亮的决策面,如下所示。

我还在此处写了一篇关于此的文章: https ://towardsdatascience.com/support-vector-machines-svm-clearly-explained-a-python-tutorial-for-classification-problems-29c539f3ad8?source=friends_link&sk=80f72ab272550d76a0cc3730d7c8af35

案例 1:2 个特征的 2D 图并使用 iris 数据集

from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets

iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features.
y = iris.target

def make_meshgrid(x, y, h=.02):
    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    return xx, yy

def plot_contours(ax, clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = ax.contourf(xx, yy, Z, **params)
    return out

model = svm.SVC(kernel='linear')
clf = model.fit(X, y)

fig, ax = plt.subplots()
# title for the plots
title = ('Decision surface of linear SVC ')
# Set-up grid for plotting.
X0, X1 = X[:, 0], X[:, 1]
xx, yy = make_meshgrid(X0, X1)

plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_ylabel('y label here')
ax.set_xlabel('x label here')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
ax.legend()
plt.show()

在此处输入图像描述

案例 2:3 个特征的 3D 图并使用 iris 数据集

from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from mpl_toolkits.mplot3d import Axes3D

iris = datasets.load_iris()
X = iris.data[:, :3]  # we only take the first three features.
Y = iris.target

#make it binary classification problem
X = X[np.logical_or(Y==0,Y==1)]
Y = Y[np.logical_or(Y==0,Y==1)]

model = svm.SVC(kernel='linear')
clf = model.fit(X, Y)

# The equation of the separating plane is given by all x so that np.dot(svc.coef_[0], x) + b = 0.
# Solve for w3 (z)
z = lambda x,y: (-clf.intercept_[0]-clf.coef_[0][0]*x -clf.coef_[0][1]*y) / clf.coef_[0][2]

tmp = np.linspace(-5,5,30)
x,y = np.meshgrid(tmp,tmp)

fig = plt.figure()
ax  = fig.add_subplot(111, projection='3d')
ax.plot3D(X[Y==0,0], X[Y==0,1], X[Y==0,2],'ob')
ax.plot3D(X[Y==1,0], X[Y==1,1], X[Y==1,2],'sr')
ax.plot_surface(x, y, z(x,y))
ax.view_init(30, 60)
plt.show()

在此处输入图像描述

原文由 seralouk 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我的代码,它执行@Christian Tuchez 描述的内容:

 outputs = my_clf.predict(1_test)

hits = []
for i in range(outputs.size):
    if outputs[i] == 1:
        hits.append(i)  # save the index where it's 1

这将保存函数中命中的所有点的索引(保存在“命中”列表中)。您可能无需循环即可完成此操作,我发现这对我来说最简单。

然后只显示这些点,你会写这样的东西:

 ax.scatter(1_test[hits[:], 0], 1_test[hits[:], 1], 1_test[hits[:], 2], c="cyan", s=2, edgecolor=None)

原文由 Yagoobean 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题