我使用RandomizedSearchCV
进行10折交叉验证和100次迭代,以获得最佳参数。这种方法效果很好。但是现在我想从性能最佳的模型中获取每个预测测试数据点的概率(如predict_proba
)。
这该如何实现呢?
我看到了两种选择。首先,可能可以直接从RandomizedSearchCV
中获取这些概率;其次,从RandomizedSearchCV
中获取最佳参数,然后使用这些最佳参数再次进行10折交叉验证(使用相同的种子以获得相同的分割)。
编辑:以下代码是否正确,用于获取性能最佳模型的概率?X是训练数据,y是标签,model是包含Pipeline
的RandomizedSearchCV
,该Pipeline
包括缺失值填补、标准化和SVM。
cv_outer = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)y_prob = np.empty([y.size, nrClasses]) * np.nanbest_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生成器,例如这里的这些:http://scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html#cross-validation-generators
如果您想用性能最佳的模型计算新测试样本的得分,那么RandomizedSearchCV
的predict_proba()
函数就足够了,前提是您的底层模型支持它。
示例:
import numpyskf = 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) # 这是您之前应该已经创建的模型对象
最后,通过以下方式获取您的预测:
model.predict_proba(X_test)
我没有亲自测试过代码,但经过小的修改应该可以工作。