Find the minimum value index in the compressed distance matrix pdist

I used scipy.spatial.distance.pdist(X)to calculate the Euclidean metric of the distance between each pair of elements below list X:

X = [[0, 3, 4, 2], [23, 5, 32, 1], [3, 4, 2, 1], [33, 54, 5, 12]]

This returns a matrix with a compacted distance:

array([ 36.30426972,   3.87298335,  61.57109712,  36.06937759,
        57.88782255,  59.41380311])

For each element of X, I need to find the index of the next other element.

Converting the squared distance matrix into a square shape helps to visualize the results, but I cannot figure out how to programmatically identify the index of the nearest element X for each element in X.

array([[  0.        ,  36.30426972,   3.87298335,  61.57109712],
       [ 36.30426972,   0.        ,  36.06937759,  57.88782255],
       [  3.87298335,  36.06937759,   0.        ,  59.41380311],
       [ 61.57109712,  57.88782255,  59.41380311,   0.        ]])

I believe that argmin()is a function that I use, but I lost here. Thanks for any help in advance.

+4
source share
1

. -, "- -",

numpy.fill_diagonal(distances, numpy.inf)

argmin :

closest_points = distances.argmin(axis=0)
+6

All Articles