【问题标题】:Why can't LinearSVC do this simple classification?为什么 LinearSVC 不能做这个简单的分类?
【发布时间】:2014-01-04 15:16:48
【问题描述】:

我正在尝试使用scikit-learn 中的LinearSVC 对象进行以下简单分类。我试过同时使用 0.10 和 0.14 版本。使用代码:

from sklearn.svm import LinearSVC, SVC
from numpy import *

data = array([[ 1007.,  1076.],
              [ 1017.,  1009.],
              [ 2021.,  2029.],
              [ 2060.,  2085.]])
groups = array([1, 1, 2, 2])

svc = LinearSVC()
svc.fit(data, groups)
svc.predict(data)

我得到了输出:

array([2, 2, 2, 2])

但是,如果我将分类器替换为

svc = SVC(kernel='linear')

然后我得到结果

array([ 1.,  1.,  2.,  2.])

这是正确的。有谁知道为什么使用LinearSVC 会搞砸这个简单的问题?

【问题讨论】:

    标签: python scikit-learn libsvm liblinear


    【解决方案1】:

    LinearSVC 的底层算法对其输入中的极值非常敏感:

    >>> svc = LinearSVC(verbose=1)
    >>> svc.fit(data, groups)
    [LibLinear]....................................................................................................
    optimization finished, #iter = 1000
    
    WARNING: reaching max number of iterations
    Using -s 2 may be faster (also see FAQ)
    
    Objective value = -0.001256
    nSV = 4
    LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
         intercept_scaling=1, loss='l2', multi_class='ovr', penalty='l2',
         random_state=None, tol=0.0001, verbose=1)
    

    (警告指的是 LibLinear 常见问题解答,因为 scikit-learn 的 LinearSVC 是基于该库的。)

    你应该在拟合之前标准化:

    >>> from sklearn.preprocessing import scale
    >>> data = scale(data)
    >>> svc.fit(data, groups)
    [LibLinear]...
    optimization finished, #iter = 39
    Objective value = -0.240988
    nSV = 4
    LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
         intercept_scaling=1, loss='l2', multi_class='ovr', penalty='l2',
         random_state=None, tol=0.0001, verbose=1)
    >>> svc.predict(data)
    array([1, 1, 2, 2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2013-06-09
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2019-08-23
      • 2011-07-08
      相关资源
      最近更新 更多