def createPopulation(self, functions, constants, n_ind, n_gene, n_register): self.p = [] for i in range(n_ind): ind = Individual(functions, constants, n_register) ind.createGene(random.randint(1, n_gene)) self.p.append(ind)
def revolution(self, args): #config if (args.crossmode == "one"): cross_func = Crossover.onePoint elif (args.crossmode == "two"): cross_func = Crossover.twoPoints else: cross_func = Crossover.randomPoints # Prepare dataset dataset = readDataset(args.dpath) # Create individuals & population ppl = Population() for i in range(args.individuals): individual = Individual() individual.createGene(dataset, args.gene) ppl.addInd(individual) # Evolution for i in range(args.revolution): # Evaluation population in individuals ppl.calcFitness(self.evaluate) if ((i % 10) == 0): ppl.show() # Select parents if (args.elite): parents = Select.Elite(ppl, args.esize, args.mode) parents.extend( Select.Tournament(ppl, args.individuals - args.esize, args.tornsize, args.mode)) else: parents = Select.Tournament(ppl, args.individuals, args.tornsize, args.mode) # Clossover children = cross_func(parents, args.individuals, args.gene, args.crossrate) # Mutation children = Mutation.mutation(children, args.mutaterate, dataset) # Swap children ppl.setPpl(children) # show result ppl.calcFitness(self.evaluate) ppl.show()
for ind in self.ppl: individual = ind.getGene() ind.setFitness(func(individual, args)) def show(self): """ This population show infomation """ print("Population Class") print("\tpopulation is ", self.ppl) ppl = sorted(self.ppl, key=lambda x: x.fit, reverse=True) for ind in ppl: ind.show() if __name__ == "__main__": from readDataset import readDataset dataset = readDataset("./dataset/binary.txt") population = Population() for i in range(5): ind = Individual() ind.createGene(dataset, 10) population.addInd(ind) def evaluate(ind): fitness = sum(ind) return (fitness) population.calcFitness(evaluate) population.show()