tensorflow--math--6--减少--tf.reduce_sum

函数:

tf.reduce_sum(
    input_tensor,
    axis=None,
    keepdims=None,
    name=None,
    reduction_indices=None,
    keep_dims=None
)

参数说明:

  • input_tensor: 待求值的tensor,需要为数值类型
  • axis: The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)). 在哪一维上求解。
  • keepdims: If true, retains reduced dimensions with length 1.
  • name: A name for the operation (optional).
  • reduction_indices: 旧的名字,跟axis效果一样
  • keep_dims: Deprecated alias for keepdims.

例子:

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

调用reduce_sum(arg1, arg2)时,参数arg1即为要求和的数据,arg2有两个取值分别为0和1,通常用reduction_indices=[0]或reduction_indices=[1]来传递参数。从上图可以看出,当arg2 = 0时,是纵向对矩阵求和,原来矩阵有几列就得到几个值;相似地,当arg2 = 1时,是横向对矩阵求和;当省略arg2参数时,默认对矩阵所有元素进行求和。

看到这里,函数名的前缀为什么是reduce_其实也就很容易理解了,reduce就是“对矩阵降维”的含义,下划线后面的部分就是降维的方式,在reduce_sum()中就是按照求和的方式对矩阵降维。那么其他reduce前缀的函数也举一反三了,比如reduce_mean()就是按照某个维度求平均值,等等。

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn