Element wise 或列求和三元组的总和

huangapple go评论93阅读模式
英文:

Sum of element wise or on columns triplet

问题

R = np.einsum('ik,jk,lk->ijl', A, A, A)
英文:

I have a NumPy array A of shape (n, m) and dtype bool:

array([[ True, False, False, False],
       [ True, False, False,  True],
       [False,  True, False, False],
       [False, False, False,  True],
       [False, False, False,  True]])

I would like to get the result R of shape (m, m, m) of dtype int:

array([[[2, 3, 2, 4],
        [3, 3, 3, 5],
        [2, 3, 2, 4],
        [4, 5, 4, 4]],

       [[3, 3, 3, 5],
        [3, 1, 1, 4],
        [3, 1, 1, 4],
        [5, 4, 4, 4]],

       [[2, 3, 2, 4],
        [3, 1, 1, 4],
        [2, 1, 0, 3],
        [4, 4, 3, 3]],

       [[4, 5, 4, 4],
        [5, 4, 4, 4],
        [4, 4, 3, 3],
        [4, 4, 3, 3]]])

where R[k, i, j] is the sum of the element wise logical or on columns k, i and j. So, for example:

R[3, 1, 2] = (np.logical_or(np.logical_or(A[:, 3], A[:, 1]), A[:, 2])).sum()

One way to get this result is

R = np.array(
    [[[np.logical_or(np.logical_or(A[:, i], A[:, j]), A[:, k]).sum()
    for i in range(m)] for j in range(m)] for k in range(m)],
)

But this is clearly not using numpy APIs. Is it possible to do it using NumPy? For example, with broadcasting, see the related question below.

This is a related (simpler) question.

答案1

得分: 1

对于这类广播问题,我通常会思考不同操作对形状的影响。例如,A[:, None, :] * A[:, :, None] 将产生形状为 (n, m, m) 的数组,而 A.sum(axis=0) 将移除第一个轴,得到形状为 (m,) 的数组。

鉴于我们希望得到形状为 (m, m, m) 的输出,我们首先将 A 的轴 1 广播到轴 1、2 和 3,得到形状为 (n, m, m, m) 的中间数组,然后在轴 0 上求和:

R = (A[:, :, None, None] | A[:, None, :, None] | A[:, None, None, :]).sum(axis=0)
英文:

For these kinds of broadcasting problems, I usually reason about what different operations do to the shape. For example, A[:, None, :] * A[:, :, None] will give an array of shape (n, m, m), while A.sum(axis=0) will remove the first axis, giving an array of shape (m,).

Given that we want an output with shape (m, m, m), we first broadcast axis 1 of A into axes 1, 2, and 3 to get an intermediate array with shape (n, m, m, m), then sum over axis 0:

R = (A[:, :, None, None] | A[:, None, :, None] | A[:, None, None, :]).sum(axis=0)

huangapple
  • 本文由 发表于 2023年5月18日 06:05:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定