Kmeans 得到相同的结果但改变 类 它以

Kmeans getting same result but changing classes it starts with

我正在 运行对我希望分类的图像进行 kmeans 聚类。当我 运行 该程序时,我得到相同的结果,期望我的颜色不一致,这意味着 kmeans 没有重复完全相同的过程。每次执行程序时如何保持 类 等于相同的值?

这里有两个例子。集合中的第一张图像是 kmeans 聚类结果,第二张是图像上的分类图。

第 1 组

设置2

代码:

#Set a 6 KMeans clustering
    kmeans = KMeans(n_clusters = 4, n_jobs = -2)

    #Compute cluster centers and predict cluster indices
    X_clustered = kmeans.fit_predict(x_3d)

    # Display scatter of kmeans
    plt.scatter(X[:, 0], X[:, 1], c=X_clustered, s=5, cmap='viridis')
    plt.show()

    # Create a temp dataframe from our PCA projection data "x_3d"
    df = pd.DataFrame(x_3d)
    df['X_cluster'] = X_clustered

    #create an greyscale image and remap the color pixel based on the df file given
    gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    tempImage = img
    row,col = img.shape[:2]
    count = 0
    for i in range(row):
        for j in range(col):
            if X_clustered[count]==0:
                tempImage[i,j] = (255,255,255,1)
            elif X_clustered[count]==1:
                tempImage[i,j] = (0,255,0,1)
            elif X_clustered[count]==2:
                tempImage[i,j] = (0,0,255,1)
            elif X_clustered[count]==3:
                tempImage[i,j] = (125,125,0,1)
            elif X_clustered[count]==4:
                tempImage[i,j] = (0,125,125,1)
            elif X_clustered[count]==5:
                tempImage[i,j] = (125,0,125,1)
            elif X_clustered[count]==6:
                tempImage[i,j] = (255,255,0,1)
            elif X_clustered[count]==7:
                tempImage[i,j] = (255,0,255,1)
            elif X_clustered[count]==8:
                tempImage[i,j] = (0,255,255,1)
            elif X_clustered[count]==9:
                tempImage[i,j] = (125,125,125)  
            count+= 1

    return tempImage

K-Means 算法的初始化 不是确定性的。

如果您使用的是 scikit-learn 的 KMeans,那么您可以提供自己的初始化 (init=...),或者您可以提供随机种子,这样每次都会生成相同的随机数 ( random_state=42).