首页 > 解决方案 > 为什么softmax交叉熵损失在张量流中永远不会给出零值?

问题描述

我在张量流中做一个神经网络,我使用 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

为什么不是零??

标签: pythontensorflowneural-networkconv-neural-networktensorflow-estimator

解决方案


马蒂亚斯的帖子是正确的。以下代码给出与您的代码相同的结果

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))

推荐阅读