[英]R “Error in terms.formula” using GA/genalg library
I'm attempting to create a genetic algorithm (not picky about library, ga and genalg produce same errors) to identify potential columns for use in a linear regression model, by minimizing -adj. 我正在尝试创建一种遗传算法(不要挑剔库,ga和genalg会产生相同的错误),以通过最小化-adj来识别用于线性回归模型的潜在列。 r^2.
R ^ 2。 Using mtcars as a play-set, trying to regress on mpg.
使用mtcars作为播放器,尝试在mpg上回归。
I have the following fitness function: 我具有以下健身功能:
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)
this causes: 这导致:
Error in terms.formula(formula, data = data) :
'.' in formula and no 'data' argument
Researching this error, I decided I could work around it this way: 研究此错误后,我决定可以采用以下方法解决此问题:
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)
but this results in: 但这导致:
Error in terms.formula(formula, data = data) :
invalid model formula in ExtractVars
I know it should work, because I can evaluate the function by hand written either way, while not using ga: 我知道它应该工作,因为我可以用任何一种方式手写评估函数,而无需使用ga:
solution <- c("1","1","1","0","1","0","1","1","1","0")
evalFunc(solution)
[1] -0.8172511
I also found in "A quick tour of GA" ( https://cran.r-project.org/web/packages/GA/vignettes/GA.html ) that using "string" in which(string == 1) is something the GA ought to be able to handle, so I have no idea what GA's issue with my function is. 我还在“ GA快速浏览”( https://cran.r-project.org/web/packages/GA/vignettes/GA.html )中发现,使用“字符串”,其中(string == 1) GA应该能够处理的事情,所以我不知道GA的功能有什么问题。
Any thoughts on a way to write this to get ga or genalg to accept the function? 有什么想法写这个来让ga或genalg接受该功能吗?
事实证明,我不认为0的解决方案字符串(或者实际上是一个带1的0s字符串)会导致内部粘贴读取“ mpg〜”,这不可能进行线性回归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.