NumPy: vectorize sum of distances to a set of points

你离开我真会死。 提交于 2020-01-05 05:43:07

问题


I'm trying to implementing a k-medoids clustering algorithm in Python/NumPy. As part of this algo, I have to compute the sum of distances from objects to their "medoids" (cluster representatives).

I have: a distance matrix on five points

n_samples = 5
D = np.array([[ 0.        ,  3.04959014,  4.74341649,  3.72424489,  6.70298441],
              [ 3.04959014,  0.        ,  5.38516481,  4.52216762,  6.16846821],
              [ 4.74341649,  5.38516481,  0.        ,  1.02469508,  8.23711114],
              [ 3.72424489,  4.52216762,  1.02469508,  0.        ,  7.69025357],
              [ 6.70298441,  6.16846821,  8.23711114,  7.69025357,  0.        ]])

a set of initial medoids

medoids = np.array([0, 3])

and the cluster memberships

cl = np.array([0, 0, 1, 1, 0])

I can compute the required sum using

>>> np.sum(D[i, medoids[cl[i]]] for i in xrange(n_samples))
10.777269622938899

but that uses a Python loop. Am I missing some kind of vectorized idiom for computing this sum?


回答1:


How about:

In [17]: D[np.arange(n_samples),medoids[cl]].sum()
Out[17]: 10.777269629999999


来源:https://stackoverflow.com/questions/8637475/numpy-vectorize-sum-of-distances-to-a-set-of-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!