【发布时间】:2018-02-17 03:25:46
【问题描述】:
我正在尝试使用包 genalg 解决 R 中的一个问题,特别是这个包,因为我需要一个可以理解的 GA 包。
问题是我必须在城市附近建立消防站,但我的目标是最少数量的救火车。它们之间的距离不得超过 15 分钟。数据表明每个城市彼此之间的时间。我对每个城市都做了限制,并在 excel 中运行了 IP,所以我知道答案应该是什么。我注释掉了这些约束,因为我不知道如何将它们与我用来存储在 GA 中求解的染色体的变量相关联。我还添加了一个惩罚项,以尝试使这些值符合约束条件。如果有人知道除了 CRAN 书之外的 genalg 的好教程,我将不胜感激。
代码如下:
#initilaize library
library(genalg)
#insert data
#set objective
#minimize the sume of x1,x2,x3,x4,x5,x6
datat = data.frame(city1 = c(0, 10, 20, 30, 30, 20),
city2 = c(10, 0, 25, 35, 15, 30),
city3 = c(20, 25, 0, 15, 30, 20),
city4 = c(30, 35, 15, 0, 15, 25),
city5 = c(30, 15, 30, 15, 0, 14),
city6 = c(20, 30, 20, 25, 14, 0))
coeff = c(0, 10, 15, 15, 14, 0)
#constraints
#add in a penalty to run function
#how?? relate x to the defined variables
# Failed applications 1 x as a list
#2 x as a variable equal to 6 variables
#3 use x indices instead (zero length?)
#4 changed the dot product to a variable > 0
#5
evalFun = function(x){
coefftot = x %*% coeff
# x1 + x2 + x3 + x4 + x5 + x6 >= 1
# x2 + x4 + x6 >= 2
# x3 + x4 >= 1
# x4 + x5 + x6 >= 2
# x2 + x4 + x5 + x6 >= 3
# x5 + x6 >= 1
# if (x5 + x6 < 1)
# #return(0)
# x[5] = 1
if (coefftot <= 0) {
return(0) else
return(coefftot)
}
}
#create function to create shortest path
lpiter = rbga.bin(size = 6,
popSize = 100,
iters = 100,
mutationChance = .01,
elitism = T,
evalFunc = evalFun)
【问题讨论】:
-
感谢您的建议,实际上我之前在处理背包问题时检查过它们。我发现解决方案是以向量的形式进行约束。不过感谢您的帮助。
标签: r optimization genetic-algorithm integer-programming