代码之家  ›  专栏  ›  技术社区  ›  arnold_107

获得支持向量机的决策边界

  •  3
  • arnold_107  · 技术社区  · 8 年前

    http://scikit-learn.org/stable/auto_examples/svm/plot_separating_hyperplane.html

    我想获得图中所示(线)决策边界的系数。 呼叫

    clf.coef_ 
    

    [[-0.2539717  -0.83806387]]
    

    如果我没有弄错的话,它代表了方程的一条线

    y = -0.83806387 * x - 0.2539717
    

    然而,上面的线不是示例中获得的决策边界,那么coef_到底是什么?如何获得线性决策边界的方程?

    3 回复  |  直到 8 年前
        1
  •  5
  •   Christopher Wells    8 年前

    要获得线性模型决策边界线的方程,需要同时获得 coef_ intercept_ . 还请注意,由于您使用的是SVC,因此将涉及多个决策边界。

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

    哪里 w0 获得自 , w1 在中可以找到后续项 系数_ 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

        2
  •  3
  •   Prem    8 年前

    如果你想绘制线性图,即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)
    

    希望这有帮助!

        3
  •  1
  •   pyano    7 年前

    谢谢@Prem和@ChristopherWells-这真的很有帮助。我结合了这两个答案,因为在Prem的代码中没有包含y\u目标(->参见Christopher的答案),这对于y\u目标=0很好。

    logRegression tutorial from scikitLearn . 我插入了以下代码:

    mf = logreg.intercept_.shape[0];
    xm = np.r_[np.min(X),np.max(X)]
    yf = logreg.classes_.copy()
    xm = np.r_[np.min(X),np.max(X)]
    
    for jf in np.arange(mf):
        tmp = logreg.coef_[jf]
        a = - tmp[0] / tmp[1]; 
        b = - (logreg.intercept_[jf]-yf[jf]) / tmp[1]
        yy = a * xm + b
        plt.plot(xm, yy, label='Coeff ='+str(jf))
    plt.legend()
    plt.show()
    

    Examlpe from scikitLearn: LogisticRegression