为什么 softmax 交叉熵损失从不在张量流中给出零值?

Why softmax cross entropy loss never gives a value of zero in tensorflow?

我在 tensorflow 中做一个神经网络,我使用 softmax_cross_entropy 来计算损失,我在做测试并注意到它永远不会给出零值,即使我比较相同的值,这是我的代码

labels=[1,0,1,1]


with tf.Session() as sess:
    onehot_labels=tf.one_hot(indices=labels,depth=2)
    logits=[[0.,1.],[1.,0.],[0.,1.],[0.,1.]]
    print(sess.run(onehot_labels))
    loss=tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels,logits=logits)
    print(sess.run(loss))

我得到了这个

[[0. 1.]
 [1. 0.]
 [0. 1.]
 [0. 1.]]
0.31326166

为什么不为零?

Matias 的 post 是正确的。以下代码给出与您的代码相同的结果

labels=[1,0,1,1]

with tf.Session() as sess:
    onehot_labels=tf.one_hot(indices=labels,depth=2)
    logits=[[0.,1.],[1.,0.],[0.,1.],[0.,1.]]
    print(sess.run(onehot_labels))

    probabilities = tf.nn.softmax(logits=logits)
    # cross entropy
    loss = -tf.reduce_sum(onehot_labels * tf.log(probabilities)) / len(labels)

    print(sess.run(loss))