【问题标题】:hadamard product of uneven shaped arrays不均匀阵列的hadamard乘积
【发布时间】:2019-05-06 10:22:34
【问题描述】:

我正在做一大堆 hadamard 产品,作为机器学习项目的一部分。为了传达这个问题,下面是设置:

# shape: (2, 3)
In [17]: arr1
Out[17]: 
array([[0.44486617, 0.21001534, 0.63833794],
       [0.90878526, 0.61692562, 0.01978946]])

# shape: (5, 3)
In [18]: arr2
Out[18]: 
array([[0.00640485, 0.22768134, 0.62845291],
       [0.58168743, 0.65527711, 0.14765079],
       [0.61389269, 0.38546809, 0.62696518],
       [0.73977707, 0.03737199, 0.45905132],
       [0.51932163, 0.00119124, 0.07241033]])

现在,我想用arr2arr1 中的每一行进行hadamard 乘积,从而获得结果数组,称为res,形状为(10, 3)

 (2, 3)
  *  | 
 (5, 3)
   ||
 (10,3)

我们如何仅使用 NumPy 以尽可能少的开销做到这一点?

【问题讨论】:

    标签: python numpy multidimensional-array multiplication elementwise-operations


    【解决方案1】:

    在将其中一个数组扩展为3D 后,我们可以利用broadcasting -

    (a[:,None]*b).reshape(-1,a.shape[1]) # a,b are input arrays
    

    对于大型数组,为了实现多核使用的内存效率和性能,我们可以使用numexpr module -

    import numexpr as ne
    
    ne.evaluate('a3D*b',{'a3D':a[:,None]}).reshape(-1,a.shape[1])
    

    时间安排 -

    In [20]: a = np.random.rand(200,30)
    
    In [21]: b = np.random.rand(500,30)
    
    In [22]: %timeit (a[:,None]*b).reshape(-1,a.shape[1])
    100 loops, best of 3: 4.61 ms per loop
    
    In [27]: %timeit ne.evaluate('a3D*b',{'a3D':a[:,None]}).reshape(-1,a.shape[1])
    100 loops, best of 3: 2.28 ms per loop
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2017-02-23
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多