我有 np.arrays 的列表,例如:
l = [array([0.2,0.3,0.5]),array([0.7,0.3])]
我需要获得外部产品:
array([[0.14, 0.06],
[0.21, 0.09],
[0.35, 0.15]])
一般来说:
array([[l[0][0] * l[1][0], l[0][0] * l[1][1]],
[l[0][1] * l[1][0], l[0][1] * l[1][1]],
[l[0][2] * l[1][0], l[0][2] * l[1][1]]])
但是对于任何长度的 l (>= 2),所以当 len(l) == 4 时,我将得到 4 维数组。
我目前的方法是在 for 循环中使用 tensordot:
product = np.tensordot(l[0], l[1], 0)
for i in range(2, len(l)):
product = np.tensordot(product, l[i], 0)
但是我在 Python 代码中使用它看起来更好。有人知道如何做更好更快的解决方案吗?
动机是我需要得到元素乘以两个数组的总和:
result = np.sum(arr * product)
其中 arr.shape == product.shape。也许你,聪明的家伙,也可以改进它。