【问题标题】:Softmax function in Tensorflow not displaying correct answerTensorflow中的Softmax函数未显示正确答案
【发布时间】:2017-07-20 11:11:49
【问题描述】:

我正在测试 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))

返回

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

print(sess.run(softmaxkh))

返回

    [[  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]]

【问题讨论】:

    标签: python tensorflow softmax


    【解决方案1】:

    那是因为random_uniformdraws 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      相关资源
      最近更新 更多