2017-10-01 11 views
1

LinearSVC 및 sklearn을 사용하여 교육 한 모델의 초평면을 플롯하려고합니다. 자연어로 작업하고 있음을 유의하십시오. 모델을 맞추기 전에 CountVectorizer 및 TfidfTransformer로 피쳐를 추출했습니다.플롯 초평형 선형 SVM 파이썬

# 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 (커널 = '선형')를 사용하여 내 분류가 LinearSVC 동안, 다음은

분류 : on the Scikit-learn website을 제안 그리고

from sklearn.svm import LinearSVC 
from sklearn import svm 

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

나는 음모 시도 .

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 분류의 hyperplan을 플롯 할 수 있습니다 : 따라서,이 오류가?

+0

그것이 : http://scikit-learn.org/0.18/auto_examples/svm/plot_separating_hyperplane.html – Alex

+0

나는 그 예를 그들이 선형 SVM 또 다른 커널을 사용하는 것이 알고 있지만, 내 분류자를 플로팅하고 싶습니다. – Alex

+0

글의 목적은 오류의 원인을 찾는 것과 같지만 문서에 명확하게 나와 있습니다 : * "LinearSVC는 키워드 커널을 허용하지 않습니다. 선형으로 가정합니다. 또한 SVC와 NuSVC의 구성원 중 일부는'support_'와 같이 부족합니다. "* LinearSVC의 사용법에 대해서는 많이 알지 못하지만 유사한 결과물을 원하는지 분명히하기 위해 질문을 다시 할 수있을 것입니다. 'SVC'를 사용하지만 대신''support_vectors_'' 속성이없는'LinearSVC'를 사용하십시오. 이런 식으로 사람들은 명백한 것을 찾기 위해 깊게 파고들 필요가 없습니다. – ImportanceOfBeingErnest

답변

1

LinearSVC에 대해 정의되지 않은 support_을 퇴장시키지 않으려면 어떻게해야합니까?

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() 

enter image description here

다음
+0

이 줄에서 실패합니다 : ----> 8 x_min, x_max = X [:, 0] .min() - 1, X [:, 0] .max() + 1 오류 : TypeError : unhashable 유형 : 'slice' – Alex

+0

예, 정확한 코드를 실행하고 있습니다. 나는 파이썬 3.6, sklearn 0.19, numpy 1.13을 사용한다. – Alex

+0

커널을 다시 시작하려고 시도했는데 이제는 작동한다. 하지만 지금은 내가 훈련 한 모델의 초평면을 어떻게 그릴 수 있습니까? – Alex