输出层中有softmax函数的问题

问题描述 投票:1回答:1

我有一个张量存储在a中,如下:

<tf.Tensor: shape=(5, 1), dtype=float32, numpy=
array([[0.1 ],
       [0.2 ],
       [0.4 ],
       [0.15],
       [0.15]], dtype=float32)>

当我在上面应用softmax函数时,

a_tf = tf.nn.softmax(a)

我得到一个张量,如下所示

<tf.Tensor: shape=(5, 1), dtype=float32, numpy=
array([[1.],
       [1.],
       [1.],
       [1.],
       [1.]], dtype=float32)>

尽管我期望0到1之间的归一化值加起来为1。

的确,当我使用softmax定义代码时

a_tf = out_put = (tf.exp(a)) / (tf.reduce_sum(tf.exp(a)))

我得到预期的张量:

<tf.Tensor: shape=(5, 1), dtype=float32, numpy=
array([[0.1799347 ],
       [0.19885859],
       [0.24288644],
       [0.18916014],
       [0.18916014]], dtype=float32)>

有人可以解释为什么第一个代码段无法按预期工作吗?

tensorflow tensor softmax
1个回答
1
投票

您的输入数组(或张量)的形状为(5, 1),默认情况下,tf.nn.softmax用于最后一个维。您可能会发现现在出了问题,因为最后一个维度是一个单独的元素,然后使用softmax将其标准化为1.0

然后您有两个选择:

  • 指定axis=0tf.nn.softmax,以便在第一个尺寸而不是最后一个尺寸上执行操作。
  • 将数组重塑为(1, 5)的形状,将其与对tf.nn.softmax的默认调用一起使用
© www.soinside.com 2019 - 2024. All rights reserved.