在评估了每个人的适应度之后,按个体适应度对总体进行分类的最佳方法是什么?
我手动实现了排序功能,但是也许有内置的方法可以做到这一点?
import random
from deap import base, tools, creator, algorithms
def sort(population):
for i in range(len(population)):
argmin = i
minimum = population[i].fitness
for j in range(i + 1, len(population)):
if population[j].fitness < minimum:
argmin = j
population[argmin], population[i] = population[i], population[argmin]
return population
def fitness(individual):
return sum(individual),
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox.register("individual", tools.initRepeat, creator.Individual, random.random, n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
pop = toolbox.population(n=10)
fitnesses = toolbox.map(toolbox.evaluate, pop)
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
print("Before")
for ind in pop:
print(ind, ind.fitness)
pop = sort(pop)
print("After")
for ind in pop:
print(ind, ind.fitness)
答案 0 :(得分:0)
可以简单地使用Python内置函数
pop.sort(key=lambda x: x.fitness, reverse=True)
这会根据个人的健康状况将人口分类。