DAY 24
0
AI & Data

## 【Day24】GA with you - R 基因演算法應用於旅行銷售員問題 (2)

(其實只有引入套件和設定path cost而已)

### 路徑成本

``````# fitness vector
A<-c(-1,25,25,10,35)
B<-c(25,-1,25,35,25)
C<-c(25,25,-1,30,15)
D<-c(10,35,30,-1,20)
E<-c(35,25,15,20,-1)
city<-rbind(A,B,C,D,E)
colnames(city)<-c('A','B','C','D','E')
``````

### 適應函數

1. 計算旅程的長度
`tourLength`用來求解整個旅程的長度
``````tourLength <- function(tour, distMatrix) {
tour <- c(tour, tour[1])
route <- embed(tour, 2)[, 2:1]
sum(route)
}
``````
1. 計算成本
將剛剛`tourLength`的總和用倒數呈現
``````tspfitness  <- function(tour, ...) 1/tourLength(tour, ...)
``````

### 執行GA

`執行迭代數(run):`100

``````GA.fit <- ga(type = "permutation",
fitness = tspfitness,
distMatrix = data,
lower  = 1,
upper = 5,
popSize = 100,
maxiter = 20,
run = 10,
pmutation = 0.05,
monitor = NULL)

``````

### 結果

`GA.fit@solution`結果

``````> GA.fit@solution
x1 x2 x3 x4 x5
[1,]  4  3  1  5  2
[2,]  5  3  2  4  1
[3,]  4  5  1  3  2
[4,]  5  3  1  4  2
[5,]  2  5  1  4  3
[6,]  1  3  2  4  5
``````

``````summary(GA.fit)
``````