为什么网络的输出在使用 softmax_cross_entropy_with_logits 时不能通过 softmax?

san*_*oxj 2 python machine-learning neural-network tensorflow

我想使用tensorflow内置的交叉熵函数。但是,在文档中,我正在阅读

不要用 softmax 的输出调用这个操作,因为它会产生不正确的结果。

https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits

就像经常做的那样,我在最后一个输出层中使用了 softmax 激活,但是:

result = tf.layers.dense(input=dropout, classes_num, tf.nn.softmax)
Run Code Online (Sandbox Code Playgroud)

因此,使用此功能是错误的,还是文档不正确?我不明白这一点,我将感谢一个简短的解释。(那么哪个 TensorFlow 成本函数适合用于 softmax 输出层?)

nes*_*uno 5

由于在tf.nn.softmax_cross_entropy_with_logits内部计算其输入的 softmax(以数值稳定的方式),您必须定义您的网络才能使用线性激活函数:tf.identity

result = tf.layers.dense(input=dropout, classes_num, tf.identity)
Run Code Online (Sandbox Code Playgroud)

此外,一旦网络经过训练并且您想使用该模型进行推理,您必须用 softmax 替换激活。

因此,在您的代码中引入一个is_trainingpython 布尔变量,并在您训练或测试时使用它来更改模型定义。

result = tf.layers.dense(input=dropout, classes_num,
             tf.identity if is_training else tf.nn.softmax)
Run Code Online (Sandbox Code Playgroud)