如何对n个数组进行元素明智乘法的for循环矢量化?

时间:2019-05-15 16:18:44

标签: python numpy vectorization

我想得到一个包含n> 2个数组的元素明智乘法的数组。具体来说,是否有一种方法可以在numpy中向量化以下示例代码(此处n = 3,但我通常需要对n> = 3进行此处理)?

p1=np.array([0.5,0.2,0.3])

p2=np.array([0.3,0.1,0.6])

p3=np.array([0.8,0.1,0.1])

p=np.zeros((p1.shape[0],p2.shape[0],p3.shape[0] ))
for i in range(p1.shape[0]):
    for j in range(p2.shape[0]):
        for k in range(p3.shape[0]):
           p[i,j,k] = p1[i]*p2[j]*p3[k]

2 个答案:

答案 0 :(得分:0)

您正在寻找outer产品。首先执行p1p2的外部乘积,然后执行p3的外部乘积。重塑可以根据需要完成

prod = np.outer(np.outer(p1, p2), p3)

prod = prod.reshape((p1.shape[0],p2.shape[0],p3.shape[0] ))

编辑:@Yann Vernier在下面的评论中建议的通用解决方案

from functools import reduce
ps = [p1, p2, p3]
prod = reduce(np.outer, ps).reshape([p.shape[0] for p in ps])

# array([[[0.12 , 0.015, 0.015],
#         [0.04 , 0.005, 0.005],
#         [0.24 , 0.03 , 0.03 ]],

#        [[0.048, 0.006, 0.006],
#         [0.016, 0.002, 0.002],
#         [0.096, 0.012, 0.012]],

#        [[0.072, 0.009, 0.009],
#         [0.024, 0.003, 0.003],
#         [0.144, 0.018, 0.018]]])

答案 1 :(得分:0)

这是一个通用的输入数组,它使用np.ix_使它们彼此之间可以外部广播-

In [83]: A = [p1,p2,p3] # list of all input arrays

In [84]: np.multiply.reduce(np.ix_(*A))
Out[84]: 
array([[[0.12 , 0.015, 0.015],
        [0.04 , 0.005, 0.005],
        [0.24 , 0.03 , 0.03 ]],

       [[0.048, 0.006, 0.006],
        [0.016, 0.002, 0.002],
        [0.096, 0.012, 0.012]],

       [[0.072, 0.009, 0.009],
        [0.024, 0.003, 0.003],
        [0.144, 0.018, 0.018]]])