1

How can I generate a tensor in tensorflow of Bernoulli distribution with factor p ?

For example:

a = tf.bernoulli(shape=[10,10], p)

generates a matrix 10x10 of 0-1 where each element of matrix is one with probability p and zero with probability 1-p.

amer
  • 1,528
  • 1
  • 14
  • 22
M.Bejani
  • 11
  • 5

4 Answers4

0

I can solve my problem! :D The following code generates, what I need where p=0.7:

p = tf.constant([0.7])
r = tf.random.uniform(shape=shape, maxval=1)
b = tf.math.greater(p, r)
f = tf.cast(b, dtype=tf.float32)
M.Bejani
  • 11
  • 5
0

You can use Bernoulli distribution from Tensorflow probability library which is an extension built on Tensorflow:

import tensorflow_probability as tfp
x = tfp.distributions.Bernoulli(probs=0.7).sample(sample_shape=(10, 10))
x

This will output

<tf.Tensor: shape=(10, 10), dtype=int32, numpy=
array([[1, 1, 1, 1, 0, 0, 0, 1, 1, 0],
       [1, 0, 1, 0, 1, 1, 0, 1, 0, 0],
       [1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
       [0, 0, 1, 1, 0, 1, 1, 1, 1, 1],
       [1, 1, 0, 1, 1, 1, 1, 0, 1, 1],
       [1, 0, 1, 1, 1, 0, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1, 1, 1, 1, 1],
       [1, 0, 0, 1, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
       [1, 0, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32)>

The other method is to use a similar class from tf.compat:

import tensorflow as tf
x = tf.compat.v1.distributions.Bernoulli(probs=0.7).sample(sample_shape=(10, 10))
x

You will get x as you want but also a bunch of deprecation warnings will fall. So, I would recommend to use the 1st variant.

Also take into account that when I tested this code the latest version of tensorflow_probability library required tensoflow>=2.3 installed.

july_coder
  • 61
  • 2
0

What about using tf.random.Generator.binomial? It does not require installing tensorflow_probability.

https://www.tensorflow.org/api_docs/python/tf/random/Generator#binomial

rng = tf.random.Generator.from_seed(seed=234)
rng.binomial(shape=[10], counts=1.0, probs=0.7)

When counts = 1.0, I think the binomial is the same as the Bernoulli.

The output of the above will be as follows:

<tf.Tensor: shape=(10,), dtype=int32, numpy=array([1, 1, 0, 1, 0, 1, 0, 0, 0, 1], dtype=int32)>
chanwcom
  • 4,420
  • 8
  • 37
  • 49
0

bern = tf.distributions.Bernoulli(probs=p)

x = bern.sample([10, 10])

杨旭东
  • 11
  • 2