R-mlr:重采样时如何向predict传递额外参数?
在mlr重采样中传递predict额外参数的最优方案
当然有更省心的方案啦!不用每次手动提取模型和测试数据重复操作,咱们可以通过自定义学习器的预测函数来直接把额外参数传递给底层的predict.coxph,这样重采样过程中每一轮的预测都会自动带上你需要的参数。
具体操作步骤如下:
创建基础的coxph学习器
先初始化mlr里的生存分析coxph学习器:library(mlr) lrn <- makeLearner("surv.coxph")自定义预测函数
写一个覆盖默认逻辑的预测函数,在调用底层predict.coxph时加入reference参数(你可以根据需求修改参数值):custom_predict_coxph <- function(model, newdata, ...) { # 调用原始的predict.coxph,添加你需要的reference参数 pred <- predict(model$learner.model, newdata = newdata, reference = "your_target_reference", ...) # 把结果转换成mlr要求的预测对象格式 makePrediction( task.desc = model$task.desc, predict.type = model$predict.type, data = list(response = pred), row.names = rownames(newdata), id = model$id ) }绑定自定义预测函数到学习器
使用setPredictFun把上面的自定义函数替换掉学习器默认的预测逻辑:lrn_custom <- setPredictFun(lrn, custom_predict_coxph)用修改后的学习器执行重采样
现在直接用这个自定义学习器跑重采样就可以了,每一轮预测都会自动带上reference参数:# 假设你已经有了对应的任务对象task和重采样策略resampling res <- resample(lrn_custom, task, resampling)
如果需要动态调整reference参数(比如不同重采样迭代用不同值),还可以把参数存在学习器的par.vals里,然后在自定义预测函数中读取:
# 先给学习器设置参数 lrn <- setHyperPars(lrn, reference = "initial_ref") # 修改自定义预测函数 custom_predict_coxph <- function(model, newdata, ...) { ref_val <- model$learner$par.vals$reference pred <- predict(model$learner.model, newdata = newdata, reference = ref_val, ...) makePrediction(...) # 同上格式转换逻辑 }
这样后续如果需要修改参数,只需要更新学习器的par.vals就行,不用改预测函数的代码。
内容的提问来源于stack exchange,提问作者complexM
相关产品推荐
相关产品推荐

