DEAP:按适应度对个体进行分类
DEAP: sorting individuals by fitness
在评估了每个个体的适应性后,按个体适应性对种群进行排序的最佳方法是什么?
我手动实现了排序功能,但也许有内置方法可以做到这一点?
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)
可以简单地使用 Python 内置函数
pop.sort(key=lambda x: x.fitness, reverse=True)
这会根据个人的健康状况对现有人口进行排序。
在评估了每个个体的适应性后,按个体适应性对种群进行排序的最佳方法是什么?
我手动实现了排序功能,但也许有内置方法可以做到这一点?
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)
可以简单地使用 Python 内置函数
pop.sort(key=lambda x: x.fitness, reverse=True)
这会根据个人的健康状况对现有人口进行排序。