gpt4 book ai didi

python - 谁能举一个小例子来解释 tf.random.categorical 的参数?

转载 作者:太空狗 更新时间:2023-10-30 01:10:56 29 4
gpt4 key购买 nike

tensorflow 的网站给出了这个例子

tf.random.categorical(tf.log([[10., 10.]]), 5)

产生一个“形状为 [1, 5] 的张量,其中每个值为 0 或 1 的概率相等”

我已经知道了,基本demo , tf.log([[10., 10.]])的含义。

我想知道的是 [batch_size, num_classes] 是做什么的,谁能举个小例子来解释这些参数?

最佳答案

如您所见,tf.random.categorical接受两个参数:

  • logits,一个二维浮点张量,形状为 [batch_size, num_classes]
  • num_samples,一个整数标量。

输出是一个二维整数张量,形状为[batch_size, num_samples]

logits 张量的每个“行”(logits[0, :], logits[1, :], ... ) 表示不同 categorical distribution 的事件概率.不过,该函数并不期望实际的概率值,而是非标准化的对数概率;所以实际概率将是 softmax(logits[0, :])softmax(logits[1, :]) 等。这样做的好处是您可以基本上给出任何真实值作为输入(例如神经网络的输出)并且它们将是有效的。此外,使用对数来使用特定的概率值或比例也很简单。例如,[log(0.1), log(0.3), log(0.6)][log(1), log(3), log(6)] 表示相同的概率,其中第二类的可能性是第一类的三倍,但只有第三类的一半。

对于每一行(非标准化对数)概率,您从分布中获得 num_samples 个样本。每个样本都是 0num_classes - 1 之间的整数,根据给定的概率抽取。因此,结果是形状为 [batch_size, num_samples] 的二维张量,每个分布都有采样整数。

编辑:函数的一个小例子。

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(123)
logits = tf.log([[1., 1., 1., 1.],
[0., 1., 2., 3.]])
num_samples = 30
cat = tf.random.categorical(logits, num_samples)
print(sess.run(cat))
# [[3 3 1 1 0 3 3 0 2 3 1 3 3 3 1 1 0 2 2 0 3 1 3 0 1 1 0 1 3 3]
# [2 2 3 3 2 3 3 3 2 2 3 3 2 2 2 1 3 3 3 2 3 2 2 1 3 3 3 3 3 2]]

在这种情况下,结果是一个包含两行和 30 列的数组。第一行中的值是从分类分布中采样的,其中每个类 ([0, 1, 2, 3]) 具有相同的概率。在第二行中,类 3 是最有可能的,类 0 只是没有被采样的概率。

关于python - 谁能举一个小例子来解释 tf.random.categorical 的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55063120/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com