Numpy 相当于“tf.tensor_scatter_nd_add”方法

问题描述

问题确实在标题中,我正在寻找 scipy/numpy/etc 中的方法。 (不是 TensorFlow),它封装了 tf.tensor_scatter_nd_add 中描述的行为,但封装在 Numpy 数组而不是张量上。

我遇到了 scipy.ndimage.sum 方法,但无法重现我在下面给出的示例。

您认为合适的方法必须能够重现 TF 文档中提供的 3 级示例:

    indices = tf.constant([[0],[2]])
    updates = tf.constant([[[5,5,5],[6,6,6],[7,7,7],[8,8,8]],[[5,8]]])
    tensor = tf.ones([4,4,4],dtype=tf.int32)
    updated = tf.tensor_scatter_nd_add(tensor,indices,updates)
    print(updated)

希望有人之前解决过类似的问题并能在这里提供帮助 - 提前致谢!

解决方法

我可以确认以下函数为我捕获了所需的行为:

    def scatter_nd_add_numpy(target,indices,updates):
        indices = tuple(indices.reshape(-1,indices.shape[-1]).T)
        np.add.at(target,updates)
        return target

感谢 Remy 在 this stackoverflow thread 上的回答。