当我尝试绘制决策边界时形状错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当我尝试绘制决策边界时形状错误相关的知识,希望对你有一定的参考价值。

从我的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()

这个错误的原因是什么?

答案

您使用了所有11个特征训练了分类器,但是在Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])方法中调用plot_contours时,您只提供了2个用于评估分类器的特征。要评估使用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

以上是关于当我尝试绘制决策边界时形状错误的主要内容,如果未能解决你的问题,请参考以下文章

SVM 决策边界绘图中的错误

绘制 SVC 拉普拉斯核的决策边界时出错

如何在 libsvm 中绘制 4 维虹膜数据的决策边界?

使用matplotlib在python中绘制曲线决策边界

尝试绘制堆积条形图时收到形状不匹配错误消息

无法理解 SVM 和 LR 中决策边界的绘制