K 均值结果索引在秒内不同 运行

K-Means Result-Index differs in second run

我是 运行 一些统计数据的 K-Means。我的矩阵大小是 [192x31634]。 K-Means 表现良好并创建了我想要的 7 个质心的数量。所以我的结果是 [192x7]

作为一些自我检查,我将获得的索引值存储在 K-Means 运行 字典中。

    centroids,idx = runkMeans(X_train, initial_centroids, max_iters)
    resultDict.update({'centroid' : centroids})
    resultDict.update({'idx' : idx})

然后我在用于查找质心的相同数据上测试我的 K-Means。奇怪的是我的结果不同:

    dict= pickle.load(open("MyDictionary.p", "rb"))         
    currentIdx = findClosestCentroids(X_train, dict['centroid'])
    print("idx Differs: ",np.count_nonzero(currentIdx != dict['idx']))

输出:

idx Differs: 189

谁能给我解释一下这个区别?我将算法的最大迭代次数调高到 50,这似乎太多了。 @Joe Halliwell 指出,K-Means 是不确定的。 findClosestCentroids 被 runkMeans 调用。我不明白为什么两个 idx 的结果会不同。感谢您的任何想法。

这是我的代码:

    def findClosestCentroids(X, centroids):
        K = centroids.shape[0]
        m = X.shape[0]
        dist = np.zeros((K,1))
        idx = np.zeros((m,1), dtype=int)
        #number of columns defines my number of data points
        for i in range(m):
            #Every column is one data point
            x = X[i,:]
            #number of rows defines my number of centroids
            for j in range(K):
                #Every row is one centroid
                c = centroids[j,:]
                #distance of the two points c and x
                dist[j] = np.linalg.norm(c-x)
                #if last centroid is processed
                if (j == K-1):
                    #the Result idx is set with the index of the centroid with minimal distance
                    idx[i] = np.argmin(dist)
        return idx

    def runkMeans(X, initial_centroids, max_iters):
        #Initialize values
        m,n = X.shape
        K = initial_centroids.shape[0]
        centroids = initial_centroids
        previous_centroids = centroids
        for i in range(max_iters):
            print("K_Means iteration:",i)
            #For each example in X, assign it to the closest centroid
            idx = findClosestCentroids(X, centroids)
            #Given the memberships, compute new centroids
            centroids = computeCentroids(X, idx, K)
        return centroids,idx

编辑:我把我的 max_iters 变成了 60,得到了

idx Differs: 0

似乎是问题所在。

K-means 是一种非确定性算法。人们通常通过设置随机种子来控制这一点。例如,SciKit Learn 的实现为此目的提供了 random_state 参数:

from sklearn.cluster import KMeans
import numpy as np
X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)

请参阅 https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

处的文档