【问题标题】:Sklearn : Mean Distance from Centroid of each clusterSklearn:到每个集群的质心的平均距离
【发布时间】:2017-04-11 06:25:46
【问题描述】:

如何找到从质心到每个集群中所有数据点的平均距离。我能够从每个集群的质心找到每个点(在我的数据集中)的欧几里得距离。现在我想找到从质心到每个集群中所有数据点的平均距离。 计算每个质心的平均距离的好方法是什么? 到目前为止,我已经做到了..

def k_means(self):
    data = pd.read_csv('hdl_gps_APPLE_20111220_130416.csv', delimiter=',')
    combined_data = data.iloc[0:, 0:4].dropna()
    #print combined_data
    array_convt = combined_data.values
    #print array_convt
    combined_data.head()


    t_data=PCA(n_components=2).fit_transform(array_convt)
    #print t_data
    k_means=KMeans()
    k_means.fit(t_data)
    #------------k means fit predict method for testing purpose-----------------
    clusters=k_means.fit_predict(t_data)
    #print clusters.shape
    cluster_0=np.where(clusters==0)
    print cluster_0

    X_cluster_0 = t_data[cluster_0]
    #print X_cluster_0


    distance = euclidean(X_cluster_0[0], k_means.cluster_centers_[0])
    print distance


    classified_data = k_means.labels_
    #print ('all rows forst column........')
    x_min = t_data[:, 0].min() - 5
    x_max = t_data[:, 0].max() - 1
    #print ('min is ')
    #print x_min
    #print ('max is ')
    #print x_max

    df_processed = data.copy()
    df_processed['Cluster Class'] = pd.Series(classified_data, index=df_processed.index)
    #print df_processed

    y_min, y_max = t_data[:, 1].min(), t_data[:, 1].max() + 5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 1), np.arange(y_min, y_max, 1))

    #print ('the mesh grid is: ')

    #print xx
    Z = k_means.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    plt.figure(1)
    plt.clf()
    plt.imshow(Z, interpolation='nearest',
               extent=(xx.min(), xx.max(), yy.min(), yy.max()),
               cmap=plt.cm.Paired,
               aspect='auto', origin='lower')


    #print Z


    plt.plot(t_data[:, 0], t_data[:, 1], 'k.', markersize=20)
    centroids = k_means.cluster_centers_
    inert = k_means.inertia_
    plt.scatter(centroids[:, 0], centroids[:, 1],
                marker='x', s=169, linewidths=3,
                color='w', zorder=8)
    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
    plt.xticks(())
    plt.yticks(())
    plt.show()

简而言之,我想计算特定集群中所有数据点与该集群质心的平均距离,因为我需要根据这个平均距离清理我的数据

【问题讨论】:

    标签: python numpy scikit-learn cluster-analysis k-means


    【解决方案1】:

    这是一种方法。如果您想要欧几里得以外的其他距离度量,您可以用函数中的另一个距离度量替换k_mean_distance()

    计算每个分配的聚类和聚类中心的数据点之间的距离并返回平均值。

    距离计算功能:

    def k_mean_distance(data, cx, cy, i_centroid, cluster_labels):
        # Calculate Euclidean distance for each data point assigned to centroid 
        distances = [np.sqrt((x-cx)**2+(y-cy)**2) for (x, y) in data[cluster_labels == i_centroid]]
        # return the mean value
        return np.mean(distances)
    

    并且对于每个质心,使用函数得到平均距离:

    total_distance = []
    for i, (cx, cy) in enumerate(centroids):
        # Function from above
        mean_distance = k_mean_distance(data, cx, cy, i, cluster_labels)
        total_dist.append(mean_distance)
    

    所以,就你的问题而言:

    def k_mean_distance(data, cx, cy, i_centroid, cluster_labels):
            distances = [np.sqrt((x-cx)**2+(y-cy)**2) for (x, y) in data[cluster_labels == i_centroid]]
            return np.mean(distances)
    
    t_data=PCA(n_components=2).fit_transform(array_convt)
    k_means=KMeans()
    clusters=k_means.fit_predict(t_data)
    centroids = km.cluster_centers_
    
    c_mean_distances = []
    for i, (cx, cy) in enumerate(centroids):
        mean_distance = k_mean_distance(t_data, cx, cy, i, clusters)
        c_mean_distances.append(mean_distance)
    

    如果您绘制结果plt.plot(c_mean_distances),您应该会看到如下内容:

    【讨论】:

      【解决方案2】:

      alphaleonis 给出了很好的答案。 对于 n 维度的一般情况,这里是他的答案需要的一些更改:

      def k_mean_distance(data, cantroid_matrix, i_centroid, cluster_labels):
          # Calculate Euclidean distance for each data point assigned to centroid
          distances = [np.linalg.norm(x-cantroid_matrix) for x in data[cluster_labels == i_centroid]]
          # return the mean value
          return np.mean(distances)
      
      for i, cent_features in enumerate(centroids):
                  mean_distance = k_mean_distance(emb_matrix, centroid_matrix, i, kmeans_clusters)
                  c_mean_distances.append(mean_distance)
      

      【讨论】:

        【解决方案3】:

        您可以使用以下 KMeans 属性:

        cluster_centers_ : array, [n_clusters, n_features]

        对于每个点,使用predict(X) 测试它属于哪个集群,然后计算到集群的距离预测返回(它返回索引)。

        【讨论】:

        • 这会给我已经得到的每个集群的质心坐标,现在我需要计算集群中所有数据点到其质心的平均距离。
        【解决方案4】:

        将所有距离计算成一个 numpy 数组。

        然后使用nparray.mean() 得到平均值。

        【讨论】:

        • 这不能回答问题
        猜你喜欢
        • 1970-01-01
        • 2019-11-21
        • 2019-05-06
        • 2019-06-11
        • 2019-01-14
        • 2017-04-10
        • 2017-10-17
        • 1970-01-01
        • 2015-11-06
        相关资源
        最近更新 更多