scikit-learn - 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"))
解决方案
目前没有 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()
它。如果您打算使用它,我们可以处理它。
推荐阅读
- docker - Docker Compose 将一项服务附加到标准输入和标准输出
- reactjs - 反应中渲染和重新渲染之间的区别?
- angular - 在 Angular 8 中单击按钮时多次调用 Subscribe() 方法
- c# - 我的 ViewModel 流程正确吗?如何将其发送回控制器并在控制器操作上刷新它?
- javascript - 如何通过单击正方形在使用 for 循环创建的板上显示 X
- c# - 更改 TextRange 字体颜色,但不更改将在其旁边写入的文本
- javascript - JS Slider 淡化图像而不是简单的改变
- php - 使用 PHP 将表单数据插入 MYSQL 数据库
- android - Flutter/Dart Android 应用 NoSuchMethodError
- java - AdapterView.OnItemClickListener()