首页 > 解决方案 > OneVsRestClassifier中的多个类的Classifier的参数可以不同吗

问题描述

有谁知道 sklearn 是否支持 a 中各种分类器的不同参数OneVsRestClassifier?例如,在那个例子中,我想C为不同的类设置不同的值。

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

标签: scikit-learnsvmmulticlass-classification

解决方案


目前没有 OneVsRestClassifier 没有不同的估计器参数或不同类的不同估计器。

在其他方面也有一些实现,例如LogisticRegressionCV,它会根据类自动调整不同的参数值,但它还没有为 OneVsRestClassifier 扩展。

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

fit()master 分支中的当前来源是:

    ... 
    ...
    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()它。如果您打算使用它,我们可以处理它。


推荐阅读