为什么实际的世代数与 R 中的遗传算法不一样

Why is the actual number of generation not as specified for genetic algorithms in R

我正在使用 R 的 genalg 库,并在我 运行 二进制通用算法时尝试保存所有代。库中似乎没有内置方法,所以我的尝试是通过评估函数保存每条染色体,x

为了测试这个方法,我尝试在评估函数中插入 print(x) 以便能够看到所有评估的染色体。然而,打印的染色体数量并不总是与我怀疑的相符。

我原以为打印的染色体数会等于迭代次数乘以种群规模,但似乎并不是一直在尝试。

问题是我想知道每条染色体属于哪一代(或迭代),我无法判断染色体的数量是否不同于iterpopSize

这是什么原因,我该如何"fix"呢。还是有另一种方法来保存每条染色体及其所属的迭代?

下面是一个例子,我认为评估函数会打印 2x5 条染色体,但只打印 8 条。

library(genalg)
library(ggplot2)

dataset <- data.frame(
    item = c("pocketknife", "beans", "potatoes", "unions", "sleeping bag", "rope", "compass"),
    survivalpoints = c(10, 20, 15, 2, 30, 10, 30),
    weight = c(1, 5, 10, 1, 7, 5, 1))

weightlimit <- 20

evalFunc <- function(x) {

    print(x)

    current_solution_survivalpoints <- x %*% dataset$survivalpoints
    current_solution_weight <- x %*% dataset$weight

    if (current_solution_weight > weightlimit)
        return(0) else return(-current_solution_survivalpoints
}


iter = 2
popSize = 5
set.seed(1)
GAmodel <- rbga.bin(size = 7, popSize = popSize, iters = iter, mutationChance = 0.1,elitism = T, evalFunc = evalFunc)

查看函数代码,似乎在每次迭代(生成)中,以一定的概率(0.1 在你的情况下)并发生了变异。评估函数只在每一代被变异的染色体调用(当然第一次迭代的所有染色体都知道它们的初始值)。

请注意,此子集不包括精英组,在您的示例中您将其定义为 1 元素大(您错误地传递了 elitism=TRUE 并且 TRUE 隐式转换为 1).

无论如何,要知道每一代的种群,你可以通过monitorFun参数传递一个监控函数,例如:

# obj contains a lot of informations, try to print it
monitor <- function(obj) {
  print(paste(" GENERATION :", obj$iter))
  print("POPULATION:")
  print(obj$population)
  print("VALUES:")
  print(obj$evaluations)
}

iter = 2
popSize = 5
set.seed(1)
GAmodel <- rbga.bin(size = 7, popSize = popSize, 
                    iters = iter, mutationChance = 0.1,
                    elitism = 1, evalFunc = evalFunc, monitorFunc = monitor)