【发布时间】:2019-12-09 07:48:41
【问题描述】:
我正在使用 scikit 执行二进制分类。就预测而言,一切似乎都是有序的,但是当我绘制决策边界时,决策边界是重叠的(参见绘图)。现在我意识到 MULTCLASS SVM 将不可避免地导致决策边界重叠,但为什么这会发生在二进制 SVM 分类中呢?据我所知,它们不应该重叠,因为空间被分成了两部分。所以知道为什么我的情节看起来如此混乱和这么多不同的颜色而应该只有两种颜色吗?这是我的阴谋吗?谢谢你。
def createSVMandPlot(X,y,x_name,y_name):
h = .02 # step size in the mesh
# we create an instance of SVM and fit out data. We do not scale our
# data since we want to plot the support vectors
C = 1.0 # SVM regularization parameter
svc = svm.SVC(kernel='linear', C=C).fit(X, y) #1 vs 1
rbf_svc = svm.SVC(kernel='rbf', gamma='scale', C=C).fit(X, y) #1v1
poly_svc = svm.SVC(kernel='poly', degree=3, gamma='scale',C=C).fit(X, y) #1v1
lin_svc = svm.LinearSVC(C=C).fit(X, y) #1 vs rest
print(str(x_name)+' vs. '+str(y_name))
for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):
X_pred=clf.predict(X)
X_pred1=np.asarray(X_pred).reshape(len(X_pred),1)
A=confusion_matrix(X_pred1, y)
print(A)
c=0
for r in range(len(X_pred)):
if X_pred[r]==y[r]:
c+=1
print(str(c)+' out of 34 predicted correctly (true positives)')
=============================================================================
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
=============================================================================
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# title for the plots
titles = ['SVC w/ linear kernel',
'LinearSVC (w/ linear kernel)',
'SVM w/ RBF kernel',
'SVM w/ poly(degree 3) kernel']
plt.pause(7)
for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):
# point in the mesh [x_min, x_max]x[y_min, y_max].
plt.subplot(2, 2, i + 1)
plt.subplots_adjust(wspace=0.4, hspace=0.4)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=.5)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], s=13,c=y)
plt.xlabel(x_name)
plt.ylabel(y_name)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.title(titles[i])
plt.show()
【问题讨论】:
-
自循环以来,您绘制了多个支持向量机的结果。
-
它实际上在一个子情节中。我刚刚拍了 4 个子图之一的照片。或者你是说它在下一次迭代期间将旧图形从那个子图空间(比如第一行,第一列)中保留下来,只是在那个空间的顶部绘制新图形?我应该在我认为的某个地方添加 plt.clf() 吗?谢谢
-
通常如果你有子图,你会得到不同的轴对象,但你没有。只需尝试不使用子图,因此删除与子图相关的两行即可。
-
更新:刚刚通过添加 if(i%4)==0 然后清除绘图来修复它,但某些区域由于某种原因是空白的(请参阅我的问题中名为“Plot2”的新图片) .这可能是什么原因造成的?
-
其实这对我来说很好。你能在没有
plt.contourf的情况下尝试吗?
标签: python machine-learning scikit-learn svm libsvm