TF2.0—tf.keras.losses.BinaryCrossentropy

文章目录

BinaryCrossentropy

tf.keras.losses.BinaryCrossentropy(
    from_logits=False, label_smoothing=0, reduction=losses_utils.ReductionV2.AUTO,
    name='binary_crossentropy'
)

描述

计算真实标签和预测标签之间的交叉熵损失
当只有两个标签类(假设为0和1)时,使用这个交叉熵损失。对于每个示例,每个预测都应该有一个浮点值

参数

from_logits
是否将y_pred解释为logit值的张量。
默认情况下,我们假设y_pred包含概率(即[0,1]中的值)

label_smoothing
浮点数在[0,1]中。
如果为0,则不会进行平滑处理。
当> 0时,我们将计算预测标签与真实标签的平滑版本之间的损失,其中平滑会将标签向0.5压缩。
label_smoothing的较大值对应于较重的平滑度

reduction
(可选)tf.keras.losses.reduction的类型,适用于损失。默认值为自动。
AUTO表示减少选项将由使用情况决定。

name
(可选)op的名称。默认为’ binary_crossenropy ’

调用的实例对象的参数

y_true : 真实值

y_pred : 预测值

sample_weight
可选的sample_weight用作损失的系数。
如果提供了标量,则损耗将简单地按给定值缩放。
如果sample_weight是大小[batch_size]的张量,则该批次的每个样本的总损失将由sample_weight向量中的相应元素重新缩放。
如果sample_weight的形状为[batch_size,d0,… dN-1](或可以广播为该形状),则y_pred的每个损失元素将通过sample_weight的相应值进行缩放。

实例

独立使用

y_true = [[0., 1.], [0., 0.]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
bce = tf.keras.losses.BinaryCrossentropy()
bce(y_true, y_pred).numpy()
0.815

# Calling with 'sample_weight'.
bce(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.458
 # Using 'sum' reduction type.
 bce = tf.keras.losses.BinaryCrossentropy(
     reduction=tf.keras.losses.Reduction.SUM)
 bce(y_true, y_pred).numpy()
 1.630
# Using 'none' reduction type.
bce = tf.keras.losses.BinaryCrossentropy(
    reduction=tf.keras.losses.Reduction.NONE)
bce(y_true, y_pred).numpy()

** tf.keras API中使用**

model.compile(optimizer='sgd', loss=tf.keras.losses.BinaryCrossentropy())

猜你喜欢

转载自blog.csdn.net/weixin_46649052/article/details/112707572