【问题标题】:Kmeans getting same result but changing classes it starts withKmeans 得到相同的结果,但改变了它开始的类
【发布时间】:2019-02-02 08:08:58
【问题描述】:

我正在对希望分类的图像运行 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

【问题讨论】:

    标签: python pandas k-means


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 2019-01-30
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多