如何将函数应用于许多ML模型并保存其输出?

时间:2019-04-26 15:39:47

标签: r

我有很多预测模型。

我写了一个可以预测准确性的函数。

如何编写另一个函数,将所有结果保存到一个向量中?

例如(仅出于说明目的)



library(randomForest)
url="http://freakonometrics.free.fr/german_credit.csv"
credit=read.csv(url, header = TRUE, sep = ",")
credit$Creditability <- as.factor(credit$Creditability)

#2 models
Random1 <- randomForest(Creditability ~ Credit.Amount +Duration.of.Credit..month., data = credit, mtry = 1)
Random2 <- randomForest(Creditability ~ Credit.Amount +Duration.of.Credit..month., data = credit, mtry = 2)

##Accuracy function 
Accuracy <- function(model){
pred <-predict(model,type ="class",newdata = credit)
tab <-table(credit$Creditability, pred)
Ac <- sum(diag(tab))/(sum(tab))
Ac}

Accuracy(Random1)
Accuracy(Random2)

如果我已保存使用的模型

Models <- c(Random1, Random2)

然后如何将精度函数应用于此并将输出另存为矢量?

我尝试

lapply(Models, Accuracy)

但出现错误

Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "call"

谢谢!

0 个答案:

没有答案