你是否尝试聚类dataPoints
通过最近的索引centroids
,并找出聚类点的平均位置?如果是,我建议使用 numpy 的一些广播规则来获取您需要的输出。
考虑到这一点,
np.linalg.norm(centroids[None, :, :] - dataPoints[:, None, :], axis=-1)
它创建一个矩阵,显示之间的所有距离dataPoints
and centroids
,
array([[ 40.01249805, 11.18033989, 11.40175425],
[ 42.3792402 , 17.02938637, 16.2788206 ],
[ 59.39696962, 43.01162634, 42.05948169],
[ 55.97320788, 41.77319715, 40.79215611],
[ 17.69180601, 20.80865205, 20.24845673],
[ 41.72529209, 28.01785145, 27.01851217],
[ 20.80865205, 44.01136217, 43.65775991],
[ 65.9241989 , 66.48308055, 65.520989 ]])
你可以通过这个技巧计算最近质心的索引(为了便于阅读,它们被分成 3 行),
In: t0 = centroids[None, :, :] - dataPoints[:, None, :]
In: t1 = np.linalg.norm(t0, axis=-1)
In: t2 = np.argmin(t1, axis=-1)
Now t2
有索引,
array([1, 2, 2, 2, 0, 2, 0, 2])
要查找 #1 簇,请使用布尔掩码t2 == 0
,
In: dataPoints[t2 == 0]
Out: array([[16, 32],
[20, 56]])
In: dataPoints[t2 == 1]
Out: array([[2, 4]])
In: dataPoints[t2 == 2]
Out: array([[17, 4],
[45, 2],
[45, 7],
[32, 14],
[68, 33]])
或者只是计算你的情况的平均值,
In: np.mean(dataPoints[t2 == 0], axis=0)
Out: array([ 18., 44.])
In: np.mean(dataPoints[t2 == 1], axis=0)
Out: array([ 2., 4.])
In: np.mean(dataPoints[t2 == 2], axis=0)
Out: array([ 41.4, 12. ])
当然,如果需要,后面的块可以在 for 循环中重写。
在我看来,通过 numpy 的约定来制定解决方案可能是一个很好的做法。