在 TensorFlow 中采样伯努利随机变量 [英] Sampling Bernoulli random variables in TensorFlow

查看:26
本文介绍了在 TensorFlow 中采样伯努利随机变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a 1D tensor containing the means of a Bernoulli distribution, how do I sample a corresponding 1D tensor with the given means?

TensorFlow 似乎只实现了 random_normalrandom_uniform 函数.我可以使用一些复杂的东西,例如:

TensorFlow only seems to have random_normal and random_uniform functions implemented. I could use something complicated like:

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

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

but the ceil function has no gradient defined in TensorFlow.

推荐答案

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

Since TFr1.0, tf.select is deprecated in favor of tf.where. Furthermore, the answer given by @keveman should compare the uniform random sampling with < 0, neither with > 0.5 nor with > 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()

这篇关于在 TensorFlow 中采样伯努利随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆