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

这篇具有很好参考价值的文章主要介绍了深入浅出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变量,否则必须在 [ − 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
返回值

Tensor,在指定维度上进行求和运算的Tensor,数据类型和输入数据类型一致。文章来源地址https://www.toymoban.com/news/detail-451399.html

实例
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 

到了这里,关于深入浅出PaddlePaddle函数——paddle.sum的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 深入浅出PaddlePaddle函数——paddle.zeros

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月06日
    浏览(27)
  • 深入浅出PaddlePaddle函数——paddle.arange

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.range · 深入浅出Pytorch函数——torch.arange · 深入浅出PaddlePaddle函数——paddle.arange 语法 当 dtype 表示浮点类型时,为了避免浮点计算误差,建议给 end 加上一个极小值 epsilon ,使边界可以更

    2024年02月05日
    浏览(58)
  • 深入浅出PaddlePaddle函数——paddle.full_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月05日
    浏览(37)
  • 深入浅出PaddlePaddle函数——paddle.to_tensor

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.constant · 深入浅出Pytorch函数——torch.tensor · 深入浅出Pytorch函数——torch.as_tensor · 深入浅出Pytorch函数——torch.Tensor · 深入浅出PaddlePaddle函数——paddle.to_tensor · 深入浅出PaddlePaddle函数—

    2024年02月08日
    浏览(32)
  • 深入浅出PaddlePaddle函数——paddle.zeros_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月07日
    浏览(28)
  • 深入浅出PaddlePaddle函数——paddle.ones_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月05日
    浏览(29)
  • 深入浅出Pytorch函数——torch.sum

    分类目录:《深入浅出Pytorch函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.reduce_sum · 深入浅出TensorFlow2函数——tf.math.reduce_sum · 深入浅出Pytorch函数——torch.sum · 深入浅出PaddlePaddle函数——paddle.sum 语法 参数 input :[ Tensor ] 输入的张量。 dim :[可选, int / tuple ] 求和

    2024年02月04日
    浏览(58)
  • 深入浅出TensorFlow2函数——tf.reduce_sum

    分类目录:《深入浅出TensorFlow2函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.reduce_sum · 深入浅出TensorFlow2函数——tf.math.reduce_sum · 深入浅出Pytorch函数——torch.sum · 深入浅出PaddlePaddle函数——paddle.sum 计算张量各维度上元素的总和。 语法 参数 input_tensor :[ Tensor

    2024年02月10日
    浏览(43)
  • 深入浅出TensorFlow2函数——tf.math.reduce_sum

    分类目录:《深入浅出TensorFlow2函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.reduce_sum · 深入浅出TensorFlow2函数——tf.math.reduce_sum · 深入浅出Pytorch函数——torch.sum · 深入浅出PaddlePaddle函数——paddle.sum 计算张量各维度上元素的总和。 语法 参数 input_tensor :[ Tensor

    2024年02月12日
    浏览(22)
  • 深入浅出C语言—【函数】上

       目录 1.函数的概念 2.C语言函数的分类 2.1 库函数 2.1.1 strcpy库函数举例学习方式 2.1.2 库函数扩展知识 2.2 自定义函数 2.2.1求两个整数中的较大值 3. 函数的参数 3.1 实际参数(实参) 3.2 形式参数(形参) 4. 函数的调用 4.1 传值调用 4.2 传址调用 老铁们,网址自取,记得一键

    2024年02月07日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包