从mlr3拟合的regr.nnet对象提取权重及相关评估问题
mlr3中regr.nnet模型训练后的常见问题解答
1. 从benchmark对象便捷提取regr.rmse等评估指标
可以通过mlr3内置方法直接提取指定指标:
- 提取所有重采样的聚合指标(如RMSE):
# 提取单个指标 rmse_agg <- benchmark$aggregate(msr("regr.rmse")) # 同时提取多个指标(如RMSE、MAE) multi_metrics <- benchmark$aggregate(c(msr("regr.rmse"), msr("regr.mae")))
- 查看每个重采样折叠的具体指标结果:
fold_scores <- benchmark$score() # 筛选RMSE列 fold_rmse <- fold_scores[, .(iteration, regr.rmse)]
2. 优化预测结果提取代码
best$predictions()[[1]]返回的是PredictionRegr对象,自带$response属性,无需先转data.table:
# 直接提取单折叠的预测响应值 pr <- best$predictions()[[1]]$response # 合并所有折叠的预测结果 pr_all <- unlist(lapply(best$predictions(), function(pred) pred$response))
若后续需要表格化处理,再转换为data.table即可,避免不必要的类型转换开销。
3. 提取nnet模型原始权重用于离线部署
mlr3训练后的学习器会将原始nnet模型存在$model字段中,直接访问即可提取权重:
# 获取训练好的原始nnet模型 trained_nnet <- best$model # 提取权重向量 nnet_weights <- trained_nnet$wts # (可选)拆分权重为输入层→隐藏层、隐藏层→输出层的结构 input_features_count <- length(trained_nnet$coefnames) hidden_nodes_count <- trained_nnet$n # 输入层到隐藏层的权重矩阵 input_hidden_weights <- matrix( nnet_weights[1:(input_features_count * hidden_nodes_count)], nrow = input_features_count, ncol = hidden_nodes_count ) # 隐藏层到输出层的权重向量 hidden_output_weights <- nnet_weights[(input_features_count * hidden_nodes_count + 1):length(nnet_weights)]
提取后的权重可保存为CSV、JSON等格式,直接在R环境外的平台加载使用。
内容的提问来源于stack exchange,提问作者tpetzoldt
相关产品推荐
相关产品推荐

