【发布时间】:2021-01-15 23:19:35
【问题描述】:
我在绘制脑海中的图像时遇到了一些麻烦。 我想用支持向量机可视化内核技巧。所以我制作了一些由两个圆(一个内圆和一个外圆)组成的二维数据,它们应该被一个超平面隔开。显然这在二维中是不可能的——所以我将它们转换为 3D。设 n 为样本数。现在我有一个 (n,3)-array (3 columns, n rows) X 数据点和一个 (n,1)-array y 和标签。使用 sklearn 我通过
得到线性分类器clf = svm.SVC(kernel='linear', C=1000)
clf.fit(X, y)
我已经将数据点绘制为散点图
plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)
现在我想将分离超平面绘制为曲面图。我的问题是缺少超平面的显式表示,因为决策函数仅通过decision_function = 0 产生隐式超平面。因此,我需要绘制一个 4 维对象的级别集(级别 0)。
由于我不是 python 专家,如果有人可以帮助我,我将不胜感激!而且我知道这并不是使用 SVM 的真正“风格”,但我需要这张图片作为我论文的插图。
编辑:我当前的“代码”
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_blobs, make_circles
from tikzplotlib import save as tikz_save
plt.close('all')
# we create 50 separable points
#X, y = make_blobs(n_samples=40, centers=2, random_state=6)
X, y = make_circles(n_samples=50, factor=0.5, random_state=4, noise=.05)
X2, y2 = make_circles(n_samples=50, factor=0.2, random_state=5, noise=.08)
X = np.append(X,X2, axis=0)
y = np.append(y,y2, axis=0)
# shifte X to [0,2]x[0,2]
X = np.array([[item[0] + 1, item[1] + 1] for item in X])
X[X<0] = 0.01
clf = svm.SVC(kernel='rbf', C=1000)
clf.fit(X, y)
plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)
# plot the decision function
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# create grid to evaluate model
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = clf.decision_function(xy).reshape(XX.shape)
# plot decision boundary and margins
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--','-','--'])
# plot support vectors
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,
linewidth=1, facecolors='none', edgecolors='k')
################## KERNEL TRICK - 3D ##################
trans_X = np.array([[item[0]**2, item[1]**2, np.sqrt(2*item[0]*item[1])] for item in X])
fig = plt.figure()
ax = plt.axes(projection ="3d")
# creating scatter plot
ax.scatter3D(trans_X[:,0],trans_X[:,1],trans_X[:,2], c = y, cmap=plt.cm.Paired)
clf2 = svm.SVC(kernel='linear', C=1000)
clf2.fit(trans_X, y)
ax = plt.gca(projection='3d')
xlim = ax.get_xlim()
ylim = ax.get_ylim()
zlim = ax.get_zlim()
### from here i don't know what to do ###
xx = np.linspace(xlim[0], xlim[1], 3)
yy = np.linspace(ylim[0], ylim[1], 3)
zz = np.linspace(zlim[0], zlim[1], 3)
ZZ, YY, XX = np.meshgrid(zz, yy, xx)
xyz = np.vstack([XX.ravel(), YY.ravel(), ZZ.ravel()]).T
Z = clf2.decision_function(xyz).reshape(XX.shape)
#ax.contour(XX, YY, ZZ, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--','-','--'])
期望的输出
我想得到类似that 的东西。 总的来说,我想重构他们在this article 中所做的事情,尤其是“非线性变换”。
【问题讨论】:
-
您能否分享您的数据和所需的输出以提供'minimal, reproducible example'?
-
我编辑了我的帖子 - 我希望这会有所帮助。我知道这并不是最小的,但也许更容易理解我想要做什么。
标签: python matplotlib svm