【问题标题】:Trying to run GA in R, getting Error in if (any(x < 0)) { : missing value where TRUE/FALSE needed尝试在 R 中运行 GA,在 if (any(x < 0)) { 中出现错误:需要 TRUE/FALSE 的缺失值
【发布时间】:2023-03-12 07:05:02
【问题描述】:

我对 R 比较陌生,需要建立一个遗传算法来找到一个能产生一定数量素数的方程。

install.packages("GA")
install.packages("matlab")
library(GA)
library(matlab)

f <- function(x)
{
  #initialize fitness score
  score <- 0 
  #set test values for k
  k <- seq(from = 1, to = 100,by = 1)
  #test if the result of the formula (k^2 + ak + b) is a prime number using test k values
  for (i in k) {
    if (isprime(i ^ 2 + x[1] * i + x[2]) == 2) {
    score = score + 1
    }
  }
  #return fitness score
  return(score)
}

lbound <- 2
ubound <- 1000

GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)

当我尝试运行 GA 部分时,我收到以下错误:

> GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)

 Error in if (any(x < 0)) { : missing value where TRUE/FALSE needed 

对我可能做错的任何建议?

谢谢

【问题讨论】:

    标签: r genetic-algorithm


    【解决方案1】:

    代码中的错误是因为它试图在 x[2] 不存在时查找它。

    如果您阅读了 GA 函数的 Rastrigin 示例小插图,对于 2 个值,您需要 1. 指定具有 2 个输入的函数和 2. 在此函数上使用包装器

    f <- function(x1,x2)
    # two variables
    {
      #initialize fitness score
      score <- 0 
      #set test values for k
      k <- seq(from = 1, to = 100,by = 1)
      #test if the result of the formula (k^2 + ak + b) is a prime number using test k values
      for (i in k) {
        if (isprime(i ^ 2 + x1 * i + x2) == 2) {
        score = score + 1
        }
      }
      #return fitness score
      return(score)
    }
    
    lbound <- 2
    ubound <- 1000
    
    GA <- ga(type="real-valued",
    #the wrapper is here
    fitness=function(x)f(round(x[1]),round(x[2])),
    popSize = 10,
    pcrossover = 0.8,pmutation = 0.1, maxiter=30, 
    run=20, lower = rep(lbound,2), upper = rep(ubound,2))
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多