tf.reduce_mean函数的作用是求平均值。第一个参数是一个集合,可以是列表、二维数组和多维数组。第二个参数指定在哪个维度上面求平均值。默认对所有的元素求平均。tf.reduce_mean
比如,下面是对所有元素求平均值:

x = tf.constant(
[[1., 1.], 
[2., 2.]])

tf.reduce_mean(x)  # 1.5

当指定第二个参数的时候,指定axis=0,表示沿着‘跨行’的方向求平均。对axis的理解可以参考一下这篇博文

m1 = tf.reduce_mean(x, axis=0)

结果为:[1.5, 1.5]

第二个参数不仅可以是一个数,也可以是一个数字,里面的数字表示指定所有的的轴的方向。
比如

xx = tf.constant([[[1., 1, 1],
                   [2., 2, 2]],

                  [[3, 3, 3],
                   [4, 4, 4]]])
m3 = tf.reduce_mean(xx, [0, 1]) # [2.5 2.5 2.5]

上面是一个三维数组, xx的shape为(2,2,3),可以想象为三个2x2的二维数组叠加在一起形成一个2x2x3的立体,也就是三个面叠加。现在的axis为[0, 1],表示对第1和第2轴的方向求平均值, 也就是分别对每一个面求平均。
第一个面为:
[[1., 2],
[3., 4]]
平均值为2.5

第二个面为
[[1., 2],
[3., 4]]
平均值为2.5

第三个面一样

完整的代码

import tensorflow as tf

x = tf.constant([[1., 1.],
                 [2., 2.]])
tf.reduce_mean(x)  # 1.5
m1 = tf.reduce_mean(x, axis=0)  # [1.5, 1.5]
m2 = tf.reduce_mean(x, 1)  # [1.,  2.]

xx = tf.constant([[[1., 1, 1],
                   [2., 2, 2]],

                  [[3, 3, 3],
                   [4, 4, 4]]])
m3 = tf.reduce_mean(xx, [0, 1]) # [2.5 2.5 2.5]


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(m1))
    print(sess.run(m2))

    print(xx.get_shape())
    print(sess.run(m3))

执行结果:
[1.5 1.5]
[1. 2.]
(2, 2, 3)
[2.5 2.5 2.5]

GitHub 加速计划 / te / tensorflow
184.54 K
74.12 K
下载
一个面向所有人的开源机器学习框架
最近提交(Master分支:1 个月前 )
a49e66f2 PiperOrigin-RevId: 663726708 2 个月前
91dac11a This test overrides disabled_backends, dropping the default value in the process. PiperOrigin-RevId: 663711155 2 个月前
Logo

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

更多推荐