为什么kmeans每次都会给出完全相同的结果?

时间:2020-10-30 07:33:01

标签: python-3.x scikit-learn k-means

我已经重新运行kmeans 4次并获得

enter image description here

从其他答案中我知道了

K-Means每次都会初始化质心,它是随机生成的。

您能解释一下每次结果为何完全相同吗?

import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt 
from sklearn.cluster import KMeans
%config InlineBackend.figure_format = 'svg' # Change the image format to svg for better quality
don = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/Deep-Learning/main/donclassif.txt.gz', sep=';')

fig, ax = plt.subplots(nrows=2, ncols=2, figsize= 2 * np.array(plt.rcParams['figure.figsize']))

for row in ax:
    for col in row:
        kmeans = KMeans(n_clusters = 4)
        kmeans.fit(don)
        y_kmeans = kmeans.predict(don)
        col.scatter(don['V1'], don['V2'], c = y_kmeans, cmap = 'viridis')
        centers = kmeans.cluster_centers_
        col.scatter(centers[:, 0], centers[:, 1], c = 'red', s = 200, alpha = 0.5);

plt.show()

2 个答案:

答案 0 :(得分:2)

它们不一样。它们是相似的。 K-means是一种算法,它以迭代方式移动质心,从而使它们在拆分数据时变得越来越好,尽管此过程是确定性的,但您必须为这些质心选择初始值,并且通常是随机进行的。随机开始,并不意味着最终质心将是随机的。它们将收敛到相对较好且通常相似的东西。

通过以下简单修改来查看您的代码:

import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt 
from sklearn.cluster import KMeans
%config InlineBackend.figure_format = 'svg' # Change the image format to svg for better quality
don = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/Deep-Learning/main/donclassif.txt.gz', sep=';')

fig, ax = plt.subplots(nrows=2, ncols=2, figsize= 2 * np.array(plt.rcParams['figure.figsize']))

cc = []

for row in ax:
    for col in row:
        kmeans = KMeans(n_clusters = 4)
        kmeans.fit(don)
        cc.append(kmeans.cluster_centers_)
        y_kmeans = kmeans.predict(don)
        col.scatter(don['V1'], don['V2'], c = y_kmeans, cmap = 'viridis')
        centers = kmeans.cluster_centers_
        col.scatter(centers[:, 0], centers[:, 1], c = 'red', s = 200, alpha = 0.5);

plt.show()

cc

如果您查看这些质心的确切值,它们将像这样:

[array([[ 4.97975722,  4.93316461],
        [ 5.21715504, -0.18757547],
        [ 0.31141141,  0.06726803],
        [ 0.00747797,  5.00534801]]),
 array([[ 5.21374245, -0.18608103],
        [ 0.00747797,  5.00534801],
        [ 0.30592308,  0.06549162],
        [ 4.97975722,  4.93316461]]),
 array([[ 0.30066361,  0.06804847],
        [ 4.97975722,  4.93316461],
        [ 5.21017831, -0.18735444],
        [ 0.00747797,  5.00534801]]),
 array([[ 5.21374245, -0.18608103],
        [ 4.97975722,  4.93316461],
        [ 0.00747797,  5.00534801],
        [ 0.30592308,  0.06549162]])]

相似,但值集不同。

也:

看看KMeans的默认参数。有一个叫做n_init的东西:

以不同的方式运行k-means算法的时间 重心种子。最终结果将是的最佳输出 n_init连续运行的惯性。

默认情况下,它等于10。这意味着,每次运行k均值时,它实际上运行10次并获得最佳结果。与单次k均值的结果相比,那些最佳结果将更加相似。

答案 1 :(得分:0)

我发布@AEF的评论以从未答复的列表中删除此问题。

随机初始化不一定意味着随机结果。最简单的例子:k-means的k = 1总是在一步之内找到均值,而不管中心在哪里初始化。