[英]Here is the code to visualize SVM decision boundary. I am unable to spot the error. Please have a look
**注意:变量x包含5个维度的特征向量的30个元组。 这些x的值被传输到x_train.x可以想象为x = [[1.0,2.0,3,0,4.0,5.0],[11.0,12.0,13.0,14.0,15.0],[21.0, 22.0,23.0,24.0,25,0],.. .. ..]和y =标签= [1,1,1、2、2、2、3、3、3 ...]我希望应用PCA在x上缩小为二维,然后绘制决策边界。 我能够绘制点,但无法绘制到决策边界**
x_train = x
y_train =labels
pca = PCA(n_components=2).fit(x_train)
pca_2d = pca.transform(x_train)
clf = svm.SVC(kernel='linear',C = 3)
clf.fit(pca_2d, y_train)
for i in range(1, pca_2d.shape[0]):
if y_train[i] == 1:
c1 = pl.scatter(pca_2d[i,0],pca_2d[i,1],c='r', s=50,marker='+')
elif y_train[i] == 2:
c2 = pl.scatter(pca_2d[i,0],pca_2d[i,1],c='r', s=50,marker='.')
elif y_train[i] == 3:
c3 = pl.scatter(pca_2d[i,0],pca_2d[i,1],c='r', s=50,marker=',')
elif y_train[i] == 4:
c4 = pl.scatter(pca_2d[i,0],pca_2d[i,1],c='r', s=50,marker='^')
elif y_train[i] == 5:
c5 = pl.scatter(pca_2d[i,0],pca_2d[i,1],c='r', s=50,marker='v')
elif y_train[i] == 6:
x_min, x_max = pca_2d[:, 0].min() - 1, pca_2d[:,0].max() + 1
y_min, y_max = pca_2d[:, 1].min() - 1, pca_2d[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, .01),np.arange(y_min,y_max, .01))
#************ ERROR ******#
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
#************ ERROR ******#
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)
pl.title('Support Vector Machine Decision Surface')
pl.axis('off')
pl.show()
## The error shown is :
Traceback (most recent call last):
File "D:\New folder_previous.2 - Copy.right\main_pos.py", line 354, in <module>
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
File "C:\Python27\lib\site-packages\numpy\lib\index_tricks.py", line 338, in __getitem__
res = _nx.concatenate(tuple(objs), axis=self.axis)
MemoryError
该错误是很直截了当的,您正在尝试分配过多的内存。 使用大于0.1的步长,调查矩阵的大小,可能您在xx,yy中生成了很大的一个。 此外-为什么循环中的所有内容都围绕样本? 您似乎打了30次电话,这似乎不太合理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.