Created
December 19, 2017 05:32
-
-
Save paujjone/9be45334bfc0995dd4520b3f02c74270 to your computer and use it in GitHub Desktop.
In too DEAP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from deap import base, creator, tools, algorithms | |
creator.create("FitnessMax", base.Fitness, weights=(1.0,)) | |
creator.create("Individual", list, fitness=creator.FitnessMax) | |
ind = creator.Individual([1, 0, 1, 1, 0]) | |
toolbox = base.Toolbox() | |
toolbox.register("attr_bool", random.randint, 0, 1) | |
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=10) | |
toolbox.register("population", tools.initRepeat, list, toolbox.individual) | |
bit = toolbox.attr_bool() | |
ind = toolbox.individual() | |
pop = toolbox.population(n=3) | |
def evalOneMax(individual): | |
score = 0 | |
for i in range(len(individual)): | |
if i%2==0: | |
if individual[i]==0: | |
score += 1 | |
elif i%2 != 0: | |
if individual[i]==0: | |
score += 1 | |
return(score) | |
toolbox.register("evaluate", evalOneMax) | |
toolbox.register("mate", tools.cxTwoPoint) | |
toolbox.register("mutate", tools.mutFlipBit, indpb=0.10) | |
toolbox.register("select", tools.selTournament, tournsize=3) | |
ind = toolbox.individual() | |
toolbox.mutate(ind) | |
mutant = toolbox.clone(ind) | |
def main(): | |
import numpy | |
pop = toolbox.population(n=50) | |
hof = tools.HallOfFame(1) | |
stats = tools.Statistics(lambda ind: ind.fitness.values) | |
stats.register("avg", numpy.mean) | |
stats.register("min", numpy.min) | |
stats.register("max", numpy.max) | |
pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=10, stats=stats, halloffame=hof, verbose=True) | |
return pop, logbook, hof | |
if __name__ == "__main__": | |
pop, log, hof = main() | |
print("Best individual is: %s\nwith fitness: %s" % (hof[0], hof[0].fitness)) | |
import matplotlib.pyplot as plt | |
gen, avg, min_, max_ = log.select("gen", "avg", "min", "max") | |
plt.plot(gen, avg, label="average") | |
plt.plot(gen, min_, label="minimum") | |
plt.plot(gen, max_, label="maximum") | |
plt.xlabel("Generation") | |
plt.ylabel("Fitness") | |
plt.legend(loc="lower right") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment