python - 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.
解决方案
问题不在行中
# If this line is uncommented I get expected value around 2.3
# logits = tf.nn.softmax(logits)
cifar10 数据集中的图像是 RGB 格式,因此像素值在 [0, 256) 范围内。如果你除以x_test
255
x_test = np.reshape(x_test, [-1, 32, 32, 3]).astype(np.float32) / 255
这些值将重新调整为 [0,1]tf.nn.sparse_softmax_cross_entropy_with_logits
并将返回预期值
推荐阅读
- android - 如何解决“发生意外错误。请在 Google Play 商店应用程序发布中重试 (7515006A)'
- mysql - 传递给 ransacker 的 Active Admin 过滤器参数
- javascript - 在数组对象内映射数组
- python - os.path.join('BASE_DIR','template') 问题
- hibernate - 当我试图将我们的整个数据移动到新服务器时,我们面临着这个问题
- grails - 如何为简单的示例制作 Grails 子查询?
- java - 来自线程的方法调用在哪里运行?
- php - 有什么方法可以将 *this* 日期格式转换为 Ymd H:i:s?
- docker - 如何在 docker image centos 8 中配置 rsyslog
- css - 仅 CSS 动画会干扰移动设备上的 Bootstrap4 导航栏切换器