unstable result from scipy.cluster.kmeans

╄→尐↘猪︶ㄣ 提交于 2019-12-06 03:15:39

That's because if you pass an integer as the k_or_guess parameter, k initial centroids are chosen randomly from the set of input observations (this is known as the Forgy method).

From the docs:

k_or_guess : int or ndarray

The number of centroids to generate. A code is assigned to each centroid, which is also the row index of the centroid in the code_book matrix generated.

The initial k centroids are chosen by randomly selecting observations from the observation matrix. Alternatively, passing a k by N array specifies the initial k centroids.

Try handing it a guess instead:

kmeans(data,np.array([1,3,7]),100)

# (array([1, 3, 7]), 0.0)
# (array([1, 3, 7]), 0.0)
# (array([1, 3, 7]), 0.0)

From the docs:

k_or_guess: int or ndarray

The number of centroids to generate. A code is assigned to each centroid, which is also the row index of the centroid in the code_book matrix generated.

The initial k centroids are chosen by randomly selecting observations

So resulting order of clusters is random. If you want more control with this, you can specify

Alternatively, passing a k by N array specifies the initial k centroids

I would not reccomend latter in general case, as different starting clusters [may] lead to different clustering, and predefined initial centroids can lead to suboptimal solution.

In your simple case resulting clustering is always the same (optimal) modulo clusters order:

>>> centroids, _ = kmeans(data,3,100)
>>> idx, _  = vq(data, centroids)
>>> centroids, idx
array([1, 7, 3]), array([0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1])
>>> centroids, _ = kmeans(data,3,100)
>>> idx, _  = vq(data, centroids)
>>> centroids, idx
array([3, 7, 1]), array([2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!