我想根据使用支持向量机给出的类来绘制数据。我被困在这段代码中。
错误显示在 - > Z = Z.reshape(XX.shape)
请注意,代码是从sklearn-svm导入的。当我尝试更改给应用程序的数据集时,会显示上面的错误。
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. We could
# avoid this ugly slicing by using a two-dim dataset
Y = iris.target
Y = np.array(Y)
# figure number
fignum = 1
# fit the model
for kernel in ('linear', 'poly', 'rbf'):
clf = svm.SVC(kernel=kernel, gamma=2)
clf.fit(X, Y)
# plot the line, the points, and the nearest vectors to the plane
plt.figure(fignum, figsize=(4, 3))
plt.clf()
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
facecolors='none', zorder=10)
plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired)
plt.axis('tight')
x_min = 0
x_max = 10
y_min = 0
y_max = 10
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# Put the result into a color plot
Z = Z.reshape(XX.shape)
#print Z
plt.figure(fignum, figsize=(4, 3))
plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],levels=[-.5, 0, .5])
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
fignum = fignum + 1
plt.show()
答案 0 :(得分:1)
XX
和YY
的形状均为(200, 200)
,但您的Z
形状为(40000, 3)
。因此XX
和YY
都包含40000个值,而Z有120000个值,因此不能简单地将其重新整形为XX
或YY
的形状,因为您会丢失值。对decision_function()
的调用不会像您期望的那样返回形状(N_samples, 1)
的矩阵。相反,根据scikit documentation,它会返回(N_samples, n_class * (n_class-1) / 2)
。您可以用predict()
替换呼叫以获得(可能)期望的结果,即
Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])