2

我有 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。也许你,聪明的家伙,也可以改进它。

4

2 回答 2

2

也许更简洁的是:

reduce(lambda x, y: tensordot(x, y, 0), l)
于 2013-04-26T21:07:40.497 回答
0

numpy 有一个很棒的东西叫做broadcasting,它遍历数组。因此,如果您有一个 x 乘 1 的数组并将其乘以 1 乘 y 的数组,您将得到一个 x 乘 y 数组。就像矩阵一样工作。因此,我将在 2 行中完成您想要的所有操作:

result = np.array((l[0])).reshape((1,len(l[0])))# resizing the first column to make it a 3 by 1 so that numpy broadcasting will work.
print result * l[1] # broadcasting the 3 by 1 by a 1 by 2 to result in your 3 by 2 

你有它!快捷方便!为了您的方便,我将把整个代码放在下面:

import numpy as np
l = [([0.2,0.3,0.5]),([0.7,0.3])]
result = np.array((l[0])).reshape((len(l[0]),1))
print result * l[1]
>>>>aray([[ 0.14  0.06]
 [ 0.21  0.09]
 [ 0.35  0.15]])
于 2013-04-27T12:38:14.390 回答