看起来您可能正在使用 sklearn 的 VotingClassifier。安装好分类器后,您可以通过属性predict_proba 看到与每个类关联的概率。请注意,这不是准确度,而是每个类别的相关概率。因此,如果您希望测试样本属于n 类的概率,则必须在相应列上索引输出y_pred_prob。下面是一个使用 sklearn 的 iris 数据集的例子:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
clf1 = LogisticRegression(multi_class='multinomial', random_state=1)
clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
clf3 = GaussianNB()
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y)
eclf2 = VotingClassifier(estimators=[
('lr', clf1), ('rf', clf2), ('gnb', clf3)],
voting='soft')
eclf2 = eclf2.fit(X_train, y_train)
我们可以得到与第一类相关的概率,例如:
eclf2.predict_proba(X_test)[:,0].round(2)
array([0.99, 0. , 0. , 0. , 0. , 0. , 0.01, 0.01, 0. , 0. , 0. ,
0.99, 0. , 0.99, 0.99, 0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0.01, 0.98, 0. , 1. , 0.99, 0. , 0. , 0. , 0.99, 0.98,
0. , 0.99, 0. , 0.01, 0.99])
最后,为了得到你描述的输出,你可以使用predict返回的结果来索引二维概率数组,如下所示:
import pandas as pd
y_pred = eclf2.predict(X_test)
y_pred_prob = eclf2.predict_proba(X_test).round(2)
associated_prob = y_pred_prob[np.arange(len(y_test)), y_pred]
pd.DataFrame({'class':y_pred, 'Accuracy':associated_prob})
class Accuracy
0 0 0.99
1 2 0.84
2 2 1.00
3 1 0.95
4 2 0.99
5 2 0.91
6 1 0.98
7 1 0.98
8 1 0.93
或者,如果您更喜欢将输出作为字典:
pd.DataFrame({'class':y_pred, 'Accuracy':associated_prob}).to_dict(orient='index')
{0: {'class': 0, 'Accuracy': 0.99},
1: {'class': 2, 'Accuracy': 0.84},
2: {'class': 2, 'Accuracy': 1.0},
3: {'class': 1, 'Accuracy': 0.95},
4: {'class': 2, 'Accuracy': 0.99},