如何在 R 中为 GA 构建变异算法

How to build a mutation algorithm for GA in R

我正在尝试为 GA 构建我的变异算法。

它应该是这样工作的:突变通过的概率为 Pm - 我们绘制两个基因 a 和 b。之后我们改变它们的顺序或这两者之间的顺序(如果它们不是邻居)。如果突变没有通过 - 我们什么都不做。

假设我们有一个后代 [010110],如果突变开始,我们选择指向 [0{1}01{1}0] 的 AB = [2,5]。我们做反向得到[011010].

我构建了这样的东西:

for(i in 1 : popSize){
  genomeMutId <- which(runif(2, Dim*cel)>pMut

   for(j in 1:length(genomeMutId)){
    drawn <- runif(1,genomeMutId[j],lenght(genomeMutId))
    iter <- 0
    for(k in genomeMutId[j]:drawn) {
      tmpValue <- nextGeneration[i, k]
      nextGeneration[i, k] = nextGeneration[i, drawn-iter]
      nextGeneration[i, drawn-iter] = tmpValue 
      iter <- iter + 1
    }
   }
}

很遗憾,它不能正常工作。有什么建议么?也许我使用示例而不是 runif?

你可以这样做:

offspring <- c(0,1,0,1,1,0,1,1,0,1)

# given an offspring vector (e.g. 0,1,0,0,1,0)
# choose 2 cut points AB and invert the values between them
getNewOffspring <- function(offspring){
  AB <- sort(sample.int(length(offspring),2))
  if(AB[2] - AB[1] > 2){
    subSqIdxs <- seq.int(from=AB[1]+1,to=AB[2]-1)
    offspring[subSqIdxs] <- rev(offspring[subSqIdxs])
  }
  offspring
}

用法示例:

getNewOffspring(c(0,1,0,1,1,0,1,1,0,1))
# e.g. with AB being 3,8
> 0 1 0 1 0 1 1 1 0 1

编辑:

假设后代列表存储在一个名为 offspringsList 的列表中,您可以为每个后代提取一个随机数来决定哪些后代必须变异,然后调用前面的函数:

offspringsToMutate <- which(runif(lenght(offspringsList)) > pM)

for(offspringIndex in seq_len(length(offspringsToMutate))){
   mutated <- getNewOffspring(offspringsList[[offspringIndex]])
   offspringsToMutate[[offspringIndex]] <- mutated
}
# now the list contains the mutated offsprings

我不得不为我的 GA 实现一个变异函数,它优化了风电场的布局。所有函数都导出了,大家可以看看:

library(windfarmGA)
## Create 4 random individuals with binary values
a <- cbind(bin=sample(c(0,1),20,replace=TRUE,prob = c(70,30)),
           bin.1=sample(c(0,1),20,replace=TRUE,prob = c(30,70)),
           bin.2=sample(c(0,1),20,replace=TRUE,prob = c(30,70)),
           bin.3=sample(c(0,1),20,replace=TRUE,prob = c(30,70)))

a

## Mutate the individuals with a low percentage
aMut <- mutation(a,0.1)
## Check which values are not like the originals
a==aMut

## Mutate the individuals with a high percentage
aMut <- mutation(a,0.4)
## Check which values are not like the originals
a==aMut

mutation

这并不完全是您想要的,但也许有助于实现目标。