我尝试绘制决策边界时的形状错误
Posted
技术标签:
【中文标题】我尝试绘制决策边界时的形状错误【英文标题】:Shape error as I try to plot the decision boundary 【发布时间】:2019-02-27 00:30:57 【问题描述】:在我的wine-dataset 中,我正在尝试绘制由 sn-p 描述的 2 列之间的决策边界:
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()
这个错误的原因可能是什么?
【问题讨论】:
【参考方案1】:您使用所有 11 个特征训练了分类器,
但是您只提供了 2 个特性来评估分类器,当从 plot_contours
方法中调用 Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
时会发生这种情况。
要评估使用 11 个特征训练的分类器,您需要提供所有 11 个特征。这就是您的错误消息所表明的。
因此,为了使 sn-p 适合您,您应该将自己限制在两个特征(否则绘制二维决策边界无论如何都没有意义),例如使用
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
【讨论】:
以上是关于我尝试绘制决策边界时的形状错误的主要内容,如果未能解决你的问题,请参考以下文章