使用caret时horizon=1出现‘重采样性能指标缺失值’警告的原因
时间序列重采样中
horizon=1导致性能指标异常的问题解析 问题背景
使用caret的时间序列滚动重采样代码时,当trainControl中的horizon设为1,会出现性能指标缺失的警告,且结果中Rsquared为NaN;而horizon>1时一切正常。示例代码及异常结果如下:
示例代码:
library(caret) library(ggplot2) data(economics) myTimeControl <- trainControl(method = "timeslice", initialWindow = 36, horizon = 1, # 设为1触发问题 fixedWindow = TRUE) plsFitTime <- train(unemploy ~ pce + pop + psavert, data = economics, method = "pls", preProc = c("center", "scale"), trControl = myTimeControl)
触发的警告:
Warning message: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo, : There were missing values in resampled performance measures.
异常的模型结果:
Partial Least Squares 574 samples 3 predictor Pre-processing: centered (3), scaled (3) Resampling: Rolling Forecasting Origin Resampling (1 held-out with a fixed window) Summary of sample sizes: 36, 36, 36, 36, 36, 36, ... Resampling results across tuning parameters: ncomp RMSE Rsquared MAE 1 650.8681 NaN 650.8681 2 557.8639 NaN 557.8639 RMSE was used to select the optimal model using the smallest value. The final value used for the model was ncomp = 2.
警告含义
这条警告说明在时间序列滚动重采样的每一轮验证中,部分轮次的性能指标计算出现了缺失值,最终汇总结果时就表现为Rsquared字段显示NaN。
产生原因
核心原因是单样本无法计算决定系数(Rsquared):
- Rsquared的计算逻辑基于真实值与预测值的方差对比,公式中需要用到真实值的总体方差。当
horizon=1时,每一轮验证集只有1个样本,真实值的方差为0(单样本没有波动),导致计算时出现除以0的情况,结果为NaN。 - 当
horizon>1时,验证集有多个样本,真实值存在方差,Rsquared可以正常计算,因此不会触发警告。 - 该现象与模型类型无关,测试的
ranger、lm、svmRadial等模型都会出现同样问题,本质是Rsquared的计算限制导致的。
应对思路
- 如果必须使用
horizon=1的重采样方式,可以忽略Rsquared指标,仅参考RMSE、MAE这类不受单样本限制的性能指标(这两个指标在单样本下仍能正常计算)。 - 也可以自定义性能评估函数,通过
trainControl的summaryFunction参数传入,修改Rsquared的计算逻辑以兼容单样本场景(比如单样本时直接返回0或1,或者跳过该指标计算)。
内容的提问来源于stack exchange,提问作者YCao0920
相关产品推荐
相关产品推荐

