scipy: pdist indexing
scipy.spatial.distance.pdist(X)
gives the pair-wise distances of X
, D
.
Question: how to get scipy.spatial.distance.squareform(D)
?
A good answer from How does condensed distance matrix work? (pdist):
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
Take X.shape[0]
==
i\j | 0 | 1 | 2 | 3 |
---|---|---|---|---|
0 | - | D[0] | D[1] | D[2] |
1 | D[0] | - | D[3] | D[4] |
2 | D[1] | D[3] | - | D[5] |
3 | D[2] | D[4] | D[5] | - |
Suppose the indexing function is
len(D)
=
- When
, - When
, - When
,
So the pattern here is:
Further more:
Comments