我使用RandomizedSearchCV
通过10次交叉验证和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_
答案 0 :(得分:1)
如果我理解正确,您希望获得具有最高CV分数的案例的测试分组中每个样本的个别分数。如果是这种情况,您必须使用其中一个CV生成器来控制拆分索引,例如:http://scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html#cross-validation-generators
如果您想使用性能最佳的模型计算新测试样本的分数,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)
我自己没有对代码进行过测试,但应该稍加修改。
答案 1 :(得分:1)
你需要查看cv_results_
这会给你得分,平均所有折叠的分数,以及平均值,拟合时间等......
如果你想对每个迭代predict_proba()
,那么这样做的方法是循环遍历cv_results_
中给出的参数,然后重新拟合每个模型,然后预测概率,因为就我所知,个别模型没有缓存在任何地方。
best_params_
将为您提供最佳拟合参数,如果您希望下次使用最佳参数训练模型。
请参阅信息页面http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html
中的cv_results_