广播矩阵-矢量点积 [英] Broadcasting matrix-vector dot product

查看:102
本文介绍了广播矩阵-矢量点积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在形状为(1222, 47, 47)的3D数组中收集了一组矩阵,并在形状为(1222, 47)的2D数组中收集了一组向量.

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).

是否存在一种将每个[47x47]矩阵与其对应的[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])])

对于1222个元素来说还可以,但是以后可能还会更多.我尝试将dotmatrix_multiplyinnerinner1dtranspose结合使用,但我不太明白.能做到吗?

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?

推荐答案

其中任何一个都应该这样做:

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.

将来的某个时候,当 PEP 465 已实施时, Python> = 3.5,您应该可以轻松做到:

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

matrices @ vectors[..., None]

这篇关于广播矩阵-矢量点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆