OneVsRestClassifier中的多个类的分类器参数可以不同吗

时间:2018-07-10 23:47:45

标签: scikit-learn svm multiclass-classification

有人知道sklearn是否支持OneVsRestClassifier中各种分类器的不同参数吗?例如,在该示例中,我想为不同的类使用不同的C值。

from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
text_clf = OneVsRestClassifier(LinearSVC(C=1.0, class_weight="balanced"))

1 个答案:

答案 0 :(得分:1)

没有OneVsRestClassifier当前没有估计器的不同参数或当前针对不同类的估计器。

还有其他实现方式,例如LogisticRegressionCV,它们会根据类自动调整参数的不同值,但尚未扩展到OneVsRestClassifier。

但是,如果您愿意,我们可以在源代码中进行更改以实现该目的。

fit() in the master branch is this的当前来源:

    ... 
    ...
    self.estimators_ = Parallel(n_jobs=self.n_jobs)(delayed(_fit_binary)(
        self.estimator, X, column, classes=[
            "not %s" % self.label_binarizer_.classes_[i],
            self.label_binarizer_.classes_[i]])
        for i, column in enumerate(columns))

如您所见,同一估计量(self.estimator)传递给所有要训练的课程。因此,我们将制作一个新版本的OneVsRestClassifier来更改此内容:

from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import LabelBinarizer
from sklearn.externals.joblib import Parallel, delayed
from sklearn.multiclass import _fit_binary

class CustomOneVsRestClassifier(OneVsRestClassifier):

    # Changed the estimator to estimators which can take a list now
    def __init__(self, estimators, n_jobs=1):
        self.estimators = estimators
        self.n_jobs = n_jobs

    def fit(self, X, y):

        self.label_binarizer_ = LabelBinarizer(sparse_output=True)
        Y = self.label_binarizer_.fit_transform(y)
        Y = Y.tocsc()
        self.classes_ = self.label_binarizer_.classes_
        columns = (col.toarray().ravel() for col in Y.T)

        # This is where we change the training method
        self.estimators_ = Parallel(n_jobs=self.n_jobs)(delayed(_fit_binary)(
            estimator, X, column, classes=[
                "not %s" % self.label_binarizer_.classes_[i],
                self.label_binarizer_.classes_[i]])
            for i, (column, estimator) in enumerate(zip(columns, self.estimators)))
        return self

现在您可以使用它了。

# Make sure you add those many estimators as there are classes
# In binary case, only a single estimator should be used
estimators = []

# I am considering 3 classes as of now
estimators.append(LinearSVC(C=1.0, class_weight="balanced"))
estimators.append(LinearSVC(C=0.1, class_weight="balanced"))
estimators.append(LinearSVC(C=10, class_weight="balanced"))
clf = CustomOneVsRestClassifier(estimators)

clf.fit(X, y)

注意:我尚未在其中实现partial_fit()。如果您打算使用它,我们可以进行处理。