【问题标题】:Efficient way to lag vector multiplication using numpy使用 numpy 滞后向量乘法的有效方法
【发布时间】:2019-12-01 21:23:01
【问题描述】:

我正在尝试优化一种算法,该算法涉及多个向量乘法,其中一个向量保持不变,另一个向量不断变化,直到所有计算完成。

例如,如果静态向量是

a = [3 2 0]

而移动向量是

b = [2 5 6 3 8 4]

我想退货

[[6 10 0], [15 12 0], [18 6 0], [9 16 0]] ([[2], [5], [6]] * [[3], [2], [0]] = [[6], [10], [0]] and [[5], [6], [3]] * [[3], [2], [0]] = [[15], [12], [0]], etc.). Is there an efficient way to do this calculation in python/numpy? Or will I just have to loop over slices of <b>b</b> and multiply each by <b>a</b>?

我曾想过将 a 放入类似对角线的矩阵中:

[[3 2 0 0 0 0],

 [0 3 2 0 0 0],

 [0 0 3 2 0 0],

 [0 0 0 3 2 0]]

并乘以对角化的b,例如:

[[2 0 0 0 0 0],

 [0 5 0 0 0 0],

 [0 0 6 0 0 0],

 [0 0 0 3 0 0],

 [0 0 0 0 8 0],

 [0 0 0 0 0 4]]

得到:

[[6 10 0  0  0  0],

 [0 15 12 0  0  0],

 [0 0  18 6  0  0],

 [0 0  0  9  16 0]] 

但这似乎有点过度和占用空间。

希望我的问题有意义。感谢您的帮助!

【问题讨论】:

    标签: python numpy matrix linear-algebra matrix-multiplication


    【解决方案1】:

    我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows 来获得滑动窗口。 More info on use of as_strided based view_as_windows。因此,对于那些strided-view,假设数组作为输入,它将是 -

    In [7]: from skimage.util.shape import view_as_windows
    
    In [8]: view_as_windows(b,len(a))*a
    Out[8]: 
    array([[ 6, 10,  0],
           [15, 12,  0],
           [18,  6,  0],
           [ 9, 16,  0]])
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2013-04-04
      • 2020-05-30
      • 2023-03-07
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      相关资源
      最近更新 更多