压缩距离矩阵转换为完整距离矩阵
pdist
返回的压缩距离矩阵可以通过使用 scipy.spatial.distance.squareform
转换为完整距离矩阵:
>>> import numpy as np
>>> from scipy.spatial.distance import pdist, squareform
>>> points = np.array([[0,1],[1,1],[3,5], [15, 5]])
>>> dist_condensed = pdist(points)
>>> dist_condensed
array([ 1. , 5. , 15.5241747 , 4.47213595,
14.56021978, 12. ])
使用 squareform
来转换成完全矩阵:
>>> dist = squareform(dist_condensed)
array([[ 0. , 1. , 5. , 15.5241747 ],
[ 1. , 0. , 4.47213595, 14.56021978],
[ 5. , 4.47213595, 0. , 12. ],
[ 15.5241747 , 14.56021978, 12. , 0. ]])
点 i,j 之间的距离存储在 dist[i, j] 中:
>>> dist[2, 0]
5.0
>>> np.linalg.norm(points[2] - points[0])
5.0
从索引到压缩矩阵的索引
可以将用于访问方阵元素的索引转换为压缩矩阵中的索引:
def square_to_condensed(i, j, n):
assert i != j, "no diagonal elements in condensed matrix"
if i < j:
i, j = j, i
return n*j - j*(j+1)//2 + i - 1 - j
例子:
>>> square_to_condensed(1, 2, len(points))
3
>>> dist_condensed[3]
4.4721359549995796
>>> dist[1,2]
4.4721359549995796
压缩索引指标
不使用方阵也可以进行另一种方向的操作,这样在运行时间和内存消耗方面更好:
import math
def calc_row_idx(k, n):
return int(math.ceil((1/2.) * (- (-8*k + 4 *n**2 -4*n - 7)**0.5 + 2*n -1) - 1))
def elem_in_i_rows(i, n):
return i * (n - 1 - i) + (i*(i + 1))//2
def calc_col_idx(k, i, n):
return int(n - elem_in_i_rows(i + 1, n) + k)
def condensed_to_square(k, n):
i = calc_row_idx(k, n)
j = calc_col_idx(k, i, n)
return i, j
例子:
>>> condensed_to_square(3, 4)
(1.0, 2.0)
使用squareform进行运行时比较
>>> import numpy as np
>>> from scipy.spatial.distance import pdist, squareform
>>> points = np.random.random((10**4,3))
>>> %timeit dist_condensed = pdist(points)
1 loops, best of 3: 555 ms per loop
生成方阵形式的过程非常缓慢:
>>> dist_condensed = pdist(points)
>>> %timeit dist = squareform(dist_condensed)
1 loops, best of 3: 2.25 s per loop
如果我们正在寻找最大距离的两个点,那么在完整矩阵中搜索是O(n),而在紧凑形式中只有O(n/2)也就不足为奇了:
>>> dist = squareform(dist_condensed)
>>> %timeit dist_condensed.argmax()
10 loops, best of 3: 45.2 ms per loop
>>> %timeit dist.argmax()
10 loops, best of 3: 93.3 ms per loop
获取两个点的索引在两种情况下几乎不需要时间,但是计算压缩索引当然会有一些开销:
>>> idx_flat = dist.argmax()
>>> idx_condensed = dist.argmax()
>>>
100000 loops, best of 3: 2.28 µs per loop
>>>
100000 loops, best of 3: 14.7 µs per loop
list(combinations(range(4), 2))
会得到[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
。该列表中的每个元组都具有形式(行索引,列索引),因此它对应于上三角。 - Warren Weckesser