我如何在scikit-learn
个二进制分类器中的N
中构建一个元分类器,如果任何分类器返回1
,该二进制分类器将返回1
?
目前我已经尝试过VotingClassifier
,但是它缺乏我需要的逻辑,两者都voting
等于hard
和soft
。 Pipeline
似乎面向顺序计算
我可以自己编写逻辑,但是我想知道是否内置了什么?
答案 0 :(得分:2)
内置选项只有soft
和hard
投票。如您所提到的,我们可以为此元分类器创建一个自定义函数,该函数基于源代码here的用户OR
逻辑。此自定义元分类器也可以适合pipeline
。
from sklearn.utils.validation import check_is_fitted
class CustomMetaClassifier(VotingClassifier):
def predict(self, X):
""" Predict class labels for X.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
The input samples.
Returns
----------
maj : array-like, shape = [n_samples]
Predicted class labels.
"""
check_is_fitted(self, 'estimators_')
maj = np.max(eclf1._predict(X), 1)
maj = self.le_.inverse_transform(maj)
return maj
>>> import numpy as np
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.naive_bayes import GaussianNB
>>> from sklearn.ensemble import RandomForestClassifier, VotingClassifier
>>> clf1 = LogisticRegression(solver='lbfgs', multi_class='multinomial',
... random_state=1)
>>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
>>> clf3 = GaussianNB()
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> eclf1 = CustomMetaClassifier(estimators=[
... ('lr', clf1), ('rf', clf2), ('gnb', clf3)])
>>> eclf1 = eclf1.fit(X, y)
>>> eclf1.predict(X)
array([1, 1, 1, 2, 2, 2])