def getNewChild(self): logging.debug('select 2 parent lives') parent1 = self.selection() parent2 = self.selection() while self.hammingDist(parent1._gene, parent2._gene) == 0: parent2 = self.selection() pass variableCount = len(self._boundaryList) encodeLength = int(self._geneLength / variableCount) # logging.debug('parent1: \n%s' % self.decodedOneGene(parent1._gene)) # logging.debug('parent2: \n%s' % parent1._gene.reshape((variableCount, encodeLength))) # logging.debug('parent2: \n%s' % self.decodedOneGene(parent2._gene)) # logging.debug('parent2: \n%s' % parent2._gene.reshape((variableCount, encodeLength))) logging.debug( 'hamming distance between parent1 and parent2: %d' % self.hammingDist(parent1._gene, parent2._gene)) # 按概率交叉 rate = random.random() if rate < self._crossoverRate: logging.debug('crossover') # 交叉 gene1, gene2 = self.crossover(parent1, parent2) logging.debug( 'hamming distance between gene1 and gene2 after crossover: %d' % self.hammingDist(gene1, gene2)) else: gene1, gene2 = parent1._gene, parent2._gene # 按概率突变 rate = random.random() if rate < self._mutationRate: logging.debug('mutation') gene1, gene2 = self.mutation(gene1), self.mutation(gene2) logging.debug( 'hamming distance between gene1 and gene2 after mutation: %d' % self.hammingDist(gene1, gene2)) # 计算子代适应度 life1 = Life(gene1) life2 = Life(gene2) life1._fitness = self._fitnessClass.fitnessFunc(self.decodedOneGene(gene1)) life2._fitness = self._fitnessClass.fitnessFunc(self.decodedOneGene(gene2)) return life1, life2
def initPopulation(self): logging.debug('init population') self._population = [] if self._binaryEncode: # 将变量进行二进制编码 if self._boundaryList is None: raise ValueError("boundaryList must be configured!") # 获取编码长度列表 self._encodeLengths = self.getEncodedLengths() # 基因长度为每个变量编码长度之和 self._geneLength = np.sum(self._encodeLengths) # 随机化初始种群为0 for i in range(self._populationSize): # 随机生成基因 gene = np.random.randint(0, 2, self._geneLength) # 生成个体,并计算适应度 life = Life(gene) life._fitness = self._fitnessClass.fitnessFunc(self.decodedOneGene(gene)) # 把生成个体添加至种群集合里 self._population.append(life) else: # 编码方式为[0, 1, 2, ..., self._geneLength-1] if self._geneLength is None: raise ValueError("geneLength must be configured!") for i in range(self._populationSize): gene = np.array(range(self._geneLength)) # 将基因乱序 random.shuffle(gene) # 生成个体,并计算适应度 life = Life(gene) life._fitness = self._fitnessClass.fitnessFunc(gene) # 把生成个体添加至种群集合里 self._population.append(life) # 根据适应度值对种群的个体降序排列,并记录最佳个体和最佳适应度 self._population = self.sortPopulation(self._population) self._bestLife = self._population[0] self._bestFitnessHistory.append(self._bestLife._fitness) # 计算总适应度 self._totalFitness = self.calTotalFitness(self._population) self._totalFitnessHistory.append(self._totalFitness)