如何在 scikit-learn 中使用交叉验证获得预测概率

How to get the prediction probabilities using cross validation in scikit-learn

我正在使用 RandomForestClassifier 如下使用二进制 classification 的交叉验证(class 标签是 01).

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score

clf=RandomForestClassifier(random_state = 42, class_weight="balanced")
k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
accuracy = cross_val_score(clf, X, y, cv=k_fold, scoring = 'accuracy')
print("Accuracy: " + str(round(100*accuracy.mean(), 2)) + "%")
f1 = cross_val_score(clf, X, y, cv=k_fold, scoring = 'f1_weighted')
print("F Measure: " + str(round(100*f1.mean(), 2)) + "%")

现在我想使用 class 1 的预测概率和 cross validation 结果来排序我的数据。为此,我尝试了以下两种方式。

pred = clf.predict_proba(X)[:,1]
print(pred)

probs = clf.predict_proba(X)
best_n = np.argsort(probs, axis=1)[:,-6:]

我收到以下错误

NotFittedError: This RandomForestClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.

对于这两种情况。

我只是想知道我哪里做错了。

如果需要,我很乐意提供更多详细信息。

看看 documentation 它指定概率是根据树的平均结果计算的。

在您的情况下,您首先需要调用 fit() 方法来生成模型中的树。在训练数据上拟合模型后,您可以调用 predict_proba() 方法。

这个错误中也有说明。

# Fit model
model = RandomForestClassifier(...)
model.fit(X_train, Y_train)

# Probabilty
model.predict_proba(X)[:,1]

我使用以下代码解决了我的问题:

proba = cross_val_predict(clf, X, y, cv=k_fold, method='predict_proba')
print(proba[:,1])
print(np.argsort(proba[:,1]))

如果您想对未见过的数据使用 CV 模型point/s,请使用以下方法。

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate

iris = datasets.load_iris()
X = iris.data
y = iris.target
clf = RandomForestClassifier(n_estimators=10, random_state = 42, class_weight="balanced")

cv_results = cross_validate(clf, X, y, cv=3, return_estimator=True)

clf_fold_0 = cv_results['estimator'][0]

clf_fold_0.predict_proba([iris.data[133]])

# array([[0. , 0.5, 0.5]])