简体   繁体   中英

what is the tensorflow equivalent for pytorch probability function: torch.bernoulli?

In Pytorch, you can do following:

x = torch.bernoulli(my_data)

Any similar functionality in tensorflow? Can the input be 2-D tensor, such as (batch, len)?

I tried tensorflow.contrib.distributions.Bernoulli:

import numpy as np
tmp_x1 = np.random.rand(20,5) 
new_data_2 = tf.convert_to_tensor(tmp_x1)
from tensorflow.contrib.distributions import  Bernoulli
tmp2_x1 = Bernoulli(probs=new_data_2)

got error:

return math_ops.log(probs) - math_ops.log1p(-1. * probs), probs
TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'

It seems tf.distributions.Bernoulli does what you need. The input can be an ND tensor, which includes a 2D tensor.

EDIT: example use

After your comment, I tried the following, which worked for me (using tensorflow 1.11):

import numpy as np
import tensorflow
import tensorflow as tf
from tensorflow.distributions import  Bernoulli

tmp_x1 = np.random.rand(20,5)
new_data_2 = tf.convert_to_tensor(tmp_x1)
tmp2_x1 = Bernoulli(probs=new_data_2)
sess = tf.Session()
print sess.run(tmp2_x1.sample())

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