在 TensorFlow 中对伯努利随机变量进行采样

Sampling Bernoulli random variables in TensorFlow

给定包含伯努利分布均值的一维张量,我如何使用给定均值对相应的一维张量进行采样?

TensorFlow 似乎只实现了 random_normalrandom_uniform 功能。我可以使用一些复杂的东西,比如:

tf.ceil(tf.sub(tf.random_uniform((1, means.get_shape()[0])),means))

但是ceil函数在TensorFlow中没有定义梯度。

你可以使用tf.select,这是可微的

means = tf.constant([.3,.8])
a = tf.select(tf.random_uniform([1, 2])- means > 0.5, tf.ones([1,2]), tf.zeros([1,2]))
with tf.Session(''): a.eval()

自 TFr1.0 起,tf.select 已弃用,取而代之的是 tf.where。此外,@keveman 给出的答案应该将均匀随机抽样与 < 0 进行比较,既不与 > 0.5 也不与 > 0:

    means = tf.constant([.3,.8])
    sample = tf.where(tf.random_uniform([1, 2]) - means < 0, 
      tf.ones([1,2]), tf.zeros([1,2]))
    with tf.Session(''): sample.eval()

I've seen 还有以下技巧作为从伯努利分布中抽样的一种方式:

tf.nn.relu(tf.sign(means - tf.random_uniform(tf.shape(means))))