Keras 如何处理分类交叉熵的 log(0)?

How does Keras deal with log(0) for categorical cross entropy?

我有一个神经网络,在 MNIST 上训练,使用分类交叉熵作为它的损失函数。

出于理论目的,我的输出层是 ReLu。因此很多 它的输出是 0.

现在我偶然发现了以下问题:

为什么我没有得到很多错误,因为肯定会有很多 零在我的输出中,我将记录它。

这里,为了方便,分类交叉熵的公式。

它没有记录在 https://keras.io/losses/#categorical_crossentropy 中,它似乎取决于后端,但我很确定他们不会生成 log y,而是生成 log(y+ epsilon),其中 epsilon 很小常量以防止 log(0).

Keras 使用常量 1e-7 and adds this constant again to the clipped output before performing the logarithm operation as defined here 裁剪网络输出。

  epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype)
  output = clip_ops.clip_by_value(output, epsilon_, 1. - epsilon_)

  # Compute cross entropy from probabilities.
  bce = target * math_ops.log(output + epsilon())
  bce += (1 - target) * math_ops.log(1 - output + epsilon())
  return -bce

为什么 Keras 再次将 epsilon 添加到裁剪输出对我来说是个谜。