Keras 2 API 文档 / 损失 / 回归损失

回归损失

[源代码]

MeanSquaredError

tf_keras.losses.MeanSquaredError(reduction="auto", name="mean_squared_error")

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

loss = mean(square(y_true - y_pred))

独立使用

>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [1., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> mse = tf.keras.losses.MeanSquaredError()
>>> mse(y_true, y_pred).numpy()
0.5
>>> # Calling with 'sample_weight'.
>>> mse(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.25
>>> # Using 'sum' reduction type.
>>> mse = tf.keras.losses.MeanSquaredError(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> mse(y_true, y_pred).numpy()
1.0
>>> # Using 'none' reduction type.
>>> mse = tf.keras.losses.MeanSquaredError(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> mse(y_true, y_pred).numpy()
array([0.5, 0.5], dtype=float32)

compile() API 一起使用

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

[源代码]

MeanAbsoluteError

tf_keras.losses.MeanAbsoluteError(reduction="auto", name="mean_absolute_error")

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

loss = mean(abs(y_true - y_pred))

独立使用

>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [1., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> mae = tf.keras.losses.MeanAbsoluteError()
>>> mae(y_true, y_pred).numpy()
0.5
>>> # Calling with 'sample_weight'.
>>> mae(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.25
>>> # Using 'sum' reduction type.
>>> mae = tf.keras.losses.MeanAbsoluteError(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> mae(y_true, y_pred).numpy()
1.0
>>> # Using 'none' reduction type.
>>> mae = tf.keras.losses.MeanAbsoluteError(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> mae(y_true, y_pred).numpy()
array([0.5, 0.5], dtype=float32)

compile() API 一起使用

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

[源代码]

MeanAbsolutePercentageError

tf_keras.losses.MeanAbsolutePercentageError(
    reduction="auto", name="mean_absolute_percentage_error"
)

计算 y_truey_pred 之间的平均绝对百分比误差。

公式

loss = 100 * abs((y_true - y_pred) / y_true)

请注意,为了避免除以零,分母中添加了一个小的 epsilon 值。

独立使用

>>> y_true = [[2., 1.], [2., 3.]]
>>> y_pred = [[1., 1.], [1., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> mape = tf.keras.losses.MeanAbsolutePercentageError()
>>> mape(y_true, y_pred).numpy()
50.
>>> # Calling with 'sample_weight'.
>>> mape(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
20.
>>> # Using 'sum' reduction type.
>>> mape = tf.keras.losses.MeanAbsolutePercentageError(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> mape(y_true, y_pred).numpy()
100.
>>> # Using 'none' reduction type.
>>> mape = tf.keras.losses.MeanAbsolutePercentageError(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> mape(y_true, y_pred).numpy()
array([25., 75.], dtype=float32)

compile() API 一起使用

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

[源代码]

MeanSquaredLogarithmicError

tf_keras.losses.MeanSquaredLogarithmicError(
    reduction="auto", name="mean_squared_logarithmic_error"
)

计算 y_truey_pred 之间的均方对数误差。

loss = square(log(y_true + 1.) - log(y_pred + 1.))

独立使用

>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [1., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> msle = tf.keras.losses.MeanSquaredLogarithmicError()
>>> msle(y_true, y_pred).numpy()
0.240
>>> # Calling with 'sample_weight'.
>>> msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
0.120
>>> # Using 'sum' reduction type.
>>> msle = tf.keras.losses.MeanSquaredLogarithmicError(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> msle(y_true, y_pred).numpy()
0.480
>>> # Using 'none' reduction type.
>>> msle = tf.keras.losses.MeanSquaredLogarithmicError(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> msle(y_true, y_pred).numpy()
array([0.240, 0.240], dtype=float32)

compile() API 一起使用

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

[源代码]

CosineSimilarity

tf_keras.losses.CosineSimilarity(axis=-1, reduction="auto", name="cosine_similarity")

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

请注意,它是一个介于 -1 和 1 之间的数字。当它是一个介于 -1 和 0 之间的负数时,0 表示正交,更接近 -1 的值表示更大的相似度。更接近 1 的值表示更大的差异。这使得它可用作损失函数,在您尝试最大化预测和目标之间的接近度的设置中。如果 y_truey_pred 是零向量,则无论预测和目标之间的接近度如何,余弦相似度都将为 0。

loss = -sum(l2_norm(y_true) * l2_norm(y_pred))

独立使用

>>> y_true = [[0., 1.], [1., 1.]]
>>> y_pred = [[1., 0.], [1., 1.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1)
>>> # l2_norm(y_true) = [[0., 1.], [1./1.414, 1./1.414]]
>>> # l2_norm(y_pred) = [[1., 0.], [1./1.414, 1./1.414]]
>>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
>>> # loss = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
>>> #       = -((0. + 0.) +  (0.5 + 0.5)) / 2
>>> cosine_loss(y_true, y_pred).numpy()
-0.5
>>> # Calling with 'sample_weight'.
>>> cosine_loss(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
-0.0999
>>> # Using 'sum' reduction type.
>>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
...     reduction=tf.keras.losses.Reduction.SUM)
>>> cosine_loss(y_true, y_pred).numpy()
-0.999
>>> # Using 'none' reduction type.
>>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
...     reduction=tf.keras.losses.Reduction.NONE)
>>> cosine_loss(y_true, y_pred).numpy()
array([-0., -0.999], dtype=float32)

compile() API 一起使用

model.compile(optimizer='sgd',
              loss=tf.keras.losses.CosineSimilarity(axis=1))

参数

  • axis:计算余弦相似度的轴(特征轴)。默认为 -1。
  • reduction:应用于损失的 tf.keras.losses.Reduction 类型。默认值为 AUTOAUTO 表示减少选项将由使用上下文确定。对于几乎所有情况,这默认为 SUM_OVER_BATCH_SIZE。在 tf.distribute.Strategy 下使用时,除了通过 Model.compile()Model.fit() 使用外,使用 AUTOSUM_OVER_BATCH_SIZE 将引发错误。有关更多详细信息,请参阅此自定义训练教程
  • name:实例的可选名称。默认为 'cosine_similarity'。

[源代码]

mean_squared_error 函数

tf_keras.losses.mean_squared_error(y_true, y_pred)

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

在计算输入之间的平方距离后,返回最后一个维度上的平均值。

loss = mean(square(y_true - y_pred), axis=-1)

独立使用

>>> y_true = np.random.randint(0, 2, size=(2, 3))
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = tf.keras.losses.mean_squared_error(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> assert np.array_equal(
...     loss.numpy(), np.mean(np.square(y_true - y_pred), axis=-1))

参数

  • y_true:真实值。形状 = [batch_size, d0, .. dN]
  • y_pred:预测值。形状 = [batch_size, d0, .. dN]

返回值

均方误差值。形状 = [batch_size, d0, .. dN-1]


[源代码]

mean_absolute_error 函数

tf_keras.losses.mean_absolute_error(y_true, y_pred)

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

loss = mean(abs(y_true - y_pred), axis=-1)

独立使用

>>> y_true = np.random.randint(0, 2, size=(2, 3))
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = tf.keras.losses.mean_absolute_error(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> assert np.array_equal(
...     loss.numpy(), np.mean(np.abs(y_true - y_pred), axis=-1))

参数

  • y_true:真实值。形状 = [batch_size, d0, .. dN]
  • y_pred:预测值。形状 = [batch_size, d0, .. dN]

返回值

平均绝对误差值。形状 = [batch_size, d0, .. dN-1]


[源代码]

mean_absolute_percentage_error 函数

tf_keras.losses.mean_absolute_percentage_error(y_true, y_pred)

计算 y_truey_pred 之间的平均绝对百分比误差。

loss = 100 * mean(abs((y_true - y_pred) / y_true), axis=-1)

独立使用

>>> y_true = np.random.random(size=(2, 3))
>>> y_true = np.maximum(y_true, 1e-7)  # Prevent division by zero
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = tf.keras.losses.mean_absolute_percentage_error(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> assert np.array_equal(
...     loss.numpy(),
...     100. * np.mean(np.abs((y_true - y_pred) / y_true), axis=-1))

参数

  • y_true:真实值。形状 = [batch_size, d0, .. dN]
  • y_pred:预测值。形状 = [batch_size, d0, .. dN]

返回值

平均绝对百分比误差值。形状 = [batch_size, d0, .. dN-1]


[源代码]

mean_squared_logarithmic_error 函数

tf_keras.losses.mean_squared_logarithmic_error(y_true, y_pred)

计算 y_truey_pred 之间的均方对数误差。

loss = mean(square(log(y_true + 1) - log(y_pred + 1)), axis=-1)

独立使用

>>> y_true = np.random.randint(0, 2, size=(2, 3))
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = tf.keras.losses.mean_squared_logarithmic_error(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> y_true = np.maximum(y_true, 1e-7)
>>> y_pred = np.maximum(y_pred, 1e-7)
>>> assert np.allclose(
...     loss.numpy(),
...     np.mean(
...         np.square(np.log(y_true + 1.) - np.log(y_pred + 1.)), axis=-1))

参数

  • y_true:真实值。形状 = [batch_size, d0, .. dN]
  • y_pred:预测值。形状 = [batch_size, d0, .. dN]

返回值

均方对数误差值。形状 = [batch_size, d0, .. dN-1]


[源代码]

cosine_similarity 函数

tf_keras.losses.cosine_similarity(y_true, y_pred, axis=-1)

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

请注意,它是一个介于 -1 和 1 之间的数字。当它是一个介于 -1 和 0 之间的负数时,0 表示正交,更接近 -1 的值表示更大的相似度。更接近 1 的值表示更大的差异。这使得它可用作损失函数,在您尝试最大化预测和目标之间的接近度的设置中。如果 y_truey_pred 是零向量,则无论预测和目标之间的接近度如何,余弦相似度都将为 0。

loss = -sum(l2_norm(y_true) * l2_norm(y_pred))

独立使用

>>> y_true = [[0., 1.], [1., 1.], [1., 1.]]
>>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]]
>>> loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1)
>>> loss.numpy()
array([-0., -0.999, 0.999], dtype=float32)

参数

  • y_true:真实目标的张量。
  • y_pred:预测目标的张量。
  • axis:确定相似度的轴。

返回值

余弦相似度张量。


[源代码]

Huber

tf_keras.losses.Huber(delta=1.0, reduction="auto", name="huber_loss")

计算 y_truey_pred 之间的 Huber 损失。

对于 error = y_true - y_pred 中的每个值 x

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

其中 d 是 delta。参见:https://en.wikipedia.org/wiki/Huber_loss

独立使用

>>> y_true = [[0, 1], [0, 0]]
>>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> h = tf.keras.losses.Huber()
>>> h(y_true, y_pred).numpy()
0.155
>>> # Calling with 'sample_weight'.
>>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.09
>>> # Using 'sum' reduction type.
>>> h = tf.keras.losses.Huber(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> h(y_true, y_pred).numpy()
0.31
>>> # Using 'none' reduction type.
>>> h = tf.keras.losses.Huber(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> h(y_true, y_pred).numpy()
array([0.18, 0.13], dtype=float32)

compile() API 一起使用

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

[源代码]

huber 函数

tf_keras.losses.huber(y_true, y_pred, delta=1.0)

计算 Huber 损失值。

对于 error = y_true - y_pred 中的每个值 x

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

其中 d 是 delta。参见:https://en.wikipedia.org/wiki/Huber_loss

参数

  • y_true:真实目标的张量。
  • y_pred:预测目标的张量。
  • delta:一个浮点数,Huber 损失函数从二次函数变为线性函数的点。

返回值

每个样本包含一个标量损失条目的张量。


[源代码]

LogCosh

tf_keras.losses.LogCosh(reduction="auto", name="log_cosh")

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

logcosh = log((exp(x) + exp(-x))/2),其中 x 是误差 y_pred - y_true

独立使用

>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [0., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> l = tf.keras.losses.LogCosh()
>>> l(y_true, y_pred).numpy()
0.108
>>> # Calling with 'sample_weight'.
>>> l(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
0.087
>>> # Using 'sum' reduction type.
>>> l = tf.keras.losses.LogCosh(
...     reduction=tf.keras.losses.Reduction.SUM)
>>> l(y_true, y_pred).numpy()
0.217
>>> # Using 'none' reduction type.
>>> l = tf.keras.losses.LogCosh(
...     reduction=tf.keras.losses.Reduction.NONE)
>>> l(y_true, y_pred).numpy()
array([0.217, 0.], dtype=float32)

compile() API 一起使用

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

[源代码]

log_cosh 函数

tf_keras.losses.log_cosh(y_true, y_pred)

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

对于小的 xlog(cosh(x)) 大约等于 (x ** 2) / 2,对于大的 x,大约等于 abs(x) - log(2)。这意味着 'logcosh' 主要像均方误差一样工作,但不会受到偶尔出现的完全错误预测的强烈影响。

独立使用

>>> y_true = np.random.random(size=(2, 3))
>>> y_pred = np.random.random(size=(2, 3))
>>> loss = tf.keras.losses.logcosh(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> x = y_pred - y_true
>>> assert np.allclose(
...     loss.numpy(),
...     np.mean(x + np.log(np.exp(-2. * x) + 1.) - tf.math.log(2.),
...             axis=-1),
...     atol=1e-5)

参数

  • y_true:真实值。形状 = [batch_size, d0, .. dN]
  • y_pred:预测值。形状 = [batch_size, d0, .. dN]

返回值

Logcosh 误差值。形状 = [batch_size, d0, .. dN-1]