【发布时间】:2017-03-09 02:38:15
【问题描述】:
我正在尝试创建一种遗传算法(对库不挑剔,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" 其中 (string == 1) 是 GA 应该能够处理的,所以我不知道 GA 是什么我的功能的问题是。
关于编写此代码以使 ga 或 genalg 接受该功能的任何想法?
【问题讨论】:
标签: r linear-regression genetic-algorithm