如何在scikit-learn中用N二进制分类器构建元分类器,如果其中任何一个分类器返回1,该分类器将返回1。
目前,我已经尝试过VotingClassifier,但是它缺乏我所需要的逻辑,无论是voting还是hard和soft。Pipeline似乎是面向顺序计算的。
我可以自己写逻辑,但我想知道是否有内置的东西?
发布于 2019-04-08 11:06:09
内置选项只有soft和hard投票。正如您所提到的,我们可以为这个元分类器创建一个自定义函数,它使用基于源代码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])https://stackoverflow.com/questions/55558640
复制相似问题