0


深入浅出PaddlePaddle函数——paddle.sum

分类目录:《深入浅出PaddlePaddle函数》总目录
相关文章:
· 深入浅出TensorFlow2函数——tf.reduce_sum
· 深入浅出TensorFlow2函数——tf.math.reduce_sum
· 深入浅出Pytorch函数——torch.sum
· 深入浅出PaddlePaddle函数——paddle.sum


对指定维度上的

  1. Tensor

元素进行求和运算,并输出相应的计算结果。

语法

  1. paddle.sum(x, axis=None, dtype=None, keepdim=False, name=None)

参数

  • x:[Tensor] 输入变量为多维Tensor,支持数据类型为float32float64int32int64
  • axis:[可选, int/list/tuple] 求和运算的维度。如果为None,则计算所有元素的和并返回包含单个元素的Tensor变量,否则必须在 [ − rank ( x ) , rank ( x ) ] [-\text{rank}(x), \text{rank}(x)] [−rank(x),rank(x)]范围内。如果 axis [ i ] < 0 \text{axis}[i]<0 axis[i]<0,则维度将变为 rank + axis [ i ] \text{rank} + \text{axis}[i] rank+axis[i],默认值为None
  • dtype:[可选, str] 输出变量的数据类型。若参数为空,则输出变量的数据类型和输入变量相同,默认值为None
  • keepdim:[bool] 是否在输出Tensor中保留减小的维度。如keepdim=True,否则结果张量的维度将比输入张量小,默认值为False
  • name:[可选, str] 具体用法参见Name,一般无需设置,默认值为None

返回值

  1. Tensor

,在指定维度上进行求和运算的

  1. Tensor

,数据类型和输入数据类型一致。

实例

  1. import paddle
  2. #xis a Tensor with following elements:
  3. # [[0.2,0.3,0.5,0.9]
  4. # [0.1,0.2,0.6,0.7]]#Each example is followed by the corresponding output tensor.
  5. x = paddle.to_tensor([[0.2,0.3,0.5,0.9],[0.1,0.2,0.6,0.7]])
  6. out1 = paddle.sum(x) # [3.5]
  7. out2 = paddle.sum(x, axis=0) # [0.3,0.5,1.1,1.6]
  8. out3 = paddle.sum(x, axis=-1) # [1.9,1.6]
  9. out4 = paddle.sum(x, axis=1, keepdim=True) # [[1.9],[1.6]]#yis a Tensor with shape [2,2,2] and elements as below:
  10. # [[[1,2],[3,4]],
  11. # [[5,6],[7,8]]]#Each example is followed by the corresponding output tensor.
  12. y = paddle.to_tensor([[[1,2],[3,4]],[[5,6],[7,8]]])
  13. out5 = paddle.sum(y, axis=[1,2]) # [10,26]
  14. out6 = paddle.sum(y, axis=[0,1]) # [16,20]#xis a Tensor with following elements:
  15. # [[True, True, True, True]
  16. # [False, False, False, False]]#Each example is followed by the corresponding output tensor.
  17. x = paddle.to_tensor([[True, True, True, True],[False, False, False, False]])
  18. out7 = paddle.sum(x) # [4]
  19. out8 = paddle.sum(x, axis=0) # [1,1,1,1]
  20. out9 = paddle.sum(x, axis=1) # [4,0]

函数实现

  1. def sum(x, axis=None, dtype=None, keepdim=False, name=None):"""
  2. Computes the sum of tensor elements over the given dimension.
  3. Args:x(Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.axis(int|list|tuple, optional): The dimensions along which the sum is performed. If
  4. :attr:`None`, sum all elements of :attr:`x` and return a
  5. Tensor with a single element, otherwise must be in the
  6. range :math:`[-rank(x),rank(x))`. If :math:`axis[i]<0`,
  7. the dimension to reduce is :math:`rank + axis[i]`.dtype(str, optional): The dtype of output Tensor. The default value is None, the dtype
  8. of output is the same as input Tensor `x`.keepdim(bool, optional): Whether to reserve the reduced dimension in the
  9. output Tensor. The result Tensor will have one fewer dimension
  10. than the :attr:`x` unless :attr:`keepdim` is true,default
  11. value is False.name(str, optional): Name for the operation(optional,default is None). For more information, please refer to :ref:`api_guide_Name`.
  12. Returns:
  13. Tensor: Results of summation operation on the specified axis of input Tensor `x`,if `x.dtype='bool'`, `x.dtype='int32'`, it's data type is `'int64'`,
  14. otherwise it's data type is the same as `x`.
  15. Examples:.. code-block:: python
  16. import paddle
  17. #xis a Tensor with following elements:
  18. # [[0.2,0.3,0.5,0.9]
  19. # [0.1,0.2,0.6,0.7]]#Each example is followed by the corresponding output tensor.
  20. x = paddle.to_tensor([[0.2,0.3,0.5,0.9],[0.1,0.2,0.6,0.7]])
  21. out1 = paddle.sum(x) # [3.5]
  22. out2 = paddle.sum(x, axis=0) # [0.3,0.5,1.1,1.6]
  23. out3 = paddle.sum(x, axis=-1) # [1.9,1.6]
  24. out4 = paddle.sum(x, axis=1, keepdim=True) # [[1.9],[1.6]]#yis a Tensor with shape [2,2,2] and elements as below:
  25. # [[[1,2],[3,4]],
  26. # [[5,6],[7,8]]]#Each example is followed by the corresponding output tensor.
  27. y = paddle.to_tensor([[[1,2],[3,4]],[[5,6],[7,8]]])
  28. out5 = paddle.sum(y, axis=[1,2]) # [10,26]
  29. out6 = paddle.sum(y, axis=[0,1]) # [16,20]#xis a Tensor with following elements:
  30. # [[True, True, True, True]
  31. # [False, False, False, False]]#Each example is followed by the corresponding output tensor.
  32. x = paddle.to_tensor([[True, True, True, True],[False, False, False, False]])
  33. out7 = paddle.sum(x) # [4]
  34. out8 = paddle.sum(x, axis=0) # [1,1,1,1]
  35. out9 = paddle.sum(x, axis=1) # [4,0]"""
  36. ifisinstance(axis, Variable):
  37. reduce_all_flag = True if axis.shape[0]==len(x.shape)else False
  38. else:if axis is not None and not isinstance(axis,(list, tuple)):
  39. axis =[axis]if not axis:
  40. axis =[]iflen(axis)==0:
  41. reduce_all_flag = True
  42. else:iflen(axis)==len(x.shape):
  43. reduce_all_flag = True
  44. else:
  45. reduce_all_flag = False
  46. dtype_flag = False
  47. if dtype is not None:
  48. dtype_flag = True
  49. dtype =convert_np_dtype_to_dtype_(dtype)ifin_dygraph_mode():return _C_ops.sum(x, axis, dtype, keepdim)if not isinstance(axis, Variable):
  50. axis = axis if axis != None and axis !=[] and axis !=()else[0]if utils._contain_var(axis):
  51. axis = utils._convert_to_tensor_list(axis)if_in_legacy_dygraph():if dtype_flag:return _legacy_C_ops.reduce_sum(x,'dim', axis,'keep_dim', keepdim,'reduce_all', reduce_all_flag,'in_dtype',
  52. x.dtype,'out_dtype', dtype)else:return _legacy_C_ops.reduce_sum(x,'dim', axis,'keep_dim', keepdim,'reduce_all', reduce_all_flag)
  53. attrs ={'dim': axis,'keep_dim': keepdim,'reduce_all': reduce_all_flag
  54. }if dtype_flag:
  55. attrs.update({'in_dtype': x.dtype,'out_dtype': dtype
  56. })check_variable_and_dtype(
  57. x,'x',['bool','float16','float32','float64','int16','int32','int64','complex64','complex128',
  58. u'bool', u'float16', u'float32', u'float64',
  59. u'int32', u'int64', u'complex64', u'complex128'],'sum')check_type(axis,'axis',(int, list, tuple,type(None), Variable),'sum')
  60. helper =LayerHelper('sum',**locals())if dtype_flag:
  61. out = helper.create_variable_for_type_inference(
  62. dtype=dtype)else:
  63. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  64. helper.append_op(
  65. type='reduce_sum',
  66. inputs={'X': x},
  67. outputs={'Out': out},
  68. attrs=attrs)return

本文转载自: https://blog.csdn.net/hy592070616/article/details/129937335
版权归原作者 von Neumann 所有, 如有侵权,请联系我们删除。

“深入浅出PaddlePaddle函数——paddle.sum”的评论:

还没有评论