Generate a random bool with Tensorflow

Viewed 557

How to efficiently generate a random bool with Tensorflow? Doesen't need to be cryptographically safe. Ideally only using tensorflow as tf.

2 Answers

This worked for me:

tf.random.uniform([]) < p  # p=0.5 for 50% chance

TensorFlow (2.9.1) documentation seems to give this:

Code:

# samples has shape [1, 5], where each value is either 0 or 1 with equal
# probability.
samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5)
print(samples) # I added this line

Result:

tf.Tensor([[0 1 0 1 1]], shape=(1, 5), dtype=int64)

For your application, I think the call might need to be:

samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 1)

which gives:

tf.Tensor([[1]], shape=(1, 1), dtype=int64)

Reference: https://www.tensorflow.org/api_docs/python/tf/random/categorical

Related