我需要一个SVM作为多标签分类器,因此我决定使用OneVsRestClassifier包装器。 但是,问题出在训练集变得高度不平衡:对于给定的班级,负面的例子比正面的要多得多。 这可以通过class_weight参数解决,但是如果在包装在OneVsRestClassifier中的分类器中使用它,则会出现错误:

from sklearn.svm import LinearSVC
from sklearn.multiclass import OneVsRestClassifier

weights = {'ham': 1, 'eggs': 2}
svm = OneVsRestClassifier(LinearSVC(class_weight=weights))

X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
Y = [['ham'], [], ['eggs', 'spam'], ['spam'], ['eggs']]

svm.fit(X, Y)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/site-packages/sklearn/multiclass.py", line 197, in fit
    n_jobs=self.n_jobs)
  File "/usr/local/lib/python2.7/site-packages/sklearn/multiclass.py", line 87, in fit_ovr
    for i in range(Y.shape[1]))
  File "/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 514, in __call__
    self.dispatch(function, args, kwargs)
  File "/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 311, in dispatch
    job = ImmediateApply(func, args, kwargs)
  File "/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 135, in __init__
    self.results = func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/sklearn/multiclass.py", line 56, in _fit_binary
    estimator.fit(X, y)
  File "/usr/local/lib/python2.7/site-packages/sklearn/svm/base.py", line 681, in fit
    self.classes_, y)
  File "/usr/local/lib/python2.7/site-packages/sklearn/utils/class_weight.py", line 49, in compute_class_weight
    if classes[i] != c:
IndexError: index 2 is out of bounds for axis 0 with size 2

===============>>#1 票数:5 已采纳

问题在于,LinearSVC需要二进制类[0,1]。 因此,给非二进制类('ham','egg'甚至[0,1,2])赋权是失败的。 但是您可以改用“自动”权重,通过选择适当的权重来自动“平衡”您的班级。 然后,它也可以用于您的多类OneVsRest分类器。

svm = OneVsRestClassifier(LinearSVC(class_weight='auto'))

X = [[1, 2], [3, 4], [5, 4]]
Y = [0,1,2]

svm.fit(X, Y)

  ask by lizarisk translate from so

未解决问题?本站智能推荐: