我正在尝试在R中实现遗传算法。我发现r具有遗传算法实现的'GA'和'genalg'包。我在链接http://www.r-bloggers.com/genetic-algorithms-a-simple-r-example/中遇到了示例。他们试图解决背包问题。问题可以简单解释为: “你将在旷野度过一个月。你带着背包,但是,它可以携带的最大重量是20公斤。你有许多生存物品,每个都有自己的生存数量积分'。你的目标是最大化生存点数“
对于单个人使用'genalg'包很容易解决问题,输出是二进制字符串。现在我有一个疑问,让我们说一个人而不是一个人有两个或更多人,我们需要分配生存点。重量限制适用于每个人。那我们怎么解决这个问题呢?我们可以使用'genalg'或'GA'套餐吗?如果是这样,我们如何应用它们?有没有在R或其他软件中解决的例子?
由于
答案 0 :(得分:1)
R包adagio(https://cran.r-project.org/web/packages/adagio/index.html)带有两个函数(背包和mackapsack),通过动态编程可以更有效地解决这类问题。
答案 1 :(得分:0)
一种简单的方法可能是让一条染色体含有该组中的所有个体并且具有评估功能将该染色体分成多个部分,每个个体一个,然后评估这些部分。在下面的示例中(基于问题中的示例)我假设每个人都有相同的权重限制,并且多个人可以带来相同的项目。
library(genalg)
#Set up the problem parameters
#how many people in the group
individual_count <-3
#The weight limit for one individual
weightlimit <- 20
#The items with their 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(1, 5, 10, 1, 7, 5, 1))
#Next, we choose the number of iterations, design and run the model.
iter <- 100
#Our chromosome has to be large enough to contain a bit for all individuals and for all items in the dataset
chromosomesize <- individual_count * nrow(dataset)
#Function definitions
#A function to split vector X in N equal parts
split_vector <- function(x,n) split(x, cut(seq_along(x), n, labels = FALSE))
#EValuate an individual (a part of the chromosome)
evalIndividual <- 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)
}
#Evaluate a chromosome
evalFunc <- function(x) {
#First split the chromosome in a list of individuals, then we can evaluate all individuals
individuals<-split_vector(x,individual_count)
#now we need to sapply the evalIndividual function to each element of individuals
return(sum(sapply(individuals,evalIndividual)))
}
#Run the Genetic Algorithm
GAmodel <- rbga.bin(size = chromosomesize, popSize = 200, iters = iter, mutationChance = 0.01,
elitism = T, evalFunc = evalFunc)
#First show a summary
summary(GAmodel,echo=TRUE)
#Then extract the best solution from the GAmodel, copy/paste from the source code of the summary function
filter = GAmodel$evaluations == min(GAmodel$evaluations)
bestSolution = GAmodel$population[filter, , drop= FALSE][1,]
#Now split the solution in the individuals.
split_vector(bestSolution,individual_count)