tensorflow - 了解 softmax_cross_entropy_with_logits 的输出

标签 tensorflow

我是 tensorflow 新手,有人可以解释一下我们是如何得到答案 1.16012561 的吗?

 unscaled_logits = tf.constant([[1., -3., 10.]])
   target_dist = tf.constant([[0.1, 0.02, 0.88]])
   softmax_xentropy = 
   tf.nn.softmax_cross_entropy_with_logits(logits=unscaled_logits, 
   labels=target_dist)
   with tf.Session() as sess:
       print(sess.run(softmax_xentropy))

输出:[1.16012561]

最佳答案

Here is a good explanation about it 。它的工作原理是这样的。首先,logits 通过 softmax function 传递,给你一个概率分布:

import numpy as np

logits = np.array([1., -3., 10.])
# Softmax function
softmax = np.exp(logits) / np.sum(np.exp(logits))
print(softmax)
>>> array([  1.23394297e-04,   2.26004539e-06,   9.99874346e-01])
# It is a probability distribution because the values are in [0, 1]
# and add up to 1
np.sum(softmax)
>>> 0.99999999999999989  # Almost, that is

然后,计算计算出的 softmax 值与目标之间的交叉熵。

target = np.array([0.1, 0.02, 0.88])
# Cross-entropy function
crossentropy = -np.sum(target * np.log(softmax))
print(crossentropy)
>>> 1.1601256622376641

tf.nn.softmax_cross_entropy_with_logits将返回“每个向量”这些值之一(默认情况下,“向量”位于最后一个维度),因此,例如,如果您的输入 logits 和目标的大小为 10x3,您最终将得到 10 个交叉熵值。通常,我们对所有这些进行求和或平均,并将结果用作损失值以最小化(这就是 tf.losses.softmax_cross_entropy 提供的)。交叉熵表达式背后的逻辑是,target * np.log(softmax) 将采用接近零的负值,其中 targetsoftmax 当它们不同时,会从零发散(向负无穷大)。

注意:这是该函数的逻辑解释。在内部,TensorFlow 很可能执行不同但等效的操作,以获得更好的性能和数值稳定性。

关于tensorflow - 了解 softmax_cross_entropy_with_logits 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45489314/

相关文章:

tensorflow - 是否建议保存 RNN 训练的最终状态以在测试期间对其进行初始化?

python - Tensorflow 第一层神经元的权重不会改变

python - 如何将稀疏张量传递到 TF 2.0 中的密集层?

tensorflow - tensorflow 中的 tf.GraphKeys.TRAINABLE_VARIABLES 和 tf.GraphKeys.UPDATE_OPS 有什么区别?

tensorflow - 导入 tensorflow 失败,错误无属性 'HIDDEN_ATTRIBUTE'

python - RaggedTensor 对 TensorFlow 服务的请求失败

tensorflow - Google Tensorflow 是否支持 OpenCL

python - 如何在 TensorFlow while_loop 中赋值

python - 从 Keras 检查点加载

machine-learning - "Flatten"在Keras中的作用是什么?