[英]I am getting this ValueError: total size of new array must be unchanged error. Can anyone resolve?
我想根據使用支持向量機提供的類來繪制數據。 我陷入了這段代碼。
錯誤顯示在-> 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()
XX
和YY
都具有形狀(200, 200)
,但是Z
卻具有形狀(40000, 3)
。 因此XX
和YY
都包含40000個值,而Z具有120000個值,因此不能簡單地重塑為XX
或YY
的形狀,因為會丟失值。 如您所料,對decision_function()
的調用不會返回形狀矩陣(N_samples, 1)
。 相反,根據scikit文檔 ,它返回(N_samples, n_class * (n_class-1) / 2)
。 您可以將調用替換為predict()
以獲取(可能)所需的結果,即
Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.