jeudi 6 février 2020

DEAP: How to generate a limited number of 1's in a cromossome using random (0, 1)

I have this first code (NO DEAP). I can create a cromossome with only zeros (0) then in a random position I change with "1". Only 50 times. I need a cromossome with maximum 50 times of "1". I need this using DEAP framework.

    size = 2000
    max_one = 50
    for i in range(size):
        self.cromossomo.append("0")
    total = np.random.randint(1, max_one)
    for i in range(total):
        index = np.random.randint(0, size - 1)
        self.cromossomo[index] = "1"

Using DEAP I have this code:

toolbox.register("attr_bool", random.randint, 0, 1)    
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=2000)

But it creates more than 50 times of "1", sometimes 900, 1200, etc. How can I limit that random creates only 50 times of "1".




Aucun commentaire:

Enregistrer un commentaire