我无法找出从 for 循环到向量化 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, :, :]
问题解决了。这与添加操作有何不同? (除了分配一个新的矩阵之外,我对语义方面感兴趣)
最佳答案
问题是传递 out=singletree[null_positions,parent.x, :, :]
正在复制 singletree
的部分,因为您正在使用advanced indexing (与 basic indexing 相反,它返回 View )。因此,结果将被写入一个完全不同的数组,并且原始数组将保持不变。
但是,you can use advanced indexing to assign values 。在您的情况下,最值得推荐的语法是:
singletree[null_positions, parent.x, :, :] += \
posteriors[parent.u, null_positions, :, :]
这将最大限度地减少中间数组的使用。
关于python - python for循环和3D numpy矩阵加法之间的等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46039833/