Tensorflow 中的 Softmax 函数未显示正确答案

Softmax function in Tensorflow not displaying correct answer

我正在测试 Tensorflow 的 softmax 函数,但我得到的答案似乎不正确。

所以在下面的代码中,kh 是一个 [5,4] 矩阵。 softmaxkh应该是kh的softmax矩阵。然而,即使不进行计算,您也可以看出 kh 中特定列或行中的最大数字不一定对应于 softmaxkh 中的最大数字。

例如,最后一列中间行的“65”是其列和行中的最高数字,但是在 softmaxkh 中它的行和列中它并不代表最高数字。

import tensorflow as tf 

kh = tf.random_uniform(
    shape= [5,4],
    maxval=67,
    dtype=tf.int32,
    seed=None,
    name=None
)

sess = tf.InteractiveSession()

kh = tf.cast(kh, tf.float32)

softmaxkh = tf.nn.softmax(kh)


print(sess.run(kh))

哪个returns

    [[ 55.  49.  48.  30.]
     [ 21.  39.  20.  11.]
     [ 40.  33.  58.  65.]
     [ 55.  19.  12.  24.]
     [ 17.   8.  14.   0.]]

print(sess.run(softmaxkh))

returns

    [[  1.42468502e-21   9.99663830e-01   8.31249167e-07   3.35349847e-04]
     [  3.53262839e-24   1.56288218e-18   1.00000000e+00   3.13913289e-17]
     [  6.10305051e-06   6.69280719e-03   9.93300676e-01   3.03852971e-07]
     [  2.86251861e-20   2.31952296e-16   8.75651089e-27   1.00000000e+00]
     [  5.74948687e-19   2.61026280e-23   9.99993801e-01   6.14417422e-06]]

那是因为随机生成器如random_uniform draws different numbers every time you call it.

您需要将结果存储在 Variable 中,以便在不同的图表 运行 中重用随机生成的值:

import tensorflow as tf 

kh = tf.random_uniform(
    shape= [5,4],
    maxval=67,
    dtype=tf.int32,
    seed=None,
    name=None
)

kh = tf.cast(kh, tf.float32)
kh = tf.Variable(kh)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

softmaxkh = tf.nn.softmax(kh)

# run graph
print(sess.run(kh))
# run graph again
print(sess.run(softmaxkh))

另外,如果这些值只使用一次但在多个位置使用,您可以运行图表一次调用所有所需的输出。

import tensorflow as tf 

kh = tf.random_uniform(
    shape= [5,4],
    maxval=67,
    dtype=tf.int32,
    seed=None,
    name=None
)

kh = tf.cast(kh, tf.float32)

sess = tf.InteractiveSession()

softmaxkh = tf.nn.softmax(kh)

# produces consistent output values
print(sess.run([kh, softmaxkh))
# also produces consistent values, but different from above
print(sess.run([kh, softmaxkh))