【问题标题】:Visualize 2D / 3D decision surface in SVM scikit-learn在 SVM scikit-learn 中可视化 2D / 3D 决策面
【发布时间】:2018-12-19 02:20:43
【问题描述】:

我让 sklearn 支持向量机分类器工作。我只是将 2 个选项分类为 0 或 1 使用特征向量。它工作正常。

我想在page 上使用图表将其可视化。

问题是我的向量是 512 项长度,很难在 x,y 图上显示。

有没有什么方法可以可视化分类超平面的特征,比如 512 之类的长向量?

【问题讨论】:

  • 不,你不能。如果你仔细看这个例子,你会发现他们只使用了虹膜数据中实际 4 个特征中的 2 个特征,以便可视化。
  • @查看我的回答,让我知道这是否适合您

标签: python scikit-learn svm


【解决方案1】:

您无法将许多特征的决策面可视化。这是因为维度会太多,无法可视化 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()

【讨论】:

  • 我真的很想知道为什么我的回答被否决了。
猜你喜欢
  • 2015-03-05
  • 2018-12-20
  • 2012-05-21
  • 2020-09-08
  • 2014-03-15
  • 2014-07-10
  • 2015-07-07
  • 2017-07-21
  • 2017-02-23
相关资源
最近更新 更多