gpt4 book ai didi

tensorflow - 类别 CategoricalCrossentropy 与函数 categorical_crossentropy

转载 作者:行者123 更新时间:2023-12-04 10:45:03 30 4
gpt4 key购买 nike

在 Tensorflow2 中,我可以使用类 tf.keras.losses.CategoricalCrossentropy ( defined here ) 或函数 categorical_crossentropy ( defined here ) 计算标签和预测之间的交叉熵损失:

第一个代码是:

     loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
# ...
@tf.function
def train_step(samples, labels):
with tf.GradientTape() as tape:
predictions = model(samples)
loss = loss_object(labels, predictions)
#...


第二个更直接:
   @tf.function
def forward(features, training=False):
predictions = model.call(...)
loss = tf.losses.categorical_crossentropy(
y_true=features['label'],
y_pred=predictions)
return loss, predictions

数值结果是一样的。但是,我想知道是否有更有效的方法?或者更一般地说,根据某些特定情况应该使用哪一个?

请注意,对于任何类/函数 defined by the API 的问题可能都相同

最佳答案

来自 Keras documentation :

Note that all losses are available both via a class handle and via a function handle. The class handles enable you to pass configuration arguments to the constructor (e.g. loss_fn = CategoricalCrossentropy(from_logits=True)), and they perform reduction by default when used in a standalone way (see details below).

关于tensorflow - 类别 CategoricalCrossentropy 与函数 categorical_crossentropy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741879/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com