首页 > 解决方案 > tf.math.reduce_mean 和 tf.keras.metrics.Mean 有什么区别?

问题描述

我很困惑使用什么功能。他们看起来一样,做同样的工作。我知道 tf.keras.metrics.Mean 是公制,但我不能在其他地方使用它吗?

标签: pythontensorflowmachine-learningdeep-learning

解决方案


tf.keras.metrics.Mean 和 tf.math.reduce_mean 的功能略有不同。看例子

#tf.keras.metrics.Mean:CASE1

import tensorflow as tf
x = tf.constant([[1, 3, 5, 7],[1, 1, 0, 0]])
m = tf.keras.metrics.Mean()
m.update_state(x)
m.result().numpy()

输出:

1.886

#tf.keras.metrics.Mean:CASE2

m.reset_state()
m.update_state([1, 3, 5, 7], sample_weight=[1, 1, 0, 0])
m.result().numpy()

输出:

2.0

#tf.math.reduce_mean

#情况1

y = tf.reduce_mean(x)

输出:

tf.Tensor(2, shape=(), dtype=int32)

#案例2

y = tf.reduce_mean(x1,1)

输出:

tf.Tensor([4 0], shape=(2,), dtype=int32)

#案例3

y = tf.reduce_mean(x1,0)

输出:

tf.Tensor([1 2 2 3], shape=(4,), dtype=int32)

在 的情况下tf.math.reduce_mean,您会看到当 axis(numpy) 为 1 时,它计算 (1, 3, 5, 7) 和 (1,1,0,0) 的平均值,因此 1 定义了计算平均值的轴。当它为 0 时,将在 (1,1)、(3,1)、(5,0) 和 (7,0) 之间计算平均值,依此类推。


推荐阅读