Skip to content

Instantly share code, notes, and snippets.

@DMTSource
Created January 16, 2021 21:11
Show Gist options
  • Save DMTSource/8005e8e345ed03438e3fca655ff57792 to your computer and use it in GitHub Desktop.
Save DMTSource/8005e8e345ed03438e3fca655ff57792 to your computer and use it in GitHub Desktop.
Deap python example showing how population lists can be combined for use with hybrid initialization methods such as heuristic + random.
import array
import random
import numpy
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", array.array, typecode='b', fitness=creator.FitnessMax)
toolbox = base.Toolbox()
# Attribute generator
toolbox.register("attr_bool", random.randint, 0, 1)
# Structure initializers
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
def evalOneMax(individual):
return sum(individual),
toolbox.register("evaluate", evalOneMax)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
def main():
random.seed(64)
# How we normally make a pop
pop = toolbox.population(n=200)
print(len(pop)) #200
# You can combine different init mthods and append them like so sice they are just lists
pop += toolbox.population(n=100)
print(len(pop)) #300
# What if we have a case of known individual, but not yet and Individual object?
known_but_not_an_ind = [
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
]
# Can manually add items too
pop += [creator.Individual(new_ind) for new_ind in known_but_not_an_ind]
print(len(pop)) #303
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)
pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40,
stats=stats, halloffame=hof, verbose=True)
return pop, log, hof
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment