首页 > 解决方案 > 获得 RandomizedSearchCV 最佳模型的概率

问题描述

我使用RandomizedSearchCV10 倍交叉验证和 100 次迭代来获得最佳参数。这很好用。但现在我还想predict_proba从表现最好的模型中获得每个预测的测试数据点(如 )的概率。

如何才能做到这一点?

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

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

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_

标签: pythonmachine-learningscikit-learngrid-search

解决方案


如果我理解正确,您希望获得测试拆分中每个样本的个人分数,以获取最高 CV 分数的案例。如果是这种情况,您必须使用可以控制拆分索引的 CV 生成器之一,例如此处的那些:http: //scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html#cross-验证生成器

如果您想使用性能最佳的模型计算新测试样本的分数,那么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)

我自己没有测试过代码,但应该稍作修改。


推荐阅读