首先先弄清楚哪是0轴(-1轴),1轴(-2轴)
看下面例子:
import tensorflow as tf x = tf.constant([[1, 2, 3], [4, 5, 6]]) y2 = tf.reduce_sum(x, axis = 0) print("沿着张量0轴方向求和:\n",y2.eval()) y3 = tf.reduce_sum(x, axis = 1) print("沿着张量1轴方向求和:\n",y3.eval()) y4 = tf.reduce_sum(x, axis = 1, keep_dims=True) print("沿着张量1轴方向求和,并保持维度:\n",y4.eval()) y5 = tf.reduce_sum(x, axis = -2) print("沿着张量-2轴方向求和:\n",y5.eval()) y6 = tf.reduce_sum(x, axis = -1) print("沿着张量-1轴方向求和:\n",y6.eval())
结果如下:
沿着张量0轴方向求和:
[5 7 9]
沿着张量1轴方向求和:
[ 6 15]
沿着张量1轴方向求和,并保持维度:
[[ 6] [15]]
沿着张量-2轴方向求和:
[5 7 9]
沿着张量1轴方向求和:
[ 6 15]
沿着张量-1轴方向求和:
[ 6 15]
可以看到0轴为列,1轴为行,-1轴==1轴,-2轴==0轴