Numpy dot product of a 4D array with its transpose

2019-07-19 00:29发布

For a 4D array A with dimensions of (60,64,2,2), need to calculate the dot product with its transpose A_t.

A_t is of dimension(2,2,64,60). Below is what I do.

A_t = np.transpose(A)
A_At = A_t.dot(A)

The dot product throws an error

ValueError: shapes (2,2,64,60) and (60,64,2,2) not aligned: 60 (dim 3) != 2 (dim 2)

Am I taking the transpose incorrectly? I have also tried converting the individual arrays to numpy matrices(even though not recommended as per several posts) and then computing the dot product but I get a different error.

Have also researched numpy topics such as broadcasting but I could not find any useful example for 4D arrays.

Any inputs would be grateful. Thanks!

Note: I'm using python 2.7

1条回答
狗以群分
2楼-- · 2019-07-19 00:45

On your knowledge-driven wish of having a 2x2 array at the end, what about using xarray.dot for that kind of task. With your A in hand

>>> A.shape
(60, 64, 2, 2)

you would do

>>> xA   = xr.DataArray(A, dims=['d1','d2','d3','d4'])
>>> xA_t = xA.T
>>> xr.dot(xA_t, xA, dims=['d1','d2']).shape
(2, 2)
查看更多
登录 后发表回答