tf.reduce_mean(#沿着axis维度求平均
input_tensor,#输入
axis=None,#表示在哪个维度进行sum操作。
keep_dims=False,#当值为False时,相当于执行完后原始数据就会减少一个维度;而为True时,表示要保留原始数据的维度。
name=None,
reduction_indices=None,#axis的废弃的名称。 )
1、关键是前两个参数,它可等价于np.mean,但np中有类型参数,默认为float64,而tf中的类型由输入的tensor类型决定;
(1)x = tf.constant([1, 0, 1, 0])
tf.reduce_mean(x) # 0(输入tensor全是整数,所以默认为整型)
(2)y = tf.constant([1., 0., 1., 0.])
tf.reduce_mean(y) # 0.5(输入tensor全是浮点,所以默认为浮点型)
2、如果没有指定axis,则默认对所有元素求平均;axis=0,对每一列取平均值;axis=1,对每一行取平均值 ;
x = tf.constant([[1., 1.], [2., 2.]])
(1)tf.reduce_mean(x) # 1.5等价于tf.reduce_mean(x,[0,1])
(2)tf.reduce_mean(x, 0) # [1.5 1.5]
(3)tf.reduce_mean(x, 1) # [1. 2.]
3、keep_dims=True时,表示要保留原始数据的维度;
(4)tf.reduce_mean(x, keep_dims=True) # [[1.5]]
(5)tf.reduce_mean(x, 0, keep_dims=True) # [[1.5 1.5]]
(6)tf.reduce_mean(x, 1, keep_dims=True) # [[1.]
[2.]]
4、当数据维度为3时;
x = tf.constant([[[1., 1, 1], [2., 2, 2]], [[3, 3, 3], [4, 4, 4]]])
(1)tf.reduce_mean(x, 0) # [[2 2 2][3 3 3]]
(2)tf.reduce_mean(x, 1) # [[1.5 1.5 1.5][3.5 3.5 3.5]]
(3)tf.reduce_mean(x, 2) # [[1. 2.][3. 4.]]
(4)tf.reduce_mean(x, [0, 1]) # [2.5 2.5 2.5]
(输入维度[2,2,3],下面指定沿[0,1]维度取平均,首先对第1维度取平均,得到[[2,2,2],[3,3,3]],然后对第2维度取平均,得[2.5,2.5,2.5])
(5)tf.reduce_mean(x, [0, 2]) # [2. 3.]
(输入维度[2,2,3],下面指定沿[0,2]维度取平均,首先对第1维度取平均,得到[[2,2,2],[3,3,3]],然后对第3 维度取平均,得[2. 3.]
(6)tf.reduce_mean(x, [1, 2]) # [2.5 2.5 2.5]
(输入维度[2,2,3],下面指定沿[1,2]维度取平均,首先对第2维度取平均,得到[[1.5,1.5,1.5],[3.5,3.5,3.5]],然后对第3维度取平均,得[1.5. 3.5])
5、类似的结构函数:tf.reduce_sum(求和)、tf.reduce_max(最大值)、tf.reduce_min(最小值)
另外:如果在编写CSDN博客的时候,发现行间距格式不一致的时候,您可以尝试使用(shift+回车键)哦!