Sampling without replacement from a given non-uniform distribution in TensorFlow

北慕城南 提交于 2019-12-01 03:53:58

You could just use tf.py_func to wrap numpy.random.choice and make it available as a TensorFlow op:

a = tf.placeholder(tf.float32)
size = tf.placeholder(tf.int32)
replace = tf.placeholder(tf.bool)
p = tf.placeholder(tf.float32)

y = tf.py_func(np.random.choice, [a, size, replace, p], tf.float32)

with tf.Session() as sess:
    print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))

You can specify the numpy seed as usual:

np.random.seed(1)
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
np.random.seed(1)
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))
np.random.seed(1)
print(sess.run(y, {a: range(3), size: 2, replace:False, p:[0.1,0.2,0.7]}))

would print:

[ 2.  0.]
[ 2.  1.]
[ 0.  1.]
[ 2.  0.]
[ 2.  1.]
[ 0.  1.]
[ 2.  0.]

Yes, there is. See here and here for some background information. The solution is:

z = -tf.log(-tf.log(tf.random_uniform(tf.shape(p),0,1))) 
_, indices = tf.nn.top_k(tf.log(p) + z, size)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!