Numpy dot product for tensors (3d times 2d)

I am currently using

Na = (3, 2, 4)
Nb = Na[1:]
A = np.arange(np.prod(Na)).reshape(Na)
b = np.arange(np.prod(Nb)).reshape(Nb)

      

I want to calculate:

r_ik = sum_j (A_ijk * b_jk)

r = np.empty((A.shape[0], A.shape[2])
for i in range(A.shape[2]):
    r[:, i] = np.dot(A[:, :, i], b[:, i])

      

In words: A - "a stack of 4 matrices" (form (3,2)), i.e. 3d-array, b - "stack of four vectors" (form (3)), i.e. 2d -array. The desired result is a "stack of 4 matrix vector products", that is, a stack of vectors, that is, again a 2d array (in the form (3, 4)).

I had a mid-term look at np.einsum and np.tensordot, but any solution I built with them was at least as long and less readable as my loop solution.

However, I think there should be a one-liner for this simple problem.

+3


source to share


1 answer


I'm not sure why np.einsum

doesn't work for you. This should do the trick:

r = np.einsum('ijk,jk->ik', A, b)

      



I find this to be very readable because it accurately reflects the math formula you provided in your question.

+5


source







All Articles