r - 尝试在 R 中运行 GA,在 if (any(x < 0)) { 中出现错误:需要 TRUE/FALSE 的缺失值
问题描述
我对 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
关于我可能做错的任何建议?
谢谢
解决方案
发生代码中的错误是因为它在 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))
推荐阅读
- typescript - 来自同一碱基的亚型之间的区别
- algorithm - 可以根据这些变量的特定总和的结果计算变量值的算法
- apache-spark - Spark:无法从填充另一列空值的输出中创建新列
- excel - 在一个表中查找一个值,从同一行复制不同列中的数据,然后粘贴到另一个表中
- php - 通过 PHAR 在 Windows 上安装的 PHPUnit 8 显示没有执行测试
- matlab - 呈现函数值随三个参数变化,一个数字
- python - XArray:向 NetCDF 添加数据“层”
- python - 为什么我的新列在使用 .sample 方法后会被分配净值?
- objective-c - 针对 Objective-C 枚举的新 Swift 5 警告:如何摆脱它们?
- android - RelativeLayout 填充剩余空间