我找到this page from the R blog,其中有一个genalg
库如何工作的示例。
我已经写了一段代码,主要是从上面链接的页面复制粘贴的。我对代码的期望是,没有染色体是一个很好的解决方案,而且我一直想知道在理论上应该丢弃所有染色体时会发生什么。似乎算法始终能够返回一个解决方案,但哪个解决方案是一个不满足约束的解决方案?
我能想象的是,算法应该始终返回仅由零组成的染色体。我试图运行几次次,但它没有发生,即它也在染色体序列中返回。但是,这怎么可能呢?我错过了什么?对于一般的遗传算法和R的genalg
库,有没有人比我有更多的经验?
代码:
library("genalg");
evalFunc <- function(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);
}
}
dataset <- data.frame(item = c("pocketknife", "beans", "potatoes", "unions", "sleeping bag", "rope", "compass"),
survivalpoints = c(10, 20, 15, 2, 30, 10, 30),
weight = c(5, 10, 20, 5, 12, 10, 5));
#this is the constraint that cannot be satisfied
weightlimit <- 4;
GAmodel <- rbga.bin(size = 7, popSize = 200, iters = 100, mutationChance = 0.01, evalFunc = evalFunc);
filter <- GAmodel$evaluations == min(GAmodel$evaluations);
chromosome <- GAmodel$population[filter, , drop= FALSE][1,];
print("the solution is");print(chromosome);