gpt4 book ai didi

python-3.x - OneVsRestClassifier 能否用于在 Python Scikit-Learn 中生成单独的二元分类器模型?

转载 作者:行者123 更新时间:2023-12-05 02:11:04 27 4
gpt4 key购买 nike

我正在阅读 Scikit-learn 的 OneVsRestClassifier() 文档,link .在我看来,OneVsRestClassifier 首先将多个类二值化为二进制类,然后训练模型,并对每个类重复。然后在最后,它将分数“平均”到可以预测多个类别的最终 ML 模型中。

对于我的例子,我有多类标签 label1, label2, label3,但不是在最后总结,是否可以使用 OneVsRestClassifier() 给我二元分类,迭代。

我喜欢获得 3 个训练有素的 ML 模型。第一个是 label1 对比其余部分(label2 和 label3),第二个是 label2 对比其余部分(label1 和 label3 code>),第三个是 label3 与其余部分(label1 和 label2)。

我知道我可以手动对结果标签进行二值化/二分法,并运行二进制 ML 算法三次。但我想知道 OneVsRestClassifier() 是否有更好、更高效的能力来替代这种手动工作。

最佳答案

训练完 OneVsRestClassifier 模型后,所有二元分类器都会保存在 estimators_ 属性中。这是您如何通过一个快速示例来使用它们:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import train_test_split

iris = load_iris() #iris has 3 classes, just like your example
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y, random_state = 42)

RFC = RandomForestClassifier(100, random_state = 42)
OVRC = OneVsRestClassifier(RFC)

OVRC.fit(X_train, y_train)

可以通过以下方式访问您的三个分类器:

OVRC.estimators_[0] # label 0 vs the rest
OVRC.estimators_[1] # label 1 vs the rest
OVRC.estimators_[2] # label 2 vs the rest

他们各自的预测可以得到如下:

print(OVRC.estimators_[0].predict_proba(X_test[0:5]))
print(OVRC.estimators_[1].predict_proba(X_test[0:5]))
print(OVRC.estimators_[2].predict_proba(X_test[0:5]))

>>> [[1. 0. ]
[0.03 0.97] # vote for label 0
[1. 0. ]
[1. 0. ]
[1. 0. ]]
[[0.02 0.98] # vote for label 1
[0.97 0.03]
[0.97 0.03]
[0. 1. ] # vote for label 1
[0.19 0.81]] # vote for label 1
[[0.99 0.01]
[1. 0. ]
[0. 1. ] # vote for label 2
[0.99 0.01]
[0.85 0.15]]

这与整体预测一致,即:

print(OVRC.predict_proba(X_test[0:5]))

>>> [[0. 0.98989899 0.01010101]
[0.97 0.03 0. ]
[0. 0.02912621 0.97087379]
[0. 0.99009901 0.00990099]
[0. 0.84375 0.15625 ]]

关于python-3.x - OneVsRestClassifier 能否用于在 Python Scikit-Learn 中生成单独的二元分类器模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57962736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com