python for-loop和3D numpy矩阵添加之间的等价性

时间:2017-09-04 15:06:51

标签: python numpy matrix vectorization addition

我无法弄清楚从for-loop到vectorized numpy操作的非常简单的过渡中的错误。代码如下

 for null_pos in null_positions:
      np.add(singletree[null_pos, parent.x, :, :],
             posteriors[parent.u, null_pos, :, :],
             out=singletree[null_pos, parent.x, :, :])

由于它是2D矩阵之间的简单加法,我概括为3D加法

 np.add(singletree[null_positions, parent.x, :, :],
             posteriors[parent.u, null_positions, :, :],
             out=singletree[null_positions, parent.x, :, :])
事情是,看来结果是不同的!你能明白为什么吗?

谢谢!

更新 似乎

singletree[null_positions, parent.x, :, :] = \
             posteriors[parent.u, null_positions, :, :] +
             singletree[null_positions, parent.x, :, :]

解决了这个问题。这与添加操作有何不同? (除了分配新矩阵,我对语义方面感兴趣)

1 个答案:

答案 0 :(得分:1)

问题是传递out=singletree[null_positions, parent.x, :, :]正在制作singletree部分的副本,因为您正在使用advanced indexing(而不是basic indexing,它会返回视图) 。因此,结果将写入完全不同的数组,原始数组将保持不变。

然而,you can use advanced indexing to assign values。在您的情况下,最值得推荐的语法是:

singletree[null_positions, parent.x, :, :] += \
    posteriors[parent.u, null_positions, :, :]

这将最大限度地减少中间阵列的使用。