简体   繁体   中英

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?

A natural way is to use the expression

1 if random.random() <= 0.8 else 0

You can abstract this into a function:

def bernoulli(p): return 1 if random.random() <= p else 0

Then bernoulli(0.8) will give 1 or 0 with the requisite probabilities. I am not familiar with the GA library you are using, but bernoulli() is callable hence it should work.

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)

random.randint does not provide such functionality, but if you wanted to stay in the random package, you could use random.choice([0] * 1 + [1] * 4) .

numpy.random also provides this functionality with np.random.choice([0, 1], p=[0.2, 0.8]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM