【问题标题】:R "Error in terms.formula" using GA/genalg library使用 GA/genalg 库的 R“terms.formula 错误”
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 2013-04-04
      • 1970-01-01
      相关资源
      最近更新 更多