在我的wine-dataset中,我试图在两列之间绘制决策边界,该边界由代码段描述:
X0, X1 = X[:, 10], Y
我从scikit svm plot tutorial中获取了以下代码,并进行了修改,以替换为变量名/索引。但是,当我运行以下代码时,出现错误消息:
ValueError: X.shape[1] = 2 should be equal to 11, the number of features at training time
错误堆栈为:
Traceback (most recent call last):
File "test-wine.py", line 120, in <module>
cmap=plt.cm.coolwarm, alpha=0.8)
File "test-wine.py", line 96, in plot_contours
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
File "/home/suhail/anaconda3/envs/ml/lib/python3.5/site-packages/sklearn/svm/base.py", line 548, in predict
y = super(BaseSVC, self).predict(X)
File "/home/suhail/anaconda3/envs/ml/lib/python3.5/site-packages/sklearn/svm/base.py", line 308, in predict
X = self._validate_for_predict(X)
File "/home/suhail/anaconda3/envs/ml/lib/python3.5/site-packages/sklearn/svm/base.py", line 459, in _validate_for_predict
(n_features, self.shape_fit_[1]))
ValueError: X.shape[1] = 2 should be equal to 11, the number of features at training time
我无法理解上述错误的原因。这是我修改过的代码。
import pandas as pd
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv('winequality-red.csv').values
x_data_shape = data.shape[0]
y_data_shape = data.shape[1]
X = data[:, 0:y_data_shape-1]
Y = data[:, y_data_shape-1]
############### PLOT DECISION BOUNDARY SVM #############
def make_meshgrid(x, y, h=.02):
"""Create a mesh of points to plot in
Parameters
----------
x: data to base x-axis meshgrid on
y: data to base y-axis meshgrid on
h: stepsize for meshgrid, optional
Returns
-------
xx, yy : ndarray
"""
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
def plot_contours(ax, clf, xx, yy, **params):
"""Plot the decision boundaries for a classifier.
Parameters
----------
ax: matplotlib axes object
clf: a classifier
xx: meshgrid ndarray
yy: meshgrid ndarray
params: dictionary of params to pass to contourf, optional
"""
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
return out
C = 1.0 # SVM regularization parameter
models = (SVC(kernel='linear', C=C),
SVC(kernel='rbf', gamma=0.7, C=C),
SVC(kernel='poly', degree=3, C=C))
models = (clf.fit(X, Y) for clf in models)
titles = ('SVC with linear kernel',
'SVC with RBF kernel',
'SVC with polynomial (degree 3) kernel')
fig, sub = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.4, hspace=0.4)
X0, X1 = X[:, 10], Y
xx, yy = make_meshgrid(X0, X1)
for clf, title, ax in zip(models, titles, sub.flatten()):
plot_contours(ax, clf, xx, yy,
cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X0, X1, c=Y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('Alcohol Content')
ax.set_ylabel('Quality')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
plt.show()
此错误的原因可能是什么?
答案 0 :(得分:0)
您使用所有11种功能训练了分类器,
但是您仅提供2个用于评估分类器的功能,这是从Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
方法中调用plot_contours
时发生的。
要评估训练有11个功能的分类器,您需要提供所有11个功能。这就是您的错误消息所指示的。
因此,为了使该代码段对您有用,您应该将自己限制为两个功能(否则绘制二维决策边界无论如何都没有意义),例如通过使用
X = data[:, :2]
Y = data[:, y_data_shape-1]
在读取数据时。
请注意,您所指的example也仅使用两个功能:
# import some data to play with
iris = datasets.load_iris()
# Take the first two features. We could avoid this by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target