如何使用sklearn同时获得概率和标签预测

Cri*_*jon 6 python classification machine-learning scikit-learn

我有一个多类分类器,我需要同时获取概率和标签。

model.predict_proba(X)返回每个数据点的所有训练类的概率。

model.predict(X)返回每个数据点的标签。

我不想对每个数据点预测两次。

Gha*_*nem 5

只需使用predict_proba然后获取标签即可np.argmax

dataset = read_csv('pollution.csv', header=0, index_col=0)
x = dataset[['pollution', 'dew', 'temp', 'press', 'wnd_spd', 'snow']].values
y = dataset[['wnd_dir']].values
from sklearn.ensemble import RandomForestClassifier

cls = RandomForestClassifier(random_state=0)
cls.fit(x, y)

z = cls.predict_proba(x)
labels = np.argmax(z, axis=1)
classes = cls.classes_
labels = [classes[i] for i in labels]
print(accuracy_score(y, labels))
Run Code Online (Sandbox Code Playgroud)