本文整理汇总了Python中individual.Individual.calculate_fitness方法的典型用法代码示例。如果您正苦于以下问题:Python Individual.calculate_fitness方法的具体用法?Python Individual.calculate_fitness怎么用?Python Individual.calculate_fitness使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类individual.Individual
的用法示例。
在下文中一共展示了Individual.calculate_fitness方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: evolve
# 需要导入模块: from individual import Individual [as 别名]
# 或者: from individual.Individual import calculate_fitness [as 别名]
def evolve(G, p, popsize, gener, mutprob, coprob, tsize, elitism=None):
nodes_ordered_by_demand = sorted(G.node.items(),
key=lambda t: t[1]['demand'],
reverse=True)
t1 = clock()
pop = []
# generating first population, which will be random
for i in range(popsize):
individual = Individual(p, G)
individual.calculate_fitness(G, nodes_ordered_by_demand)
pop.append(individual)
rank_population(pop)
report = {
'worst_i': pop[-1].fitness,
'best_i': pop[0].fitness,
'generation': 0,
'better_sons': 0,
'total_sons': 0,
'best_i_hist': [pop[0].fitness],
'mean_fitness_hist': [sum([i.fitness for i in pop]) / popsize],
'repeated_i_hist': [popsize - unique_individuals(pop)]
}
for generation in range(gener):
# applying elitism if relevant
if elitism:
topelite = int(ceil(elitism * popsize))
new_pop = pop[0:topelite]
else: # if no elitism specified, simply create a new population
new_pop = []
# while the population is not complete
while len(new_pop) < popsize:
random_number = random()
subpop = sample(pop, tsize) # tournament individuals
if random_number < mutprob: # mutating
new_pop.append(mutate(subpop[0], G))
new_pop[-1].calculate_fitness(G, nodes_ordered_by_demand)
elif random_number < coprob: # doing crossover
mean_fitness = (subpop[0].fitness + subpop[1].fitness) / 2.0
i1, i2 = crossover(subpop[0], subpop[1])
i1.calculate_fitness(G, nodes_ordered_by_demand)
if i1.fitness > mean_fitness:
report['better_sons'] += 1
report['total_sons'] += 1
new_pop.append(i1)
if i2 is not None:
i2.calculate_fitness(G, nodes_ordered_by_demand)
if i2.fitness > mean_fitness:
report['better_sons'] += 1
new_pop.append(i2)
report['total_sons'] += 1
else: # if no mutation or crossover, insert the best individual
new_pop.append(deepcopy(subpop[0]))
if len(new_pop) > popsize:
new_pop.pop()
report['total_sons'] -= 1
pop = rank_population(new_pop)
report['best_i_hist'].append(pop[0].fitness)
report['mean_fitness_hist'].append(sum([i.fitness for i in pop]) /
popsize)
report['repeated_i_hist'].append(popsize - unique_individuals(pop))
if report['best_i'] > pop[0].fitness:
report['best_i'] = pop[0].fitness
report['generation'] = generation
if report['worst_i'] < pop[-1].fitness:
report['worst_i'] = pop[-1].fitness
t2 = clock()
report['time'] = round(t2 - t1, 3)
report['gener_per_s'] = gener / report['time']
return report