我正在使用RandomizedSearchCV通过10倍交叉验证和100次迭代来获取最佳参数。这很好。但是现在我也想从性能最好的模型中获得每个预测的测试数据点(如predict_proba)的概率。

如何才能做到这一点?

我看到两个选择。首先,也许可以直接从RandomizedSearchCV获得这些概率,或者第二,从RandomizedSearchCV获得最佳参数,然后再次进行10倍交叉验证(使用相同的种子,以便获得相同的分割) )的最佳参数。

编辑:以下代码是否正确,以获得最佳性能模型的概率? X是训练数据,y是标签,模型是我的RandomizedSearchCV,其中包含带有估算缺失值,标准化和SVM的Pipeline

cv_outer = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
y_prob = np.empty([y.size, nrClasses]) * np.nan
best_model = model.fit(X, y).best_estimator_

for train, test in cv_outer.split(X, y):
    probas_ = best_model.fit(X[train], y[train]).predict_proba(X[test])
    y_prob[test] = probas_

最佳答案

如果我理解正确,那么您希望针对CV得分最高的案例获得测试样本中每个样本的得分。如果是这种情况,则必须使用那些可以控制拆分索引的CV生成器之一,例如此处的

如果要使用性能最佳的模型来计算新测试样本的分数,则只要基础模型支持该功能,则predict_proba()RandomizedSearchCV函数就足够了。

例:

import numpy
skf = StratifiedKFold(n_splits=10, random_state=0, shuffle=True)
scores = cross_val_score(svc, X, y, cv=skf, n_jobs=-1)
max_score_split = numpy.argmax(scores)


现在您知道最好的模型发生在max_score_split上,您可以自行拆分并使其适合模型。

train_indices, test_indices = k_fold.split(X)[max_score_split]
X_train = X[train_indices]
y_train = y[train_indices]
X_test = X[test_indices]
y_test = y[test_indices]
model.fit(X_train, y_train) # this is your model object that should have been created before


最后通过以下方式获得您的预测:

model.predict_proba(X_test)


我还没有亲自测试过代码,但应该对其进行较小的修改。