【问题标题】:plotting linear SVM绘制线性 SVM
【发布时间】:2015-08-24 20:31:24
【问题描述】:

我尝试按照示例 here 进行操作,但是当我有 16 个功能时,我无法应用它。 lin_svc 使用这 16 个特征进行了训练(我删除了该行以再次从示例中重新训练它)。它有效,我试过了,还提取了.coef_before。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

#features is an array of 16
#lin_svc variable is available 
#train is a pandas DF

X = train[features].as_matrix()
y = train.outcome

h = .02 # step size in the mesh

# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

# title for the plots
titles = ['SVC with linear kernel']



for i, clf in enumerate([lin_svc]):
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    plt.subplot(2, 2, i + 1)
    plt.subplots_adjust(wspace=0.4, hspace=0.4)

    Z = clf.predict(X)

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)
    plt.xlabel('Sepal length')
    plt.ylabel('Sepal width')
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())
    plt.title(titles[i])

plt.show()

我得到的错误是:

ValueError                                Traceback (most recent call last)
<ipython-input-8-d52ca252fc3a> in <module>()
     24 
     25     # Put the result into a color plot
---> 26     Z = Z.reshape(xx.shape)
     27     plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)
     28 

ValueError: total size of new array must be unchanged

【问题讨论】:

    标签: python scikit-learn svm


    【解决方案1】:

    我自己也遇到过同样的问题。由于您真的有兴趣将 Z 绘制为 xx 和 yy 的函数,因此您应该将它们传递给 clf.predict() 而不是传递 X。尝试替换

    Z = clf.predict(X)
    

    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    

    并且情节应该很好地显示(假设没有其他错误)。

    此外,您可能希望将问题的标题更改为“Plotting 2-D Decision Boundary”之类的内容,因为这与 SVM 无关。使用任何 sklearn 分类器都会遇到此类问题。

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 2016-07-13
      • 2015-12-30
      • 2016-02-05
      • 2017-11-20
      • 2016-03-09
      • 2017-09-03
      • 1970-01-01
      • 2017-08-20
      相关资源
      最近更新 更多