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 = 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