Numpy dot product of a 4D array with its transpose fails

扶醉桌前 提交于 2019-12-14 03:56:13

问题


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:


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)


来源:https://stackoverflow.com/questions/52679673/numpy-dot-product-of-a-4d-array-with-its-transpose-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!