簡體   English   中英

繪制超平面線性SVM Python

[英]Plot hyperplane Linear SVM python

我正在嘗試為用LinearSVC和sklearn訓練的模型繪制超平面。 請注意,我正在使用自然語言。 在擬合模型之前,我使用CountVectorizer和TfidfTransformer提取了特征。

這里是分類器:

from sklearn.svm import LinearSVC
from sklearn import svm

clf = LinearSVC(C=0.2).fit(X_train_tf, y_train)

然后我嘗試按照Scikit-learn網站上的建議進行繪圖:

# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clf.intercept_[0]) / w[1]

# plot the parallels to the separating hyperplane that pass through the
# support vectors
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])

# plot the line, the points, and the nearest vectors to the plane
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')

plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
            s=80, facecolors='none')
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)

plt.axis('tight')
plt.show()

此示例使用svm.SVC(kernel ='linear'),而我的分類器是LinearSVC。 因此,我收到此錯誤:

AttributeError                            Traceback (most recent call last)
<ipython-input-39-6e231c530d87> in <module>()
      7 # plot the parallels to the separating hyperplane that pass through the
      8 # support vectors
----> 9 b = clf.support_vectors_[0]
     1 yy_down = a * xx + (b[1] - a * b[0])
     11 b = clf.support_vectors_[-1]

AttributeError: 'LinearSVC' object has no attribute 'support_vectors_'

如何成功繪制我的LinearSVC分類器的超級計划?

怎么樣離開support_出來,這不是一個定義LinearSVC

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

np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20

fig, ax = plt.subplots()
clf2 = svm.LinearSVC(C=1).fit(X, Y)

# get the separating hyperplane
w = clf2.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clf2.intercept_[0]) / w[1]

# 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
xx2, yy2 = np.meshgrid(np.arange(x_min, x_max, .2),
                     np.arange(y_min, y_max, .2))
Z = clf2.predict(np.c_[xx2.ravel(), yy2.ravel()])

Z = Z.reshape(xx2.shape)
ax.contourf(xx2, yy2, Z, cmap=plt.cm.coolwarm, alpha=0.3)
ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.coolwarm, s=25)
ax.plot(xx,yy)

ax.axis([x_min, x_max,y_min, y_max])
plt.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM