不少博文解释过这个函数,但是对axis=0表示行还是列说的很费解。
本文以3维张量为例来补充解释,详细看看输入输出张量维度的变化。代码如下:
import tensorflow as tf
x = [[[1, 2, 3], [4, 5, 6]]]
y = tf.cast(x, tf.float32)
ym = tf.reduce_mean(y)
ym0 = tf.reduce_mean(y, axis=0)
ym1 = tf.reduce_mean(y, axis=1)
ym2 = tf.reduce_mean(y, axis=2)
print("y的维度为", y.shape)
print("tf.reduce_mean(y)的维度为", ym.shape)
print("tf.reduce_mean(y, axis=0)的维度为", ym0.shape)
print("tf.reduce_mean(y, axis=1)的维度为", ym1.shape)
print("tf.reduce_mean(y, axis=2)的维度为", ym2.shape)
输出结果为:
y的维度为 (1, 2, 3)
tf.reduce_mean(y)的维度为 ()
tf.reduce_mean(y, axis=0)的维度为 (2, 3)
tf.reduce_mean(y, axis=1)的维度为 (1, 3)
tf.reduce_mean(y, axis=2)的维度为 (1, 2)
y是3维张量,3个维数为dim0=1,dim1=2,dim2=3。
tf.reduce_mean(y)是对所有数求平均,结果为0维张量,即一个数。
tf.reduce_mean(y, axis=0)在0维上求平均,结果为(dim1=2,dim2=3)维。
tf.reduce_mean(y, axis=1)在1维上求平均,结果为(dim0=1,dim2=3)维。
tf.reduce_mean(y, axis=2)在2维上求平均,结果为(dim0=1,dim1=2)维。
明确了张量维度的变化,就不用纠结是行还是列了,况且行列的概念只适用于2维。