2017-08-26 80 views
3

在下面的例子: http://scikit-learn.org/stable/auto_examples/svm/plot_separating_hyperplane.html獲取決策邊界爲SVM

我想獲得圖中所示的(線)決策邊界的係數。 到

clf.coef_ 

返回

[[-0.2539717 -0.83806387]] 

一種呼叫,如果我沒有弄錯,代表方程的線

y = -0.83806387 * x - 0.2539717 

然而,上述線是沒有得到所述決定邊界在這個例子中,coef_究竟是什麼,我怎樣才能獲得線性決策邊界的方程?

回答

2

要獲得線性模型決策邊界線的方程,您需要同時獲得coef_intercept_。另請注意,由於您使用的是SVC,因此會涉及多個決策邊界。

線方程可以構造爲:

y = w0 + w1 * x1 + w2 * x2 + ...

w0intercept_獲得w1起在coef_發現,和x1及以後是你的特點。

例如,此代碼顯示如何打印出每個決策邊界的方程式。

from sklearn import svm 
import numpy as np 

clf = svm.SVC(kernel="linear") 

X = np.array([[1, 2], [3, 4], [5, 1], [6, 2]]) 
y = np.array(["A", "B", "A", "C"]) 

clf.fit(X, y) 

for (intercept, coef) in zip(clf.intercept_, clf.coef_): 
    s = "y = {0:.3f}".format(intercept) 
    for (i, c) in enumerate(coef): 
     s += " + {0:.3f} * x{1}".format(c, i) 

    print(s) 

在本例中,線被確定爲:

y = 2.800 + -0.200 * x0 + -0.800 * x1 
y = 7.000 + -1.000 * x0 + -1.000 * x1 
y = 1.154 + -0.462 * x0 + 0.308 * x1 

來源:http://scikit-learn.org/stable/modules/linear_model.html

1

如果你想繪製線性圖,即Y = AX + B,那麼你可以使用下面塊的代碼

tmp = clf.coef_[0] 
a = - tmp[0]/tmp[1] 

b = - (clf.intercept_[0])/tmp[1] 

xx = np.linspace(xlim[0], xlim[1]) 
yy = a * xx + b 
plt.plot(xx, yy) 

希望這有助於!