r - 如何在 R 中将 lapply 与 get.confusion_matrix() 一起使用?
问题描述
我正在使用 mixOmics 包在 R 中执行 PLS-DA 分析。我有一个二元 Y 变量(是否存在湿地)和 21 个连续预测变量 (X),其值范围为 1 到 100。我已经使用数据集制作了模型,data_training
并希望使用数据集预测新结果data_validation
。这些数据集具有完全相同的结构。
我的代码如下所示:
library(mixOmics)
model.plsda<-plsda(X,Y, ncomp = 10)
myPredictions <- predict(model.plsda, newdata = data_validation[,-1], dist = "max.dist")
我想根据 10、9、8、... 到 2 个主成分来预测结果。通过使用该get.confusion_matrix
函数,我想估计每个主成分数量的错误率。
prediction <- myPredictions$class$max.dist[,10] #prediction based on 10 components
confusion.mat = get.confusion_matrix(truth = data_validatie[,1], predicted = prediction)
get.BER(confusion.mat)
我可以单独做 10 次,但我想做得快一点。因此,我正在考虑prediction
为每个数量的组件制作一个列表...
library(BBmisc)
prediction_test <- myPredictions$class$max.dist
predictions_components <- convertColsToList(prediction_test, name.list = T, name.vector = T, factors.as.char = T)
...然后将 lapply 与get.confusion_matrix
andget.BER
函数一起使用。但后来我不知道该怎么做。我在互联网上搜索过,但找不到有效的解决方案。我怎样才能做到这一点?
非常感谢您的帮助!
解决方案
如果没有可重现性,则无法对此进行测试,但是您需要将每次要运行的代码转换为函数。像这样的东西:
confmat <- function(x) {
prediction <- myPredictions$class$max.dist[,x] #prediction based on 10 components
confusion.mat = get.confusion_matrix(truth = data_validatie[,1], predicted = prediction)
get.BER(confusion.mat)
}
现在申请:
results <- lapply(10:2, confmat)
这将返回一个列表,其中get.BER
包含每个 PC 数量的结果,因此 results[[1]] 将是 10 台 PC 的结果。除非prediction
它们confusionmat
包含在get.BER
. 如果您想要所有这些,则需要将函数的最后一行替换为return(list(prediction, confusionmat, get.BER(confusion.mat))
. 这将生成一个列表列表,这results[[1]][[1]]
将是prediction
10 台 PC的结果,results[[1]][[2]]
并且results[[1]][[3]]
将分别是confusionmat
和get.BER(confusion.mat)
。
推荐阅读
- php - 浏览 json 和计数值
- javascript - 使用 rxjs ReplaySubject 在两个组件之间共享数据的正确方法是什么?
- excel - excel日期格式MMYYYY
- oauth - 我收到了一封电子邮件,标题为:[需要采取行动] 使用受限 Gmail API 范围的项目的政策变更
- shell - 如果表计数为零或等于数字,是否存在退出配置单元的条件?
- c# - 如何使用 .NET AWS 开发工具包从 AWS S3 检索时过滤模式匹配文件?
- c++ - CMake - 使用 FetchContent 下载后如何构建 Boost?
- python - Flask 根据其他下拉菜单上的选择显示下拉菜单
- amazon-web-services - AWS CodeBuild 无法下载 gradle 包装器
- php - 如何在 php 中使用 shell_exec() 函数运行 ansible 命令