首页 > 解决方案 > 评分前的后处理交叉验证预测

问题描述

我有一个回归问题,我正在交叉验证结果并评估性能。我事先知道基本事实不能小于零。因此,我想在将预测输入分数指标之前截取预测,以将预测剪裁为零。我认为使用 make_scorer 函数会很有用。是否有可能在交叉验证之后以某种方式对预测进行后处理,但在对其应用评估指标之前?

from sklearn.metrics import mean_squared_error, r2_score, make_scorer
from sklearn.model_selection import cross_validate

# X = Stacked feature vectors
# y = ground truth vector
# regr = some regression estimator

#### How to indicate that the predictions need post-processing 
#### before applying the score function???
scoring = {'r2': make_scorer(r2_score),
           'neg_mse': make_scorer(mean_squared_error)}

scores = cross_validate(regr, X, y, scoring=scoring, cv=10)

PS:我知道有约束估计,但我想看看像这样的启发式方法会如何执行。

标签: pythonscikit-learncross-validation

解决方案


您可以做的一件事是按照您的建议将您希望使用的那些记分器 ( r2_score, mean_squared_error) 包装在自定义记分器函数中make_scorer()

查看sklearn 文档的这一部分Stack Overflow 帖子中的一些示例。特别是,您的函数可以执行以下操作:

def clipped_r2(y_true, y_pred):
    y_pred_clipped = np.clip(y_pred, 0, None)
    return r2_score(y_true, y_pred_clipped)

def clipped_mse(y_true, y_pred):
    y_pred_clipped = (y_pred, 0, None)
    return mean_squared_error(y_true, y_pred_clipped)

r2_score这允许您在调用评分函数(在本例中为or )之前在记分器中进行后处理mean_squared_error。然后要使用它,只需像上面那样使用 make_scorer ,greater_is_better根据 scorer 是评分函数(如 r2,越大越好)或损失函数(mean_squared_error 为 0 时更好,即更少)设置:

scoring = {'r2': make_scorer(clipped_r2, greater_is_better=True),
           'neg_mse': make_scorer(clipped_mse, greater_is_better=False)}
scores = cross_validate(regr, X, y, scoring=scoring, cv=10)

推荐阅读