python - 评分前的后处理交叉验证预测
问题描述
我有一个回归问题,我正在交叉验证结果并评估性能。我事先知道基本事实不能小于零。因此,我想在将预测输入分数指标之前截取预测,以将预测剪裁为零。我认为使用 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:我知道有约束估计,但我想看看像这样的启发式方法会如何执行。
解决方案
您可以做的一件事是按照您的建议将您希望使用的那些记分器 ( 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)
推荐阅读
- oracle - ORA-01858 在执行创建的过程时
- kotlin - RxJava2 如果元素当前存在于流中,则忽略它
- docker - 如何通过容器的 IP 地址访问 Docker 容器的服务?
- ios - 实例化 MPVolumeView 时,新的 OutputDeviceUID 为 nil msg
- java - 从文本文件中逐行读取并将每一行保存到数组中的不同单元格中
- r - R Knit Markdown 代码块:“找不到对象”
- alfresco - Activiti 通过组 id 获取用户
- c# - Active Directory 检索组中的组成员似乎陷入无限循环
- java - 如果我们可以使用构造函数设置所有值,为什么还要在 java 中使用 setter?
- python - 从 API 获取数据并对每年的 2 个值求和