提问人:Devarapalli Vamsi 提问时间:9/5/2023 最后编辑:Devarapalli Vamsi 更新时间:9/6/2023 访问量:64
如何获得 (n,1,3) numpy 数组中每个数组的点积,以及 (n,3) 数组的所有数组,并得到形状为 (n,n) 的结果数组?
How to get dot product of each array in (n,1,3) numpy array with all arrays of (n,3) array and get the resultant array of shape (n,n)?
问:
我尝试了 einsum np.einsum,但这给了我错误,输出不能重复相同的字母。
np.einsum('aij,aj->aa', vector1, vector2)
还尝试了 np.dot 方法,但这种尝试也是徒劳的。
(广播可能对此有答案。
试
np.sum(vector1[:,np.newaxis] * vector2, axis=axis)
但是,这也给了我一个错误 以下是向量 1 和 2
vector1 = np.arange(12).reshape((4,1,3))
vector2 = np.arange(12).reshape((4,3))
谢谢大家的评论。对于错误地提出问题,我们深表歉意。 (我需要 n,n 形状而不是 n,3)。
我可以通过以下方式实现它: np.einsum('ijk,bk->ib',向量1,向量2)
答:
0赞
Jesse Sealand
9/5/2023
#1
解决方案:
这里的关键是能够控制在哪些轴上进行加工。np.dot() 和 np.tensordot() 不适合此用例。所以你使用 np.einsum 的直觉是正确的,你的符号需要调整一下。例如
import numpy as np
vector1 = np.arange(12).reshape((4,1,3))
vector2 = np.arange(12).reshape((4,3))
np.einsum('ijk,ij->ik',vector1,vector2)
0赞
KamiSama
9/5/2023
#2
确实是我的朋友。广播就是答案。试试这个
vector1 = np.arange(12).reshape((4, 1, 3))
vector2 = np.arange(12).reshape((4, 3))
result = np.sum(vector1 * vector2[:, np.newaxis], axis=2)
np.sum(..., axis=2)
就像沿着最后一个维度(轴 2)将上一步的结果相加一样。这为您提供了 和 中每对数组的点积。vector1
vector2
评论
0赞
hpaulj
9/6/2023
结果是 (4,1)。另一种方法是在轴 1 上求和,即大小为 1,得到 (4,3)。
0赞
Devarapalli Vamsi
9/6/2023
嘿,谢谢你的信息。请重新审视这个问题一次。也考虑到溶胶。
评论
np.einsum('aij,aj->aj', vector1, vector2)
A[:,0,:] *B
einsum('aij,aj->aj'
A.sum(axis=1) * B