首页 > 解决方案 > 如何在 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_matrixandget.BER函数一起使用。但后来我不知道该怎么做。我在互联网上搜索过,但找不到有效的解决方案。我怎样才能做到这一点?

非常感谢您的帮助!

标签: rlistlapplyconfusion-matrixpls

解决方案


如果没有可重现性,则无法对此进行测试,但是您需要将每次要运行的代码转换为函数。像这样的东西:

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]]将是prediction10 台 PC的结果,results[[1]][[2]]并且results[[1]][[3]]将分别是confusionmatget.BER(confusion.mat)


推荐阅读