OneVsRestClassifier 可用于在 Python Scikit-Learn 中生成单独的二元分类器模型吗?

Kub*_*888 3 python-3.x scikit-learn multiclass-classification

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

对于我的示例,我有多类标签label1, label2, label3,但不是在最后进行总结,而是可以OneVsRestClassifier()迭代地为我提供二元分类。

我喜欢获得 3 个经过训练的 ML 模型。第一个是针对label1其余的 ( label2 and label3),第二个是针对label2其余的 ( label1 and label3),第三个是针对label3其余的 ( label1 and label2)。

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

Max*_*Kan 5

训练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)
Run Code Online (Sandbox Code Playgroud)

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

OVRC.estimators_[0] # label 0 vs the rest
OVRC.estimators_[1] # label 1 vs the rest
OVRC.estimators_[2] # label 2 vs the rest
Run Code Online (Sandbox Code Playgroud)

他们的个人预测如下:

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]]
Run Code Online (Sandbox Code Playgroud)

这与总体预测一致,即:

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   ]]
Run Code Online (Sandbox Code Playgroud)