Broadcasting matrix-vector dot product

不羁岁月 提交于 2019-12-24 12:23:13

问题


I have a set of matrices collected in a 3-D array with shape (1222, 47, 47), and a set of vectors in a 2-D array with shape (1222, 47).

Is there a broadcasting way to multiply each [47x47] matrix with its corresponding [47] vector? With a full loop, this would be

numpy.vstack([A[n, :, :].dot(xb[n, :]) for n in range(A.shape[0])])

which is okay for 1222 elements, but I might have a lot more later. I tried if dot, matrix_multiply, inner, or inner1d would fit the bill, in combination with transpose, but I didn't quite get it. Can this be done?


回答1:


Any of these should do it:

matrix_multiply(matrices, vectors[..., None])
np.einsum('ijk,ik->ij', matrices, vectors)

None will take advantage of a highly optimized library though.

Sometime in the future, when PEP 465 has been implemented, using Python >= 3.5 you should be able to simply do:

matrices @ vectors[..., None]


来源:https://stackoverflow.com/questions/24174045/broadcasting-matrix-vector-dot-product

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