age*_*nis 5 r missing-data r-caret imputation
我有一个数据集,我想建立一个模型,最好是caret包.我的数据实际上是一个时间序列,但问题不是特定于时间序列,而是我CreateTimeSlices为数据分区工作.
我的数据有一定数量的缺失值NA,我将它们分别caret编码为代码.我还记录了他们的位置:
# a logical vector same size as the data, which obs were imputed NA
imputed=c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE)
imputed[imputed] <- NA; print(imputed)
#### [1] FALSE FALSE FALSE NA FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
我知道Caret train函数中有一个选项可以排除NA或用不同的技术对它们进行估算.那不是我想要的.我需要在已经估算的数据集上构建模型,但我想从错误指标(RMSE,MAE,...)的计算中排除推算点.
我不知道如何在插入符号中这样做.在我的第一个脚本中,我尝试手动完成整个交叉验证,然后我有一个自定义的错误度量:
actual = c(5, 4, 3, 6, 7, 5)
predicted = c(4, 4, 3.5, 7, 6.8, 4)
Metrics::rmse(actual, predicted) # with all the points
#### [1] 0.7404953
sqrt(mean( (!imputed)*(actual-predicted)^2 , na.rm=T)) # excluding the imputed
#### [1] 0.676757
Run Code Online (Sandbox Code Playgroud)
我该如何处理这种做法caret?或者还有另一种方法可以避免手工编码吗?
我不知道您是否正在寻找这个,但这里有一个通过创建函数的简单解决方案:
i=which(imputed==F) ## As you have index for NA values
metric_na=function(fun, actual, predicted, index){
fun(actual[index], predicted[index])
}
metric_na(Metrics::rmse, actual, predicted, index = i)
0.676757
metric_na(Metrics::mae, actual, predicted, index = i)
0.54
Run Code Online (Sandbox Code Playgroud)
您也可以在计算所需指标时直接使用索引:
Metrics::rmse(actual[i], predicted[i])
Run Code Online (Sandbox Code Playgroud)