scatter

paddle.fluid.layers. scatter ( input, index, updates, name=None, overwrite=True ) [源代码]

该OP根据index中的索引值将updates数据更新到input中。

  1. 输入:
  2. input = np.array([[1, 1], [2, 2], [3, 3]])
  3. index = np.array([2, 1, 0, 1])
  4. # updates的维度需要和input一样
  5. # updates 维度 > 1 的shape要和input一样
  6. updates = np.array([[1, 1], [2, 2], [3, 3], [4, 4]])
  7. overwrite = False
  8. 计算过程:
  9. if not overwrite:
  10. for i in range(len(index)):
  11. input[index[i]] = np.zeros((2))
  12. # 根据index中的索引值取updates中的数据更新到input中去
  13. for i in range(len(index)):
  14. if (overwirte):
  15. input[index[i]] = updates[i]
  16. else:
  17. input[index[i]] += updates[i]
  18. 输出:
  19. out # np.array([[3, 3], [6, 6], [1, 1]])
  20. out.shape # [3, 2]

参数:

  • input (Variable) - 支持任意纬度的Tensor。支持的数据类型为float32。

  • index (Variable) - 表示索引,仅支持1-D Tensor。 支持的数据类型为int32,int64。

  • updates (Variable) - 根据索引的值将updates Tensor中的对应值更新到input Tensor中,updates Tensor的维度需要和input tensor保持一致,且除了第一维外的其他的维度的大小需要和input Tensor保持相同。支持的数据类型为float32。

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

  • overwrite (bool,可选) - 如果index中的索引值有重复且overwrite 为True,旧更新值将被新的更新值覆盖;如果为False,新的更新值将同旧的更新值相加。默认值为True。

返回:返回类型为Variable(Tensor|LoDTensor),数据类型以及shape大小同输入一致。

代码示例

  1. import numpy as np
  2. import paddle.fluid as fluid
  3. input = fluid.layers.data(name='data', shape=[3, 2], dtype='float32', append_batch_size=False)
  4. index = fluid.layers.data(name='index', shape=[4], dtype='int64', append_batch_size=False)
  5. updates = fluid.layers.data(name='update', shape=[4, 2], dtype='float32', append_batch_size=False)
  6. output = fluid.layers.scatter(input, index, updates, overwrite=False)
  7. exe = fluid.Executor(fluid.CPUPlace())
  8. exe.run(fluid.default_startup_program())
  9. in_data = np.array([[1, 1], [2, 2], [3, 3]]).astype(np.float32)
  10. index_data = np.array([2, 1, 0, 1]).astype(np.int64)
  11. update_data = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]).astype(np.float32)
  12. res = exe.run(fluid.default_main_program(), feed={'data':in_data, "index":index_data, "update":update_data}, fetch_list=[output])
  13. print(res)
  14. # [array([[3., 3.],
  15. # [6., 6.],
  16. # [1., 1.]], dtype=float32)]