一文总结Keras的loss函数和metrics函数

Loss函数

定义:

keras.losses.mean_squared_error(y_true, y_pred)

用法很简单,就是计算均方误差平均值,例如

loss_fn = keras.losses.mean_squared_error
a1 = tf.constant([1,1,1,1])
a2 = tf.constant([2,2,2,2])
loss_fn(a1,a2)
<tf.Tensor: id=718367, shape=(), dtype=int32, numpy=1>

Metrics函数

Metrics函数也用于计算误差,但是功能比Loss函数要复杂。

定义

tf.keras.metrics.Mean(
    name='mean', dtype=None
)

这个定义过于简单,举例说明

mean_loss([1, 3, 5, 7])
mean_loss([1, 3, 5, 7])
mean_loss([1, 1, 1, 1])
mean_loss([2,2])

输出结果

<tf.Tensor: id=718929, shape=(), dtype=float32, numpy=2.857143>

这个结果等价于

np.mean([1, 3, 5, 7, 1, 3, 5, 7, 1, 1, 1, 1, 2, 2])

这是因为Metrics函数是状态函数,在神经网络训练过程中会持续不断地更新状态,是有记忆的。因为Metrics函数还带有下面几个Methods

reset_states()

Resets all of the metric state variables.

This function is called between epochs/steps, when a metric is evaluated during training.

result()

Computes and returns the metric value tensor.

Result computation is an idempotent operation that simply calculates the metric value using the state variables

update_state(
    values, sample_weight=None
)

Accumulates statistics for computing the reduction metric.

另外注意,Loss函数和Metrics函数的调用形式,

loss_fn = keras.losses.mean_squared_error
mean_loss = keras.metrics.Mean()

mean_loss(1)等价于keras.metrics.Mean()(1),而不是keras.metrics.Mean(1),这个从keras.metrics.Mean函数的定义可以看出。

但是必须先令生成一个实例mean_loss=keras.metrics.Mean(),而不能直接使用keras.metrics.Mean()本身。