多个向量在数组中的张量积

huangapple go评论62阅读模式
英文:

Tensorproduct of multiple vectors in an array

问题

我需要计算存储在两个数组中的多对向量的张量积。我将给您一个示例:

a = np.array([[3, 5, 1], [6, 5, 4]])
b = np.array([[8, 2, 3], [7, 8, 9]])

我想要计算的是:

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

我找不到使用numpy函数完成这个任务的好方法,而且我不想将数组拆分为其各个向量,因为这太耗时了(我需要在递归模拟中使用这个,所以我可以节省的每一点时间都非常宝贵)。我希望有人可以帮助我。

英文:

I need to compute the tensor product of several pairs of vectors, that are stored in two arrays. I'll give you an example:

a=np.array([[3,5,1],[6,5,4]])
b=np.array([[8,2,3],[7,8,9]])

what I want to compute is:

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

I couldn't find a good way to do this with numpy functions and I don't want to do it by splitting the arrays up into their individual vectors, because this takes way to long (I need this for a recursive simulation, so every bit of time I can save is gold). I hope there is a quick way to do this, can anyone help me?

答案1

得分: 1

如果您指的是张量积仅仅是矩阵乘法/点积,我认为您想要类似这样的东西:

z = a * b
z = np.sum(z, axis=1)

编辑:

根据您的评论,我认为您想要(可以做)的是使用广播将维度添加,以便可以进行简单的乘法。

z = x[:, :, None, None] * y[None, None, :, :]
英文:

If by tensorproduct you just mean a matmul/dot product, I think you want something like this:

z = a * b
z = np.sum(z, axis=1)

Edit:

Based on your comment what I think you want (can do) is use broadcasting to add dimensions so that you can do a simple multiplication.

z = x[:, :, None, None] * y[None, None, :, :]

答案2

得分: 0

如果你想要计算(a[0]*b[0]).sum()(a[1]*b[1]).sum()

你可以使用numpy.einsum来进行计算:

np.einsum('ij,ij->i', a, b)

输出:array([ 37, 118])

英文:

If you want (a[0]*b[0]).sum() and (a[1]*b[1]).sum(),

You can use numpy.einsum with:

np.einsum('ij,ij->i', a, b)

Output: array([ 37, 118])

huangapple
  • 本文由 发表于 2023年4月17日 02:35:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定