Reputation: 553
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?
Upvotes: 2
Views: 1924
Reputation: 69984
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)
Upvotes: 2
Reputation: 52008
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.
Upvotes: 2
Reputation: 596
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])
.
Upvotes: 1