【问题标题】:Accessing specific pairwise distances in a distance matrix (scipy / numpy)访问距离矩阵中的特定成对距离(scipy / numpy)
【发布时间】:2020-02-21 20:09:57
【问题描述】:

我正在使用scipy 及其cdist 函数从向量数组计算距离矩阵。

import numpy as np
from scipy.spatial import distance


vectorList = [(0, 10), (4, 8), (9.0, 11.0), (14, 14), (16, 19), (25.5, 17.5), (35, 16)]

#Convert to numpy array
arr = np.array(vectorList)

#Computes distances matrix and set self-comparisons to NaN
d = distance.cdist(arr, arr)
np.fill_diagonal(d, None)

假设我想返回低于特定阈值的所有距离(例如6

#Find pairs of vectors whose separation distance is < 6
id1, id2 = np.nonzero(d<6)

#id1 --> array([0, 1, 1, 2, 2, 3, 3, 4]) 
#id2 --> array([1, 0, 2, 1, 3, 2, 4, 3]) 

我现在有 2 个索引数组。

问题:如何将这些向量对之间的距离作为数组/列表返回?

4.47213595499958  #d[0][1]
4.47213595499958  #d[1][0]
5.830951894845301 #d[1][2]
5.830951894845301 #d[2][1]
5.830951894845301 #d[2][2]
5.830951894845301 #d[3][2]
5.385164807134504 #d[3][4]
5.385164807134504 #d[4][3]

d[id1][id2] 返回一个矩阵,而不是一个列表,到目前为止我发现的唯一方法是再次遍历距离矩阵,这没有意义。

np.array([d[i1][i2] for i1, i2 in zip(id1, id2)])

【问题讨论】:

    标签: python-2.7 numpy matrix scipy distance


    【解决方案1】:

    使用

    d[id1, id2]
    

    这是numpy.nonzero 示例显示的形式(即a[np.nonzero(a &gt; 3)]),与您使用的d[id1][id2] 不同。

    有关 numpy 索引的更多详细信息,请参阅 arrays.indexing

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 2011-08-08
      • 1970-01-01
      相关资源
      最近更新 更多