繁体   English   中英

R使用GA / genalg库的“ terms.formula错误”

[英]R “Error in terms.formula” using GA/genalg library

我正在尝试创建一种遗传算法(不要挑剔库,ga和genalg会产生相同的错误),以通过最小化-adj来识别用于线性回归模型的潜在列。 R ^ 2。 使用mtcars作为播放器,尝试在mpg上回归。

我具有以下健身功能:

mtcarsnompg <- mtcars[,2:ncol(mtcars)]

evalFunc <- function(string) {
  costfunc <- summary(lm(mtcars$mpg ~ ., data = mtcarsnompg[, which(string == 1)]))$adj.r.squared
  return(-costfunc)
}

ga("binary",fitness = evalFunc, nBits = ncol(mtcarsnompg), popSize = 100, maxiter = 100, seed = 1, monitor = FALSE)

这导致:

 Error in terms.formula(formula, data = data) : 
  '.' in formula and no 'data' argument 

研究此错误后,我决定可以采用以下方法解决此问题:

evalFunc = function(string) {
  child <- mtcarsnompg[, which(string == 1)]
  costfunc <- summary(lm(as.formula(paste("mtcars$mpg ~", paste(child, collapse = "+"))), data = mtcars))$adj.r.squared
  return(-costfunc)
}

ga("binary",fitness = evalFunc, nBits = ncol(mtcarsnompg), popSize = 100, maxiter = 100, seed = 1, monitor = FALSE)

但这导致:

 Error in terms.formula(formula, data = data) : 
  invalid model formula in ExtractVars 

我知道它应该工作,因为我可以用任何一种方式手写评估函数,而无需使用ga:

solution <- c("1","1","1","0","1","0","1","1","1","0")

evalFunc(solution)
[1] -0.8172511

我还在“ GA快速浏览”( https://cran.r-project.org/web/packages/GA/vignettes/GA.html )中发现,使用“字符串”,其中(string == 1) GA应该能够处理的事情,所以我不知道GA的功能有什么问题。

有什么想法写这个来让ga或genalg接受该功能吗?

事实证明,我不认为0的解决方案字符串(或者实际上是一个带1的0s字符串)会导致内部粘贴读取“ mpg〜”,这不可能进行线性回归。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM