Search code examples
tensorflowrandomtensorflow-probability

Generating random integers in TensorFlow


I would like to generate random integers in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {1, 2, 3, 4}. I have tried to look among the distributions included in tensorflow_probability but I didn't find it.

Thanks in advance for your help.


Solution

  • For simple integers from uniform distribution you could use tf.random.uniform.
    In order to get the specified range and integers you should specify the minval, maxval and dtype parameters. So in your case:

    For Tensorflow 2.0 and above:

    print(tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
    

    For Tensorflow 1.15 and below:

    with tf.Session() as sess:
        random_int = tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
        print(sess.run(random_int))
    

    Note that the actual maximum value will be maxval-1.