【问题标题】:Numpy dot product of a stacked array堆叠数组的 Numpy 点积
【发布时间】:2021-01-28 14:59:42
【问题描述】:

我有 4 个矩阵表示向量 v1 和 v2 的 (x, y) 分量。因此矩阵是x1, y1, x2, y2

是否可以计算数组[x1_i, y1_i], [x2_i, y2_i] 之间的点积,其中 i 只是所有四个数组中的单个元素索引(它们都是相同的形状)。

到目前为止,我的解决方案是将它们堆叠在一起并进行 for 循环:

v1 = np.stack((y1, x1), axis=0)
v2 = np.stack((y2, x2), axis=0)
s = np.zeros(v1.shape[1:])
for i in range(v1.shape[1]):
    for j in range(v1.shape[2]):
        s[i,j] = np.dot(v1[:,i,j], v2[:,i,j])

最好的解决方案是对 v1 和 v2 中的所有元素在 axis=0 中的两个元素上进行点积。像 np.dot(v1,v2,axis=0)

x1.shape, y1.shape, x2.shape, y2.shape = (228, 192)
After stacking: v1.shape, v2.shape = (2, 228, 192)

其中 i1 和 i2 是来自图像 (SimpleITK) 的数组的代码。

    y1, x1 = np.gradients(i1)
    y2, x2 = np.gradients(i2)
    v1 = np.stack((y1, x1), axis=0)
    v2 = np.stack((y2, x2), axis=0)
    # this part is stupid
    s = np.zeros(v1.shape[1:])
    for i in range(v1.shape[1]):
        for j in range(v1.shape[2]):
            s[i,j] = np.dot(v1[:,i,j], v2[:,i,j])

感谢您的帮助

【问题讨论】:

  • v1、v2的形状是什么?您能否添加一个虚拟示例输入?
  • 请添加您想要的输出示例。
  • 这里有样本输入和输出会有很大帮助。 x1、y1、x2 和 y2 实际上是向量而不是矩阵吗?
  • matmul/@ 将前导维度视为“批次”,最后 2 个维度视为 dot 部分(A 的最后一个和 B 的第二个到最后一个的积和)。 einsum 允许您指定(几乎)任意轴组合。
  • 或者你试过np.sum( v1*v2, axis=0)吗?

标签: python numpy


【解决方案1】:

听起来像你想要的

y1 * y2 + x1 * x2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2018-06-05
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多