Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute inner dot products of multidimensional numpy array elements

What is the most elegant way to compute "inner" dot products of a multidimensional numpy array?

Let's assume I have 2 arrays a and b both of shape (2, 2, 2) (could be (n, n, 2) with n>= 2) and I want to compute the inner_dot(a, b) with the following definition:

np.array([[np.dot(a[0, 0, :], b[0, 0, :]), np.dot(a[1, 0, :], b[1, 0, :])],
          [np.dot(a[0, 1, :], b[0, 1, :]), np.dot(a[1, 1, :], b[1, 1, :])]])

Here is an example:

a = np.arange(8).reshape(2, 2, 2)
b = np.arange(8).reshape(2, 2, 2)

Expected result:

array([[ 1, 41],
       [13, 85]])
like image 656
Benoit Fgt Avatar asked Nov 15 '25 03:11

Benoit Fgt


1 Answers

You can directly multiply both arrays and sum along the last axis. Also since you want the top right corner of the output as np.dot(a[1, 0, :], b[1, 0, :]), rather than 0,1 and presumably in the same fashion for the off-diagonal elements, you can transpose the result to get as expected:

(a*b).sum(-1).T
array([[ 1, 41],
       [13, 85]])
like image 113
yatu Avatar answered Nov 17 '25 17:11

yatu