python - 从 numpy 压缩距离矩阵获取整行距离

标签 python numpy

我有一个从一组数据点 x 生成的 numpy 压缩距离矩阵:

dists = scipy.spatial.distance.pdist(x)

对于数据点 i 和 j 之间的距离(假设 i < j),我知道我可以通过以下方式从压缩矩阵中检索索引:

condensed_inx = lambda i,j,n: i*n + j - i*(i+1)/2 - i - 1  # n is the number of data points

然后,我可以通过以下方式获取点 i 和 j 之间的距离:

dists[condensed_inx(i, j, n)]

对于单个距离来说,这是微不足道的。但是,我无法找到一种快速/有效的方法来获取涉及数据点 i 的所有距离的所有距离。这是我目前拥有的:

n = n = scipy.spatial.distance.num_obs_y(dists) #Get number of data points from condensed matrix
for i in range(n):
    #Get all distance indices relative to data point i
    inx = []
    for j in range(n):
        if i < j:
            inx.append(condensed_inx(i, j, n))
        elif i > j:
            inx.append(condensed_inx(j, i, n))
        else:
            continue
    #Get distances relative to data point i
    distance_for_i = dists[np.array(inx, dtype=np.uint64)]

    #Do some calculations with the distances_for_i
    #For example
    print np.mean(distance_for_i)

更新:看起来效率低下来自“condensed_inx”lambda 函数。

最佳答案

除非您正在处理非常大的数组,否则最好使用 squareform 构建平方距离矩阵。然后对每一行进行处理。例如,您的平均示例变为

dists = scipy.spatial.distance.pdist(x)
square = scipy.spatial.distance.squareform(dists)
print square.mean(axis=1)

关于python - 从 numpy 压缩距离矩阵获取整行距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28009579/

相关文章:

python - 无法安装pymorph

python - GeoDjango:无法导入名称 GEOSException 已修复,现在 [WinError 126]

python - 使用 django 模板向后循环

Python C-API int128 支持

python - 如何向量化双线性和二次形式的评估?

python - 如何区分 matplotlib 条形图中特定的 x 条形颜色?

python - 找到所有可逆方阵

python - 在python中计算每年前10名的平均值(groupby,nlargest)

python - Dataframe - 根据条件创建新列

python - 从 SciPy 稀疏矩阵获取左、右、上、下非零邻居