【问题标题】:why sklearn.svm.SVC's attribute coef_ has shape = [n_class * (n_class-1) / 2, n_features]?为什么 sklearn.svm.SVC 的属性 coef_ 具有 shape = [n_class * (n_class-1) / 2, n_features]?
【发布时间】:2020-08-26 19:43:16
【问题描述】:

我正在使用带有线性内核的 sklearn.svm.SVC,并且我想获得特征重要性,所以我使用属性 coeff_(如此处解释:https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html)是一个形状为 [n_class * ( n_class-1) / 2, n_features],例如我的情况,我有 10 个类和 54 个特征,所以形状是 [45,54],

为什么我得到 45 个权重数组?这些数组中的每一个的含义是什么?因为直觉上我会期望 10 个权重数组,每个类一个

【问题讨论】:

    标签: python scikit-learn svm


    【解决方案1】:

    形状确实 [n_class * (n_class-1) / 2, n_features] 但为什么呢?

    这是因为如果您有 2 个以上的类,即如果您遇到的问题是不是 二进制,那么 multiclass该功能的支持是根据一对一的方案处理的。


    示例: 如果您有 3 个类,比如说 1,2,3,那么分类器将适用于以下情况:1vs2、1vs3 和 2vs3。所以在这里,我们有n_class * (n_class-1) / 2 = 3 * (3-1) / 2 = 3。


    让我们验证一下:

    import numpy as np
    from sklearn.svm import SVC
    
    X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
    y = np.array([1, 1, 2, 3]) # 3 classes
    
    clf = SVC(kernel='linear')
    clf.fit(X, y)
    
    print(clf.coef_)
    [[-0.5        -0.5       ]
     [-0.46153846 -0.30769231]
     [-1.          0.        ]]
    

    这里,在clf.coef_中,每一行分别对应上述情况1vs2、1vs3和2vs3。因此,第一行即[-0.5, -0.5] 为您提供1vs2 分类拟合情况下的第一个和第二个特征/变量的系数。


    P.S:在二进制分类的情况下,print(clf.coef_) 将只为1vs2 分类情况返回一行。


    关于行的顺序:

    在“one-vs-one” SVC 的情况下,属性的布局是 更多的参与。在具有线性内核的情况下, 属性 coef_ 和 intercept_ 的形状为 [n_class * (n_class - 1) / 2, n_features] 和 [n_class * (n_class - 1) / 2] 分别。 这类似于上述 LinearSVC 的布局,每个 行现在对应于二元分类器。第 0 类的顺序 到 n 是“0 对 1”、“0 对 2”、……“0 对 n”、“1 对 2”、“1 对 3”、“1 对 n”、 . . . “n-1 对 n”。

    在https://scikit-learn.org/stable/modules/svm.html中找到的段落

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2019-11-28
      • 1970-01-01
      • 2016-12-03
      • 2018-05-07
      • 2020-10-27
      • 2020-12-20
      • 2020-03-30
      • 1970-01-01
      相关资源
      最近更新 更多