英文:
How to sample 5 index and their probabilities from a tensorflow tensor of probability distribution?
问题
Sure, here's the translation of the code-related part:
我有一个概率分布(经过Softmax处理后),其中每行的值相加等于1。
probs = tf.constant([
[0.0, 0.1, 0.2, 0.3, 0.4],
[0.5, 0.3, 0.2, 0.0, 0.0]])
我想要使用tensorflow操作从中抽样k个索引及其相应的概率值。
3个索引的期望输出:
index: [
[4, 3, 4],
[0, 1, 0]
]
probs: [
[0.4, 0.3, 0.4],
[0.5, 0.3, 0.5]
]
我该如何实现这个?
英文:
I have a probability distribution (after applying Softmax) where values in each row sums up to 1
probs = tf.constant([
[0.0, 0.1, 0.2, 0.3, 0.4],
[0.5, 0.3, 0.2, 0.0, 0.0]])
I want to sample k index from it and their respective probability values using tensorflow operations.
The expected output for 3 index:
index: [
[4, 3, 4],
[0, 1, 0]
]
probs: [
[0.4, 0.3, 0.4],
[0.5, 0.3, 0.5]
]
How can I achieve this?
答案1
得分: 1
使用tf.random.uniform
生成随机索引的张量:
k = 3 # 设置要抽样的元素数量
# 获取概率张量的维度
row, cols = tf.unstack(tf.shape(probs))
# 为每行生成0到cols - 1之间的k个值
idx = tf.random.uniform((row, k), 0, cols, dtype=tf.int32)
使用tf.gather_nd
根据索引获取概率张量的值:
tf.gather(probs, idx, batch_dims=1)
英文:
Generating a random tensor of indexes with tf.random.uniform
:
k = 3 # setting up the number of element to sample
# getting the dimension of the prob tensor
row, cols = tf.unstack(tf.shape(probs))
# Generating k values for each row between 0 and cols - 1
idx = tf.random.uniform((row, k), 0, cols, dtype=tf.int32)
>>> idx
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 4],
[3, 1, 0]], dtype=int32)>
Using tf.gather_nd
to index the probabilities tensor with the indexes:
>>> tf.gather(probs, idx, batch_dims=1)
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0. , 0. , 0.4],
[0. , 0.3, 0.5]], dtype=float32)>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论