我有 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。也许聪明的你们也可以改进它。
最佳答案
也许更简洁的是:
reduce(lambda x, y: tensordot(x, y, 0), l)
关于python - 多个数组张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244980/