【问题标题】:Most efficient way to build cost matrix for linear sum assignment?为线性总和分配构建成本矩阵的最有效方法?
【发布时间】:2020-04-20 12:51:04
【问题描述】:

假设我们想用 scipy 解决一个线性求和分配,并且分配的成本可以从欧几里德距离构建。

因此,在m 工人W=[j_1, ..., j_m]n 任务T=[t_1, ..., t_n] 中,成本矩阵由下式给出

cost_matrix = np.array([
    [np.linalg.norm(x - y) for x in W] for y in T
])

这看起来计算量很大,效率不高。有没有一种 numpy/scipy 方法可以更好更快地做到这一点?


工作示例:

import numpy as np
from scipy.optimize import linear_sum_assignment

np.random.seed(0)

# define tasks 
t = np.random.rand(5)

# define workers
w = np.random.rand(3)

cost_matrix = np.array([[np.linalg.norm(x-y) for x in w] for y in t])  
>>> linear_sum_assignment(cost_matrix)
(array([1, 2, 4]), array([2, 0, 1]))

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    我相信您正在寻找的是cdistScipy cdist

    Y = cdist(XA, XB, 'euclidean')
    

    这是您的工作代码示例:

    import numpy as np
    from scipy.optimize import linear_sum_assignment
    from scipy.spatial.distance import cdist
    
    np.random.seed(0)
    
    # define tasks 
    t = np.random.rand(5)
    
    # define workers
    w = np.random.rand(3)
    
    # cost_matrix = np.array([[np.linalg.norm(x-y) for x in w] for y in t])  
    cost_matrix = cdist(np.array([t]).T, np.array([w]).T, 'euclidean')
    linear_sum_assignment(cost_matrix)
    

    【讨论】:

      【解决方案2】:

      这可能不是最有效的方法,但迭代会传递给 numpy,所以这可能会更快:

      import numpy as np
      from scipy.optimize import linear_sum_assignment
      
      np.random.seed(0)
      
      # define tasks 
      t = np.random.rand(5)
      
      # define workers
      w = np.random.rand(3)
      
      W, T = np.meshgrid(w, t)
      cost_matrix = abs(T-W)
      

      【讨论】:

      • 为什么不一起广播数组?
      • 试试这个:t.reshape(-1, 1) - w。除了输出之外,这不会为任何东西制作完整的数组。
      猜你喜欢
      • 2015-12-22
      • 2016-06-15
      • 2019-04-01
      • 2021-10-02
      • 2022-07-23
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 2016-08-12
      相关资源
      最近更新 更多