我需要一个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
答案 0 :(得分: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)