Matplotlib 利用线性支持向量机绘制三维决策边界

Matplotlib 利用线性支持向量机绘制三维决策边界,matplotlib,scikit-learn,svm,Matplotlib,Scikit Learn,Svm,我使用sklearn.svm.svc()拟合了一个3个特征数据集。我可以使用matplotlib和Axes3D绘制每个观测的点。我想画出决策边界,看看是否合适。我尝试过调整2D示例来绘制决策边界,但没有效果。我知道clf.coef_u是一个垂直于决策边界的向量。我怎样才能画出它来看看它在哪里划分点 下面是一个关于玩具数据集的示例。请注意,使用matplotlib,在3D中打印很时髦。有时,位于飞机后面的点可能看起来像是在飞机前面,因此您可能需要调整绘图以确定发生了什么 将numpy导入为np 将

我使用sklearn.svm.svc()拟合了一个3个特征数据集。我可以使用matplotlib和Axes3D绘制每个观测的点。我想画出决策边界,看看是否合适。我尝试过调整2D示例来绘制决策边界,但没有效果。我知道clf.coef_u是一个垂直于决策边界的向量。我怎样才能画出它来看看它在哪里划分点

下面是一个关于玩具数据集的示例。请注意,使用
matplotlib
,在3D中打印很时髦。有时,位于飞机后面的点可能看起来像是在飞机前面,因此您可能需要调整绘图以确定发生了什么

将numpy导入为np
将matplotlib.pyplot作为plt导入
从mpl_toolkits.mplot3d导入Axes3D
从sklearn.svm导入SVC
rs=np.random.RandomState(1234)
#生成一些虚假数据。
n_样本=200
#X是按行输入的特征。
X=np.零((200,3))
X[:n个样本/2]=rs.多变量正态分布(np.1(3),np.眼(3),大小=n个样本/2)
X[n_样本/2:]=rs.多元_正态(-np.一(3),np.眼(3),大小=n_样本/2)
#Y是X的每一行的类标签。
Y=np.零(n_个样本);Y[n_样本/2:]=1
#用支持向量机拟合数据
svc=svc(kernel='linear')
svc.fit(X,Y)
#分离面方程由R^3中的所有x给出,如下所示:
#np.dot(svc.coef_[0],x)+b=0。我们应该解最后一个坐标
#以x和y绘制平面。
z=lambda x,y:(-svc.intercept_0]-svc.coef_0[0]*x-svc.coef_0[1]*y)/svc.coef_0[2]
tmp=np.linspace(-2,2,51)
x、 y=np.meshgrid(tmp,tmp)
#阴谋的东西。
图=plt.图()
ax=图添加_子图(111,投影='3d')
ax.plot_曲面(x,y,z(x,y))
plot3D(X[Y==0,0],X[Y==0,1],X[Y==0,2],'ob')
plot3D(X[Y==1,0],X[Y==1,1],X[Y==1,2],'sr')
plt.show()
输出:

编辑(上述注释中的关键数学线性代数语句):

#分离面方程由R^3中的所有x给出,如下所示:
#点(系数,x_向量)+截距_值=0。
#我们应该求解最后一个坐标:x_向量[2]==z
#以x和y绘制平面。

您无法为许多功能可视化决策面。这是因为尺寸太多,无法可视化N维曲面。

但是,您可以使用2个功能并按如下方式绘制漂亮的决策面。

我在这里也写了一篇关于这一点的文章:

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

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

谢谢您的回答和非常清晰的解释!我误解了拦截的意思!非常感谢你,切斯特。只有一个小错误或输入错误:
(-svc.intercept[0]-svc.coef[0][0]*x-svc.coef[0][1]
*y
)/svc.coef[0][2]
对于Python3,所有索引分区都应该使用“/”操作符进行编码,以生成具有隐式地板的整数除法。答案非常清晰。关于线性代数的评论没有写在其他地方。我在问题的最后把它孤立起来,并试图使它更一般一些。
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()
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()