我正在使用tf.multinomial在Tensorflow中生成样本,并且正在寻找一种方法来返回与随机选择的元素相关联的概率。因此,在以下情况下:
logits = [[-1., 0., 1], [1, 1, 1], [0, 1, 2]]
samples = tf.multinomial(logits, 2)
with tf.Session() as sess:
sess.run(samples)而不是让
[[1, 2], [0, 1], [1, 1]]因此,我希望看到类似这样的东西
[[(1, 0.244728), (2, 0.66524)],
[(0, 0.33333), (1, 0.33333)],
[(1, 0.244728), (1, 0.244728)]]有什么方法可以做到这一点吗?
发布于 2018-06-21 22:17:37
我很困惑,tensorflow是否在内部做了某种转换,将您的逻辑转换为概率?多项分布采用一组位置概率作为参数,这些概率概率地确定了结果(位置)被抽样的可能性。i.e
# this is all psuedocode
x = multinomial([.2, .3, .5])
y ~ x
# this will give a value of 0 20% of the time
# a value of 1 30% of the time
# and a value of 2 50% of the time因此,你的概率可能就是你的逻辑。
看着https://www.tensorflow.org/api_docs/python/tf/multinomial
你会看到它们是“非标准化的对数概率”,所以如果你能应用这个变换,你就有了这些概率
发布于 2020-01-18 20:02:00
你可以试试tf.gather_nd,你可以试试
>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> probs = tf.constant([[0.5, 0.2, 0.1, 0.2], [0.6, 0.1, 0.1, 0.1]], dtype=tf.float32)
>>> idx = tf.multinomial(probs, 1)
>>> row_indices = tf.range(probs.get_shape()[0], dtype=tf.int64)
>>> full_indices = tf.stack([row_indices, tf.squeeze(idx)], axis=1)
>>> rs = tf.gather_nd(probs, full_indices)或者,您可以使用tf.distributions.Multinomial,优点是您不需要关心上面代码中的batch_size。当您设置batch_size=None时,它可以在不同的batch_size下工作。这里有一个简单的例子,
multinomail = tf.distributions.Multinomial(
total_count=tf.constant(1, dtype=tf.float32),
probs=probs)
sampled_actions = multinomail.sample() # sample one action for data in the batch
predicted_actions = tf.argmax(sampled_actions, axis=-1)
action_probs = sampled_actions * predicted_probs
action_probs = tf.reduce_sum(action_probs, axis=-1)我想这就是你想要做的。我更喜欢后者,因为它灵活而优雅。
https://stackoverflow.com/questions/48724795
复制相似问题