CategoricalCrossentropy 和 categorical_crossentropy 都是类别交叉熵损失函数,前者是类的实现形式,后者是函数的实现形式。CategoricalCrossentropy 调用的还是categorical_crossentropy 的实现。
y_true = [[0, 1, 0], [0, 0, 1]]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred)
assert loss.shape == (2,)
print(loss.numpy())#[0.05129331 2.3025851 ]
loss1 = -( 0*tf.math.log(0.05) + 1*tf.math.log(0.95) +0*tf.math.log(0) )
print(loss1)#tf.Tensor(0.051293306, shape=(), dtype=float32)
loss2 = -(0*tf.math.log(0.1) + 0*tf.math.log(0.8) +1*tf.math.log(0.1))
print(loss2)#tf.Tensor(2.3025851, shape=(), dtype=float32)