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

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

对指定维度上的Tensor元素进行求和运算,并输出相应的计算结果。

语法

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

参数

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

返回值

Tensor,在指定维度上进行求和运算的Tensor,数据类型和输入数据类型一致。

实例

import paddle

# x is a Tensor with following elements:
#    [[0.2, 0.3, 0.5, 0.9]
#     [0.1, 0.2, 0.6, 0.7]]
# Each example is followed by the corresponding output tensor.
x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
                      [0.1, 0.2, 0.6, 0.7]])
out1 = paddle.sum(x)  # [3.5]
out2 = paddle.sum(x, axis=0)  # [0.3, 0.5, 1.1, 1.6]
out3 = paddle.sum(x, axis=-1)  # [1.9, 1.6]
out4 = paddle.sum(x, axis=1, keepdim=True)  # [[1.9], [1.6]]

# y is a Tensor with shape [2, 2, 2] and elements as below:
#      [[[1, 2], [3, 4]],
#      [[5, 6], [7, 8]]]
# Each example is followed by the corresponding output tensor.
y = paddle.to_tensor([[[1, 2], [3, 4]],
                      [[5, 6], [7, 8]]])
out5 = paddle.sum(y, axis=[1, 2]) # [10, 26]
out6 = paddle.sum(y, axis=[0, 1]) # [16, 20]

# x is a Tensor with following elements:
#    [[True, True, True, True]
#     [False, False, False, False]]
# Each example is followed by the corresponding output tensor.
x = paddle.to_tensor([[True, True, True, True],
                      [False, False, False, False]])
out7 = paddle.sum(x)  # [4]
out8 = paddle.sum(x, axis=0)  # [1, 1, 1, 1]
out9 = paddle.sum(x, axis=1)  # [4, 0]

函数实现

def sum(x, axis=None, dtype=None, keepdim=False, name=None):
    """
    Computes the sum of tensor elements over the given dimension.
    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
            :attr:`None`, sum all elements of :attr:`x` and return a
            Tensor with a single element, otherwise must be in the
            range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
            the dimension to reduce is :math:`rank + axis[i]`.
        dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype
            of output is the same as input Tensor `x`.
        keepdim (bool, optional): Whether to reserve the reduced dimension in the
            output Tensor. The result Tensor will have one fewer dimension
            than the :attr:`x` unless :attr:`keepdim` is true, default
            value is False.
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
    Returns:
        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'`, 
        otherwise it's data type is the same as `x`.
    Examples:
        .. code-block:: python
            import paddle
            # x is a Tensor with following elements:
            #    [[0.2, 0.3, 0.5, 0.9]
            #     [0.1, 0.2, 0.6, 0.7]]
            # Each example is followed by the corresponding output tensor.
            x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
                                  [0.1, 0.2, 0.6, 0.7]])
            out1 = paddle.sum(x)  # [3.5]
            out2 = paddle.sum(x, axis=0)  # [0.3, 0.5, 1.1, 1.6]
            out3 = paddle.sum(x, axis=-1)  # [1.9, 1.6]
            out4 = paddle.sum(x, axis=1, keepdim=True)  # [[1.9], [1.6]]
            # y is a Tensor with shape [2, 2, 2] and elements as below:
            #      [[[1, 2], [3, 4]],
            #      [[5, 6], [7, 8]]]
            # Each example is followed by the corresponding output tensor.
            y = paddle.to_tensor([[[1, 2], [3, 4]], 
                                  [[5, 6], [7, 8]]])
            out5 = paddle.sum(y, axis=[1, 2]) # [10, 26]
            out6 = paddle.sum(y, axis=[0, 1]) # [16, 20]
            
            # x is a Tensor with following elements:
            #    [[True, True, True, True]
            #     [False, False, False, False]]
            # Each example is followed by the corresponding output tensor.
            x = paddle.to_tensor([[True, True, True, True],
                                  [False, False, False, False]])
            out7 = paddle.sum(x)  # [4]
            out8 = paddle.sum(x, axis=0)  # [1, 1, 1, 1]
            out9 = paddle.sum(x, axis=1)  # [4, 0]
    """
    if isinstance(axis, Variable):
        reduce_all_flag = True if axis.shape[0] == len(x.shape) else False
    else:
        if axis is not None and not isinstance(axis, (list, tuple)):
            axis = [axis]

        if not axis:
            axis = []

        if len(axis) == 0:
            reduce_all_flag = True
        else:
            if len(axis) == len(x.shape):
                reduce_all_flag = True
            else:
                reduce_all_flag = False

    dtype_flag = False
    if dtype is not None:
        dtype_flag = True
        dtype = convert_np_dtype_to_dtype_(dtype)

    if in_dygraph_mode():
        return _C_ops.sum(x, axis, dtype, keepdim)

    if not isinstance(axis, Variable):
        axis = axis if axis != None and axis != [] and axis != () else [0]
        if utils._contain_var(axis):
            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',
                                       x.dtype, 'out_dtype', dtype)
        else:
            return _legacy_C_ops.reduce_sum(x, 'dim', axis, 'keep_dim', keepdim,
                                       'reduce_all', reduce_all_flag)

    attrs = {
        'dim': axis,
        'keep_dim': keepdim,
        'reduce_all': reduce_all_flag
    }

    if dtype_flag:
        attrs.update({
            'in_dtype': x.dtype,
            'out_dtype': dtype
        })

    check_variable_and_dtype(
        x, 'x', ['bool', 'float16', 'float32', 'float64',
                'int16', 'int32', 'int64', 'complex64', 'complex128',
                u'bool', u'float16', u'float32', u'float64',
                u'int32', u'int64', u'complex64', u'complex128'], 'sum')

    check_type(axis, 'axis', (int, list, tuple, type(None), Variable), 'sum')

    helper = LayerHelper('sum', **locals())
    if dtype_flag:
        out = helper.create_variable_for_type_inference(
            dtype=dtype)
    else:
        out = helper.create_variable_for_type_inference(dtype=x.dtype)
    helper.append_op(
        type='reduce_sum',
        inputs={'X': x},
        outputs={'Out': out},
        attrs=attrs)
    return 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年6月25日
下一篇 2023年6月25日

相关推荐