[英]How to sample tensor values given probabilities for each value in tensorflow?
We need to sample values from one tensor regarding to another tensor that contains probabilities. 我们需要从一个张量采样到另一个包含概率的张量的值。 Lets say, we have two tensors t1,t2 of shape (?,3), and want to find another tensor t3 of shape (?,1) that contains a sample of each row in t1 regarding to probabilities in t2.
可以说,我们有两个形状为(?,3)的张量t1,t2,并且想要找到另一个形状为(?,1)的张量t3,其中包含与t2中的概率有关的t1中每一行的样本。
You do this in two steps. 您分两步执行此操作。 First, you sample indices
0
, 1
and 2
, then you replace those indices with tensor values. 首先,样本索引
0
, 1
和2
,然后用你张量的值替换那些索引。 This can be done with tf.random.categorical
(see this question for more information about this function). 这可以通过
tf.random.categorical
完成(有关此功能的更多信息,请参阅此问题 )。 Note tf.random.categorical
was added in version 1.13.1. 注意
tf.random.categorical
已在1.13.1版中添加。
import tensorflow as tf
with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(0)
values = tf.placeholder(tf.float32, [None, 3])
probabilities = tf.placeholder(tf.float32, [None, 3])
# You can change the number of samples per row (or make it a placeholder)
num_samples = 1
# Use log to get log-probabilities or give logit values (pre-softmax) directly
logits = tf.log(probabilities)
# Sample column indices
col_idx = tf.random.categorical(logits, num_samples, dtype=tf.int32)
# Make row indices
num_rows = tf.shape(values)[0]
row_idx = tf.tile(tf.expand_dims(tf.range(num_rows), 1), (1, num_samples))
# Gather actual values
result = tf.gather_nd(values, tf.stack([row_idx, col_idx], axis=-1))
# Test
print(sess.run(result, feed_dict={
values: [[10., 20., 30.], [40., 50., 60.]],
# Can be actual or "proportional" probabilities not summing 1
probabilities: [[.1, .3, .6], [0., 4., 2.]]
}))
# [[30.]
# [60.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.