nansum

paddle. nansum ( x, axis=None, dtype=None, keepdim=False, name=None ) [源代码]

计算给定轴上的元素之和,并将非数字元素(NaNs)视为 0。

参数

  • x (Tensor) - 输入的 Tensor,数据类型为:float16、float32、float64、int32 或 int64。

  • axis (int|list|tuple,可选) - 求和运算的维度。如果为 None,则计算所有元素的和并返回包含单个元素的 Tensor 变量,否则必须在 \([−rank(x),rank(x)]\) 范围内。如果 \(axis [i] <0\),则维度将变为 \(rank+axis[i]\),默认值为 None。

  • dtype (str,可选) - 输出变量的数据类型。若参数为空,则输出变量的数据类型和输入变量相同,默认值为 None。

  • keepdim (bool) - 是否在输出 Tensor 中保留减小的维度。如 keepdim 为 True,否则结果 Tensor 的维度将比输入 Tensor 小,默认值为 False。

  • name (str,可选) - 具体用法请参见 Name,一般无需设置,默认值为 None。

返回

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

代码示例

>>> import paddle

>>> # x is a Tensor with following elements:
>>> #    [[nan, 0.3, 0.5, 0.9]
>>> #     [0.1, 0.2, -nan, 0.7]]
>>> # Each example is followed by the corresponding output tensor.
>>> x = paddle.to_tensor([[float('nan'), 0.3, 0.5, 0.9],
...                       [0.1, 0.2, float('-nan'), 0.7]],dtype="float32")
>>> out1 = paddle.nansum(x)
>>> out1
Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
2.69999981)
>>> out2 = paddle.nansum(x, axis=0)
>>> out2
Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.10000000, 0.50000000, 0.50000000, 1.59999990])
>>> out3 = paddle.nansum(x, axis=-1)
>>> out3
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[1.70000005, 1.        ])
>>> out4 = paddle.nansum(x, axis=1, keepdim=True)
>>> out4
Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1.70000005],
 [1.        ]])

>>> # y is a Tensor with shape [2, 2, 2] and elements as below:
>>> #      [[[1, nan], [3, 4]],
>>> #       [[5, 6], [-nan, 8]]]
>>> # Each example is followed by the corresponding output tensor.
>>> y = paddle.to_tensor([[[1, float('nan')], [3, 4]],
...                       [[5, 6], [float('-nan'), 8]]])
>>> out5 = paddle.nansum(y, axis=[1, 2])
>>> out5
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[8. , 19.])
>>> out6 = paddle.nansum(y, axis=[0, 1])
>>> out6
Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
[9. , 18.])