tf.keras.losses实例是用来计算真实标签( y_true )和预测标签之间( y_pred )的loss损失。

参数:from_logits、label_smoothing...

参数的解释请移驾此处tf.keras.losses参数详解

函数方法

1、from_config(config)

 实例化一个损失函数,返回一个损失函数实例

cce = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2,reduction=tf.keras.losses.Reduction.SUM,name='sss')
bce=tf.keras.losses.BinaryCrossentropy()
bce=bce.from_config(cce.get_config()) #参数为字典,{'reduction': 'sum', 'name': 'sss', 'from_logits': False, 'label_smoothing': 0.2}

 2、get_config()

返回 Loss 实例的配置字典 

cce = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2,reduction=tf.keras.losses.Reduction.SUM,name='sss')
print(cce.get_config())
#输出:{'reduction': 'sum', 'name': 'sss', 'from_logits': False, 'label_smoothing': 0.2}

3、 __call__(y_true, y_pred, sample_weight=None)

参数:

前两者为两个标签

sample_weight:可选的 sample_weight 缩放损失的系数。 如果是标量,则损失均按该值进行缩放。 如果 sample_weight 是大小为 [batch_size] 的张量,则每个batch的样本的总损失由 sample_weight 向量中的相应元素重新缩放。 如果sample_weight的shape是[batch_size, d0, .. dN-1],那么y_pred的每一个loss元素都按照sample_weight的对应值进行缩放。(注意 dN-1值所有损失函数都减少一维,通常轴=-1计算损失。)

调用时,以实例化的loss函数传递参数即可:

import tensorflow as tf
import math
y_true = [[0, 1], [0, 0]]  #二分类,2个batch,每个batch 2个样本
y_pred = [[0.6, 0.3], [0.2, 0.8]]
bce = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
print(bce(y_true, y_pred).numpy()) 
#输出:[1.0601315 0.9162904]每个batch的Loss损失
a = -0*math.log(0.6)-1*math.log(1-0.6)
b = -1*math.log(0.3)-0*math.log(1-0.3)
c = -0*math.log(0.2)-1*math.log(1-0.2)
d = -0*math.log(0.8)-1*math.log(1-0.8)
print((a+b)/2,(c+d)/2,0.8*(a+b)/2,0.2*(c+d)/2)
#输出:1.0601317681000455 0.9162907318741551 0.8481054144800364 0.18325814637483104
#后两个按0.8和0.2缩放后
print(bce(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy())
#输出:[0.84810525 0.18325809]

tf.keras.losses.BinaryCrossentropy

二元交叉熵

函数原型

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

 函数计算方式,N指的是一个中括号 [ ] 之间的数目,即在二分类中指中括号中样本的个数:

Loss=-\frac{1}{N}\sum_{i=1}^{N}y_{i}\cdot log\left ( p(x_{i}) \right )+(1-y_{i})\cdot log\left ( 1-p(x_{i}) \right )

tf.keras.losses.CategoricalCrossentropy

分类交叉熵

tf.keras.losses.CategoricalCrossentropy(
    from_logits=False, label_smoothing=0, axis=-1,
    reduction=losses_utils.ReductionV2.AUTO,
    name='categorical_crossentropy'
)

计算方式,K指的是一个中括号 [ ] 之间的数目,即在多分类中指类别的个数,Loss即为一个样本的损失:

Loss=-\sum_{j=1}^{K} y_{j}\cdot ln\left ( p(x_{j}) \right )

当有两个以上标签类别时,使用此交叉熵损失函数。y_true 标签以 one_hot 形式表示。 即[0, 1, 0]表示该值属于第1类。对应的为SparseCategoricalCrossentropy,稀疏分类交叉熵,这个函数y_true 标签以 数值形式表示,如 1 表示第1类。

注:ValueError 如果 sample_weight 的形状无效

tf.keras.losses.CategoricalHinge

分类铰链损失

tf.keras.losses.CategoricalHinge(
    reduction=losses_utils.ReductionV2.AUTO, name='categorical_hinge'
)

计算方法,计算是在一个中括号内进行的,按位进行计算:

Loss = MAX(neg - pos + 1, 0) 其中 neg=MAX((1-y_true)*y_pred) 和 pos=sum(y_true*y_pred)

和 tf.keras.losses.categorical_hinge(y_true, y_pred)函数相同作用,但后者参数是两个标签,且和reduction为NONE的情况一致

tf.keras.losses.CosineSimilarity

计算标签和预测之间的余弦相似度。

tf.keras.losses.CosineSimilarity(
    axis=-1, reduction=losses_utils.ReductionV2.AUTO,
    name='cosine_similarity'
)

Loss值在-1和1之间。当它是-1和0之间的负数时,0表示正交性,值越接近-1表示相似性越大。越接近 1 表示差异越大。 如果 y_true 或 y_pred 是零向量,则无论预测和目标之间的接近程度如何,余弦相似度都将为 0。

import tensorflow as tf
import numpy as np
y_true = [[0., 1.], [1., 1.]]
y_pred = [[1., 0.], [1., 1.]]

cosine_loss = tf.keras.losses.CosineSimilarity(reduction=tf.keras.losses.Reduction.NONE)
a=tf.math.l2_normalize(y_true,axis=1)# [[0., 1.], [1./1.414, 1./1.414]]
b=tf.math.l2_normalize(y_pred,axis=1)# [[1., 0.], [1./1.414, 1./1.414]]
loss=np.array(a*b).sum(axis=1)   # l2_norm(y_true)*l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]],loss=[0., 1]
print(loss,sum(loss)/2)   # loss = mean([0., 1])= -([0., 1]) / 2 =  - 0.5
#输出:[0.         0.99999994]  0.4999999701976776
cosine_loss = tf.keras.losses.CosineSimilarity()  #Reduction=AUTO,即为sum(loss)/2
print(cosine_loss(y_true, y_pred).numpy())
#输出:-0.49999997  正常情况下应为0.5,但TensorFlow在计算根号2等无理数时取了精度

函数和tf.keras.losses.cosine_similarity(y_true, y_pred, axis=-1)作用一致,后者参数是两个标签和对应的axis

tf.keras.losses.Hinge

铰链损失

tf.keras.losses.Hinge(
    reduction=losses_utils.ReductionV2.AUTO, name='hinge'
)

计算公式:loss = maximum(1 - y_true * y_pred, 0),其中y_true 值是0、1标签,则会转换为 -1 或 1。

函数和tf.keras.metrics.hinge(y_true, y_pred)作用一致,后者参数为两个标签,且和reduction为NONE时一致。

tf.keras.losses.Huber

tf.keras.losses.Huber(
    delta=1.0, reduction=losses_utils.ReductionV2.AUTO, name='huber_loss'
)

参数:delta:浮点数,Huber 损失函数从二次变为线性的点。

计算原理:

loss = 0.5 * x^2                  if |x| <= d
loss = 0.5 * d^2 + d * (|x| - d)  if |x| > d

 x 为误差 e=y_true-y_pred中的数,d为delta,在中括号 [ ] 内逐位计算后求平均,为一个 [ ] 内的损失Loss。

import tensorflow as tf
import numpy as np
y_true = [[0, 1], [0, 0]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
h = tf.keras.losses.Huber(reduction=tf.keras.losses.Reduction.NONE)
print(h(y_true, y_pred).numpy())# np.array(y_true)-np.array(y_pred)=[[-0.6  0.6],[-0.4 -0.6]]
#输出:[0.18       0.13000001]...和官方API上面的不太一样,不知道为什么有0.00000001,其他的例子实验后也会有
#loss=0.5x^2,|x|<=1    loss=0.5*1^2+0.5*(|x|-1) ,|x|>1
a=0.5*0.6*0.6
b=0.5*0.6*0.6
c=0.5*0.4*0.4
d=0.5*0.6*0.6
print((a+b)/2,(c+d)/2)#输出:0.18 0.13

tf.keras.losses.KLDivergence

相对熵

计算 y_true 和 y_pred 之间的 Kullback-Leibler 散度损失。

tf.keras.losses.KLDivergence(
    reduction=losses_utils.ReductionV2.AUTO, name='kl_divergence'
)

计算方法:

Loss =\sum_{i=1}^{N}Ytrue_{i} * ln(\frac{Ytrue_{i} }{Ypred_{i}} )

 y_true或者y_pred中出现0则以0.0000001计算该项(代入实验结果基本吻合)

import tensorflow as tf
import math
y_true = [[0, 1]]
y_pred = [[0.6, 0]]
kl = tf.keras.losses.KLDivergence(reduction=tf.keras.losses.Reduction.NONE)
print(kl(y_true, y_pred).numpy())   #[16.118093]
print(math.log(1/0.0000001)+0.0000001*math.log(0.0000001/0.6)) #16.118094090231317

tf.keras.losses.LogCosh

计算预测误差的双曲余弦的对数。

tf.keras.losses.LogCosh(
    reduction=losses_utils.ReductionV2.AUTO, name='log_cosh'
)

计算公式:

Logcosh =\frac{1}{N}\sum_{i=1}^{N} ln(\frac{e^{x_{i}} + e^{-x_{i}}}{2})

logcosh = ln((exp(x) + exp(-x))/2),其中 x 是误差 y_pred - y_true,在中括号 [ ] 内逐位计算后求平均。

import tensorflow as tf
import math
import numpy as np
y_true = np.array([0.1, 1.6])
y_pred = np.array([1., 1.])
l = tf.keras.losses.LogCosh(tf.keras.losses.Reduction.NONE)
print(l(y_true, y_pred).numpy()) #0.26498284935951233
# y_true-y_pred=[-0.9  0.6]
a=math.log((math.pow(math.e,-0.9)+math.pow(math.e,0.9))/2)
b=math.log((math.pow(math.e,-0.6)+math.pow(math.e,0.6))/2)
print ((a+b)/2)  #0.2649828583721073

函数和tf.keras.losses.log_cosh(y_true, y_pred)含义一致。

tf.keras.losses.MeanAbsoluteError

计算标签和预测之间绝对差异的平均值。

tf.keras.losses.MeanAbsoluteError(
    reduction=losses_utils.ReductionV2.AUTO, name='mean_absolute_error'
)

计算公式,计算是在 [ ] 内进行的:

Loss= \frac{1}{N} \sum_{i=1}^{N}|(Ytrue_i - Ypred_i)|

tf.keras.losses.MeanAbsolutePercentageError

计算 y_true 和 y_pred 之间的平均绝对百分比误差

tf.keras.losses.MeanAbsolutePercentageError(
    reduction=losses_utils.ReductionV2.AUTO,
    name='mean_absolute_percentage_error'
)

计算公式,计算是在 [ ] 内进行的:

loss = \frac{1}{N}\sum_{i=1}^{N}100\cdot \frac{|(Ytrue_{i} - Ypred_{i})|}{Ytrue_{i}}

y_true中含有0元素的依旧以0.0000001代替,在中括号 [ ] 内逐位计算后求平均得到Loss。

tf.keras.losses.MeanSquaredError

计算标签和预测之间的误差平方均值。

tf.keras.losses.MeanSquaredError(
    reduction=losses_utils.ReductionV2.AUTO, name='mean_squared_error'
)

计算公式,计算是在 [ ] 内进行的:

loss = \frac{1}{N}\sum_{i=1}^{N}(Ytrue_{i} - Ypred_{i})^{2}

tf.keras.losses.MeanSquaredLogarithmicError

计算 y_true 和 y_pred 之间的对数误差均方值。

tf.keras.losses.MeanSquaredLogarithmicError(
    reduction=losses_utils.ReductionV2.AUTO,
    name='mean_squared_logarithmic_error'
)

计算公式,计算是在 [ ] 内进行的:

Loss = \frac{1}{N}\sum_{i=1}^{N}(ln(Ytrue_{i}+1) - ln(Ypred_{i}+1))^{2}

tf.keras.losses.Poisson

计算 y_true 和 y_pred 之间的Poisson损失

tf.keras.losses.Poisson(
    reduction=losses_utils.ReductionV2.AUTO, name='poisson'
)

计算公式,计算是在 [ ] 内进行的:

 Loss = \frac{1}{N}\sum_{i=1}^{N}(Ypred_{i}-Ytrue_{i}\cdot ln(Ypred_{i}))

tf.keras.losses.SparseCategoricalCrossentropy

计算标签和预测之间的交叉熵损失。

tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=False, reduction=losses_utils.ReductionV2.AUTO,
    name='sparse_categorical_crossentropy'
)

y_true 的形状为 [batch_size],y_pred 的形状为 [batch_size, num_classes]。原理和CategoricalCrossentropy相同,只是这里的y_true是数字,CategoricalCrossentropy是one-hot形式,如,y_true = [1, 2] 和 y_true = [[0, 1, 0], [0, 0, 1]]

tf.keras.losses.SquaredHinge

计算 y_true 和 y_pred 之间的平方铰链损失。

tf.keras.losses.SquaredHinge(
    reduction=losses_utils.ReductionV2.AUTO, name='squared_hinge'
)

计算公式,计算是在 [ ] 内进行的:

Loss = \frac{1}{N}\sum_{i=1}^{N}(MAX(1-Ytrue_{i}\cdot Ypred_{i},0))^{2}

其中y_true中的0会被转化为-1。

tf.keras.losses.get

检索 作为函数/损失类实例的Keras 损失函数。

tf.keras.losses.get(
    identifier
)

参数:损失函数或损失类的字符串名称。除此之外:还可以是包含 class_name 和 config 的 dict ,并以此指定此函数的损失配置。其中 class_name 必须映射到 Loss 类,返回值为loss实例

import tensorflow as tf
loss = tf.keras.losses.get("categorical_crossentropy")
print(type(loss)) #<class 'function'>
loss = tf.keras.losses.get("CategoricalCrossentropy")
print(type(loss)) #<class 'keras.losses.CategoricalCrossentropy'>
identifier = {"class_name": "CategoricalCrossentropy","config": {"from_logits": True} }
loss = tf.keras.losses.get(identifier)
print(type(loss)) #<class 'keras.losses.CategoricalCrossentropy'>

无函数方法 

tf.keras.losses.serialize

序列化损失函数或损失实例。

tf.keras.losses.serialize(
    loss
)

参数:损失函数实例

返回:包含class_name、config的字典,例如:{'class_name': 'LogCosh', 'config': {'reduction': 'none', 'name': 'log_cosh'}}

无函数方法

tf.keras.losses.deserialize

反序列化序列化的损失类/函数实例。

tf.keras.losses.deserialize(
    name, custom_objects=None
)

参数:

name:tf.keras.losses.serialize的返回dict

custom_object:可选字典,该字典将名称(字符串)映射到要自定义对象(类和函数)

无函数方法

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐