scatter_nd_add

paddle. scatter_nd_add ( x, index, updates, name=None ) [源代码]

通过对 Tensor 中的单个值或切片应用稀疏加法,从而得到输出的 Tensor。

x 是维度为 R 的 Tensor。index 是维度为 K 的 Tensor。因此,index 的形状是 \([i_0, i_1, ..., i_{K-2}, Q]\),其中 \(Q \leq R\)updates 是一个维度为 \(K - 1 + R - Q\) 的 Tensor,它的形状是 \(index.shape[:-1] + x.shape[index.shape[-1]:]\)

根据 index\([i_0, i_1, ..., i_{K-2}]\) 得到相应的 updates 切片,将其加到根据 index 的最后一维得到 x 切片上,从而得到最终的输出 Tensor。

示例:

- 案例 1:
    x = [0, 1, 2, 3, 4, 5]
    index = [[1], [2], [3], [1]]
    updates = [9, 10, 11, 12]

  得到:

    output = [0, 22, 12, 14, 4, 5]

- 案例 2:
    x = [[65, 17], [-14, -25]]
    index = [[], []]
    updates = [[[-1, -2], [1, 2]],
               [[3, 4], [-3, -4]]]
    x.shape = (2, 2)
    index.shape = (2, 0)
    updates.shape = (2, 2, 2)

  得到:

    output = [[67, 19], [-16, -27]]

参数

  • x (Tensor) - 输入 Tensor,数据类型可以是 int32,int64,float32,float64。

  • index (Tensor) - 输入的索引 Tensor,数据类型为非负 int32 或非负 int64。它的维度 index.ndim 必须大于 1,并且 index.shape[-1] <= x.ndim

  • updates (Tensor) - 输入的更新 Tensor,它必须和 x 有相同的数据类型。形状必须是 index.shape[:-1] + x.shape[index.shape[-1]:]

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

返回

Tensor,数据类型和形状都与 x 相同。

代码示例

>>> import paddle

>>> x = paddle.rand(shape=[3, 5, 9, 10], dtype='float32')
>>> updates = paddle.rand(shape=[3, 9, 10], dtype='float32')
>>> index = paddle.to_tensor([[1, 1],
...                           [0, 1],
...                           [1, 3]], dtype='int64')

>>> output = paddle.scatter_nd_add(x, index, updates)
>>> print(output.shape)
[3, 5, 9, 10]