如何使用 random.randint 以不等概率找到随机的 0 和 1
How to use random.randint to find random 0 and 1 with not equal propbability
我在 Python 中使用 DEAP 工具箱进行遗传算法。
toolbox.register("attr_bool", random.randint, 0, 1)
是GA中随机选择0和1的函数。我想强制 GA 随机选择 0 和 1,但例如 80% 为 1,其余为 0。
我认为srng.binomial(X.shape, p=retain_prob)
是一个选择,但我想使用random.randint
功能。想知道我们如何做到这一点?
random.randint
不提供这样的功能,但是如果你想留在 random
包中,你可以使用 random.choice([0] * 1 + [1] * 4)
.
numpy.random
也通过 np.random.choice([0, 1], p=[0.2, 0.8])
.
提供此功能
一种自然的方式是使用表达式
1 if random.random() <= 0.8 else 0
你可以把它抽象成一个函数:
def bernoulli(p): return 1 if random.random() <= p else 0
然后 bernoulli(0.8)
将以必要的概率给出 1 或 0。我不熟悉您使用的 GA 库,但 bernoulli()
是可调用的,因此它应该可以工作。
toolbox.register
的参数必须是一个函数,并且当您 运行 它
时要传递给该函数的参数
因为 0 if random.randint(0, 4) == 0 else 1
不是一个函数(它是一个随机数)你得到了一个错误。解决方法是将此表达式打包到一个可以传递给 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)
我在 Python 中使用 DEAP 工具箱进行遗传算法。
toolbox.register("attr_bool", random.randint, 0, 1)
是GA中随机选择0和1的函数。我想强制 GA 随机选择 0 和 1,但例如 80% 为 1,其余为 0。
我认为srng.binomial(X.shape, p=retain_prob)
是一个选择,但我想使用random.randint
功能。想知道我们如何做到这一点?
random.randint
不提供这样的功能,但是如果你想留在 random
包中,你可以使用 random.choice([0] * 1 + [1] * 4)
.
numpy.random
也通过 np.random.choice([0, 1], p=[0.2, 0.8])
.
一种自然的方式是使用表达式
1 if random.random() <= 0.8 else 0
你可以把它抽象成一个函数:
def bernoulli(p): return 1 if random.random() <= p else 0
然后 bernoulli(0.8)
将以必要的概率给出 1 或 0。我不熟悉您使用的 GA 库,但 bernoulli()
是可调用的,因此它应该可以工作。
toolbox.register
的参数必须是一个函数,并且当您 运行 它
因为 0 if random.randint(0, 4) == 0 else 1
不是一个函数(它是一个随机数)你得到了一个错误。解决方法是将此表达式打包到一个可以传递给 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)