Search code examples
pythonrandomgenetic-algorithmdeap

How to use random.randint to find random 0 and 1 with not equal propbability


I am using DEAP toolbox in Python for Genetic Algorithm.

toolbox.register("attr_bool", random.randint, 0, 1) is a function randomly chooses 0 and 1 for populations in GA. I want to force GA to choose 0 and 1 randomly but with for example 80% one and the rest zero.

I think srng.binomial(X.shape, p=retain_prob) is a choice, but I want to use random.randint function. Wondering how we can do that?


Solution

  • The arguments to toolbox.register must be a function and the arguments that you want to pass to that function when you run it

    Since 0 if random.randint(0, 4) == 0 else 1 is not a function (its a random number) you got an error. The fix is to package this expression inside a function that you can pass to toolbox.register:

    # returns 1 with probability p and 0 with probability 1-p
    def bernoulli(p):
        if random.random() < p:
            return 1
        else:
            return 0
    
    toolbox.register("attr_bool", bernoulli, 0.8)