我正在尝试使用GA算法来计算客户端之间的最短距离,
下面是我的代码
file1<-read.xlsx("distance_matrix_v1.xlsx",sheetName = "Sheet1",header = T)
str(file1)
file1$Place<-as.character(file1$Place)
newdf<- file1 %>% column_to_rownames("Place")
str(newdf)
class(newdf)
D2 <- as.matrix(newdf)
D2
#Function to calculate tour length
tourLength <- function(tour, distMatrix) {
tour <- c(tour, tour[1])
route <- embed(tour, 2)[,2:1]
sum(distMatrix[route])
}
#Firness function to be maximized
tspFitness <- function(tour, ...) 1/tourLength(tour, ...)
GA <- ga(type = "permutation", fitness = tspFitness, distMatrix = D2,
min = 1, max = attr(newdf, "Size"), popSize = 50, maxiter = 5000,
run = 500, pmutation = 0.2)
summary(GA)
这是我的矩阵
> D2
A B C D E F G H I
A 0 10 2 2 8 1 17 8 6
B 10 0 8 8 1 7 9 2 2
C 2 8 0 1 11 2 17 8 7
D 2 8 1 0 9 8 17 8 8
E 8 1 11 9 0 4 10 1 2
F 1 7 2 8 4 0 12 4 3
G 17 9 17 17 10 12 0 9 10
H 8 2 8 8 1 4 9 0 2
I 6 2 7 8 2 3 10 2 0
此部分发生错误
GA <-ga(type =“ permutation”,fitness = tspFitness,distMatrix = D2, + min = 1,max = attr(newdf,“大小”),popSize = 50,maxiter = 5000, +运行= 500,突变= 0.2) seq.int(lower,upper)中的错误:“ to”的长度必须为1 另外:警告消息: 1:在ga(type =“ permutation”中,fitness = tspFitness,distMatrix = D2 ,: 不推荐使用“ min” arg。请改用“降低”。 2:在ga(type =“ permutation”中,fitness = tspFitness,distMatrix = D2 ,: “ max” arg已弃用。改用“上”。