【问题标题】:Faster way of calculating a distance matrix with numpy?用numpy计算距离矩阵的更快方法?
【发布时间】:2016-01-27 15:50:39
【问题描述】:

我正在用 numpy/scipy 计算一个矩阵,如下所示:

cost = np.empty([chroma1.data.shape[1], chroma2.data.shape[1]])

for x, cx in enumerate(chroma1.transpose()):
    for y, cy in enumerate(chroma2.transpose()):
        cost[x, y] = sp.distance.euclidean(cx, cy)

这需要相当长的时间。是否有任何 numpy/scipy 函数可以让我摆脱两个嵌套循环?

【问题讨论】:

    标签: python numpy matrix scipy


    【解决方案1】:

    看起来您正在计算距离矩阵。 scipy.spatial.distance 包含几个专门的、优化的函数来做到这一点。

    在你的情况下:

    cost = scipy.spatial.distance.cdist(chroma1.T, chroma2.T)
    

    应该做你想做的。

    【讨论】:

    • 完美,这就是我想要的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2018-11-30
    • 2021-03-05
    • 2012-02-08
    • 2014-09-24
    相关资源
    最近更新 更多