python - python for循环和3D numpy矩阵加法之间的等价

标签 python numpy matrix vectorization addition

我无法找出从 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/

相关文章:

python - 安装 LabelImg Windows

python - 在 Pandas 中创建通用 header 字段

python - numpy 唯一没有排序

python - 如何将源和目标参数定义为shortest_path的数组?

r - 将邻接表转换为 R 中的二进制矩阵

matlab - 矩阵长度的目的

python - 从另一个数据框中减去一个 Pandas 数据框中的属性值

Python 欧拉方法在二体问题中的实现不起作用

python - 将 numpy 数组 + 字符串导出到 CSV

python - 与常数的矩阵乘法