首页 > 解决方案 > tf.nn.sparse_softmax_cross_entropy_with_logits 的意外输出

问题描述

TensorFlow 文档tf.nn.sparse_softmax_cross_entropy_with_logits明确声明我不应该将 softmax 应用于此操作的输入:

此操作需要未缩放的 logits,因为它在内部对 logits 执行 softmax 以提高效率。不要用 softmax 的输出调用这个操作,因为它会产生不正确的结果。

但是,如果我在没有 softmax 的情况下使用交叉熵,它会给我带来意想不到的结果。根据CS231n 课程,CIFAR-10 的预期损失值约为 2.3:

例如,对于带有 Softmax 分类器的 CIFAR-10,我们预计初始损失为 2.302,因为我们预计每个类别的扩散概率为 0.1(因为有 10 个类别),而 Softmax 损失是负对数概率正确的类:-ln(0.1) = 2.302。

但是,如果没有 softmax,我会得到更大的值,例如 108.91984。

我到底做错了sparse_softmax_cross_entropy_with_logits什么?TF 代码如下所示。

import tensorflow as tf
import numpy as np
from tensorflow.python import keras


(_, _), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_test = np.reshape(x_test, [-1, 32, 32, 3])

y_test = np.reshape(y_test, (10000,))
y_test = y_test.astype(np.int32)

x = tf.placeholder(dtype=tf.float32, shape=(None, 32, 32, 3))
y = tf.placeholder(dtype=tf.int32, shape=(None,))

layer = tf.layers.Conv2D(filters=16, kernel_size=3)(x)
layer = tf.nn.relu(layer)
layer = tf.layers.Flatten()(layer)
layer = tf.layers.Dense(units=1000)(layer)
layer = tf.nn.relu(layer)
logits = tf.layers.Dense(units=10)(layer)

# If this line is uncommented I get expected value around 2.3
# logits = tf.nn.softmax(logits)

loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,
                                                      logits=logits)
loss = tf.reduce_mean(loss, name='cross_entropy')

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    res = sess.run(loss, feed_dict={x: x_test[0:256], y: y_test[0:256]})
    print("loss: ", res)
    # Expected output is value close to 2.3
    # Real outputs are 108.91984, 72.82324, etc.

标签: pythontensorflowneural-network

解决方案


问题不在行中

# If this line is uncommented I get expected value around 2.3
# logits = tf.nn.softmax(logits)

cifar10 数据集中的图像是 RGB 格式,因此像素值在 [0, 256) 范围内。如果你除以x_test255

x_test = np.reshape(x_test, [-1, 32, 32, 3]).astype(np.float32) / 255

这些值将重新调整为 [0,1]tf.nn.sparse_softmax_cross_entropy_with_logits并将返回预期值


推荐阅读