Search code examples
pythontensorflowrandomrandom-seedhashlib

Generating random sequence in tensorflow with another tensor as seed


I have a use-case where I need to generate a sequence of random integers given an input integer. There are many ways to do this in python. The one I am currently using is as follows:

import hashlib
def nextRandom(seed, length, maxval):
    md5 = hashlib.md5(str(hash(seed)).encode('utf-8'))
    for k in range(length):
        md5.update(str(k).encode('utf-8'))
        yield int(md5.hexdigest(), 16) % maxval

seed = 12345
length = 10
maxval = 1000
for randInt in nextRandom(seed, length, maxval):
    print(randInt)

This ensures that the generated sequence is fixed given a seed value.

Now, I need to a similar functionality in tensorflow where seed comes as a tensor and the returned sequence should also be tensor.

I checked this issue in tensorflow github page, but couldn't find a working solution.


Solution

  • Here is one possible solution with tf.contrib.stateless module:

    import tensorflow as tf
    
    seed = tf.random_uniform(shape=[2], dtype=tf.int64, maxval=1000000)
    x = tf.contrib.stateless.stateless_random_uniform(shape=(1, 1), dtype=tf.float32, seed=seed)
    
    sess = tf.Session()
    print(sess.run(x))
    

    Note that, the stateless module does not support integers unless in stateless_multinomial case.