tensorflow 中 reduce_sum 理解

时间:2023-03-08 22:12:30

定义如下:

reduce_sum(
input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None
)

reduce_sum 是 tensor 内部求和的工具。其参数中:

1. input_tensor 是要求和的 tensor

2. axis 是要求和的 rank,如果为 none,则表示所有 rank 都要仇和

3. keep_dims 求和后是否要降维

4. 这个操作的名称,可能在 graph 中 用

5. 已被淘汰的,被参数 axis 替代

示例如下:

x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x, 0) # 对 tensor 的 0 级进行求和,[1,1,1] + [1,1,1] = [2, 2, 2]
tf.reduce_sum(x, 1) # 对 tensor 的 1 级进行仇和,[1+1+1, 1+1+1] = [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) # 对第 1 级进行求和,但不降维, [[3], [3]]
tf.reduce_sum(x, [0, 1]) # 0 级和 1级都要求和,6
tf.reduce_sum(x) # 因为 x 只有 2 级,所以结果同上一个,6