tf.reduce_sum 用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/G66565906/article/details/84140989

tf.reduce_sum 的功能描述原文为:

 """Computes the sum of elements across dimensions of a tensor.

  Reduces `input_tensor` along the dimensions given in `axis`.
  Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
  entry in `axis`. If `keepdims` is true, the reduced dimensions
  are retained with length 1.

  If `axis` is None, all dimensions are reduced, and a
  tensor with a single element is returned.

  For example:

  ```python
  x = tf.constant([[1, 1, 1], [1, 1, 1]])
  tf.reduce_sum(x)  # 6
  tf.reduce_sum(x, 0)  # [2, 2, 2]
  tf.reduce_sum(x, 1)  # [3, 3]
  tf.reduce_sum(x, 1, keepdims=True)  # [[3], [3]]
  tf.reduce_sum(x, [0, 1])  # 6

初次看该注释时总是理解不了,通过一翻试验,大致理解了该函数的功能。

此处axis为tensor的阶数,使用该函数将消除tensor指定的阶axis,同时将该阶下的所有的元素进行累积求和操作。

tensor的阶数即为括号的嵌套层数,

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

a = tf.constant([  [[5.0,7.0]]  , [[4.0,9.0]]   ])  阶数为 3


阶数的计数从0开始,即 最外层括号的阶数为:0

a = tf.constant([  [[5.0,7.0]]  , [[4.0,9.0]]   ])
c = tf.reduce_sum(a,0,keepdims= False)

如上述代码:

第0阶的子元素有两个 即:    [[5.0, 7.0]], [[4.0,9.0]]    累计求和, 函数的输出结果为:  [[9.0, 16.0]]

a = tf.constant([  [[5.0,7.0]]  , [[4.0,9.0]]   ])

c = tf.reduce_sum(a,1,keepdims=
                  False)

再者  第1阶的元素有两个  分别为 [[5.0,7.0]]   , [[4.0, 9.0]]  各自的子元素均只有一个,分别为[5.0,7.0]和[4.0, 9.0],因此消除掉第1阶后 这两个子元素变为第0阶的子元素, 函数输出结果为  [[5.0,7.0], [4.0,9.0]]

猜你喜欢

转载自blog.csdn.net/G66565906/article/details/84140989
今日推荐