Python遗传算法工具箱DEAP框架分析

时间:2024-08-31 17:34:50

  本文主要介绍python遗传算法工具箱DEAP的实现。先介绍deap的如何使用,再深入介绍deap的框架实现,以及遗传算法的各种实现算法。

  代码可以参考 https://github.com/sumatrae/deap

  下面是使用deap求解TSP的实现:

 import array
import random
import json import numpy from deap import algorithms
from deap import base
from deap import creator
from deap import tools # gr*.json contains the distance map in list of list style in JSON format
# Optimal solutions are : gr17 = 2085, gr24 = 1272, gr120 = 6942
with open("tsp/gr17.json", "r") as tsp_data:
tsp = json.load(tsp_data) distance_map = tsp["DistanceMatrix"]
IND_SIZE = tsp["TourSize"] creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", array.array, typecode='i', fitness=creator.FitnessMin) toolbox = base.Toolbox() # Attribute generator
toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) # Structure initializers
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
toolbox.register("population", tools.initRepeat, list, toolbox.individual) def evalTSP(individual):
distance = distance_map[individual[-1]][individual[0]]
for gene1, gene2 in zip(individual[0:-1], individual[1:]):
distance += distance_map[gene1][gene2]
return distance, toolbox.register("mate", tools.cxPartialyMatched)
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("evaluate", evalTSP) def main():
random.seed(169) pop = toolbox.population(n=300) hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", numpy.mean)
stats.register("std", numpy.std)
stats.register("min", numpy.min)
stats.register("max", numpy.max) algorithms.eaSimple(pop, toolbox, 0.7, 0.2, 40, stats=stats,
halloffame=hof) return pop, stats, hofn'g'x

  该例子中使用SGA实现求解TSP问题,可以看到deap提供了灵活的插件化算法解决方案。deap的思想实现就是通过灵活的插件化思想,同时再框架中提供了丰富的算法实现,你可以用堆积木一样的方式,轻松的实现你的遗传算法处理程序。同时你也可以使用自己实现的算法模块,只需要注册框架就可以。框架通过函数导入的方法,通过register可以将你的算法函数注册到运行环境中。

  未完待续。