DEAP / deap

Distributed Evolutionary Algorithms in Python
http://deap.readthedocs.org/
GNU Lesser General Public License v3.0
5.77k stars 1.12k forks source link

How to generate random strings or characters for individuals #676

Open r8vnhill opened 1 year ago

r8vnhill commented 1 year ago

I am currently trying to make a simple algorithm that can guess words, I am using the One Max example as base, but I can't find a way to generate the individual's attributes.

What I tried doing is:

res = string.ascii_letters
the_toolbox.register("attr_bool", random.choice, res)

But I get the following error:

TypeError: array() argument 1 must be a unicode character, not getset_descriptor

I don't really understand what's causing the error and I haven't been able to find anything online

r8vnhill commented 1 year ago

I'll leave the full code for completion

import array
import random
import string

import numpy
from deap import algorithms, base, creator, tools

creator.create("fitness_max", base.Fitness, weights=(1.0,))
creator.create("individual_creator", array.array, fitness=creator.fitness_max)
toolbox = base.Toolbox()
toolbox.register("attr_char", random.choice, string.ascii_letters)
toolbox.register("individual", tools.initRepeat, creator.individual_creator,
                 toolbox.attr_char, n=10)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

target: str

def count_matches(individual):
    """
    The fitness function.
    It counts the number of characters that match the target word.
    """
    return sum(1 for expected, actual in zip(target, individual) if expected == actual),

toolbox.register("evaluate", count_matches)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

def main():
    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)

    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__":
    target = "Sopaipilla"
    _, _, fittest = main()
    print(fittest[0])