TensorFlow 2.0:sparse_categorical_crossentropy 和 SparseCategoricalCrossentropy 有什么区别?

TensorFlow 2.0: What is the difference between sparse_categorical_crossentropy and SparseCategoricalCrossentropy?

阅读 TensorFlow 2.0 的文档,我发现:

tf.keras.losses.sparse_categorical_crossentropy

tf.keras.losses.SparseCategoricalCrossentropy

他们在教程中的使用方式,他们的论点,他们的描述,他们似乎和我一样。两者有什么区别?

有none。如果您查看链接的文档,您可以在 GitHub 上找到源代码。两者都指向同一个对象:

def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
  """Categorical crossentropy with integer targets.

  if not from_logits:
    if (isinstance(output, (ops.EagerTensor, variables_module.Variable)) or
        output.op.type != 'Softmax'):
      epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype)
      output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_)
      output = math_ops.log(output)
      # ... blablabla

在:

tensorflow/python/keras/backend.py

比如前者(tf.keras.losses.sparse_categorical_crossentropy)是这样调用的:

def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1):
  return K.sparse_categorical_crossentropy(
      y_true, y_pred, from_logits=from_logits, axis=axis)

所以它指向另一个 tensorflow/python/keras/backend.py

一个是函数,一个是class。

第一个是functional版本,你求值的时候只会吐出loss的值。

第二个是class版本。您需要评估 class 本身的实例以获得损失值。

我相信你是对的,如果使用 keras,差别不大 api 唯一的区别是你编译模型的时间。

例如

model.compile(loss=tf.keras.losses.sparse_categorical_crossentropy)

vs

model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy())

注意 class 版本的额外括号,您需要传入一个 class 的实例。