在Keras(Tensorflow后端)中使用binary_crossentropy损失

Min*_*ing 6 keras tensorflow

在Keras文档中的培训示例中,

https://keras.io/getting-started/sequential-model-guide/#training

使用binary_crossentropy,并在网络的最后一层添加了乙状结肠激活,但是是否有必要在网络的最后一层中加入乙状结肠?正如我在源代码中发现的:

def binary_crossentropy(output, target, from_logits=False):
  """Binary crossentropy between an output tensor and a target tensor.
  Arguments:
      output: A tensor.
      target: A tensor with the same shape as `output`.
      from_logits: Whether `output` is expected to be a logits tensor.
          By default, we consider that `output`
          encodes a probability distribution.
  Returns:
      A tensor.
  """
  # Note: nn.softmax_cross_entropy_with_logits
  # expects logits, Keras expects probabilities.
  if not from_logits:
    # transform back to logits
    epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
    output = clip_ops.clip_by_value(output, epsilon, 1 - epsilon)
    output = math_ops.log(output / (1 - output))
  return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)
Run Code Online (Sandbox Code Playgroud)

Keras在Tensorflow中调用sigmoid_cross_entropy_with_logits,但是在sigmoid_cross_entropy_with_logits函数中,会再次计算sigmoid(logits)

https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits

因此,我认为最后添加一个S形是没有道理的,但是似乎我在网上找到的Keras中所有二进制/多标签分类示例和教程最后都添加了S形。另外我不明白什么是

# Note: nn.softmax_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
Run Code Online (Sandbox Code Playgroud)

为什么Keras期望概率?它不使用nn.softmax_cross_entropy_with_logits函数吗?是否有意义?

谢谢。

Max*_*xim 3

你是对的,这正是正在发生的事情。我认为这是有历史原因的。

Keras 是在 Tensorflow 之前创建的,作为 theano 的包装器。在 theano 中,必须手动计算 sigmoid/softmax,然后应用交叉熵损失函数。Tensorflow 在一个融合运算中完成所有操作,但带有 sigmoid/softmax 层的 API 已被社区采用。

如果您想避免不必要的 logit <-> 概率转换,请使用呼binary_crossentropyfrom_logits=True,并且不要添加 sigmoid 层。