defselect(self): """ 轮盘赌选择 :return: """ # calculate fitness function sum_f = 0 for i in range(self.pop_size): self.pop[i].func()
# guarantee fitness > 0 min = self.pop[0].y for i in range(self.pop_size): if self.pop[i].y < min: min = self.pop[i].y if min < 0: for i in range(self.pop_size): self.pop[i].y = self.pop[i].y + (-1) * min
# roulette for i in range(self.pop_size): sum_f += self.pop[i].y p = [0] * self.pop_size for i in range(self.pop_size): p[i] = self.pop[i].y / sum_f q = [0] * self.pop_size q[0] = 0 for i in range(self.pop_size): s = 0 for j in range(0, i+1): s += p[j] q[i] = s # start roulette v = [] for i in range(self.pop_size): r = random.random() if r < q[0]: v.append(self.pop[0]) for j in range(1, self.pop_size): if q[j - 1] < r <= q[j]: v.append(self.pop[j]) self.pop = v
变异
这里的变异,我们先以变异概率,从种群中选一个,然后对选中的个体,随机选一个变异位点进行变异。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
defmutation(self): """ 变异 :return: """ for i in range(self.pop_size): if self.pm > random.random(): pop = self.pop[i] # select mutation index index1 = random.randint(0, pop.code_x1_length-1) index2 = random.randint(0, pop.code_x2_length-1)
i = pop.code_x1[index1] i = self.__inverse(i) pop.code_x1 = pop.code_x1[:index1] + i + pop.code_x1[index1+1:]
i = pop.code_x2[index2] i = self.__inverse(i) pop.code_x2 = pop.code_x2[:index2] + i + pop.code_x2[index2+1:]