2016-11-27 192 views
2

我怎樣才能找到從質心到每個簇中所有數據點的平均距離。我能夠從每個羣集的質心找到每個點(在我的數據集中)的歐氏距離。現在我想查找從質心到每個羣集中所有數據點的平均距離。 從每個質心計算平均距離的好方法是什麼? 到目前爲止,我已經做到了這一點..Sklearn:每個簇的質心的平均距離

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() 

總之我想從集羣的重心計算特別是集羣中的所有數據點的平均距離,因爲我需要清理的基礎上,我的數據這意味着距離

回答

1

可以使用KMEANS的以下屬性:

cluster_centers_ : array, [n_clusters, n_features]

對於每一個點,測試它屬於什麼ü集羣唱predict(X)和之後,計算距離羣集預測回報(它返回索引)。

+0

這會給我,我已經得到了每個集羣的質心座標,現在我需要計算在集羣中的質心的所有數據點的平均距離。 – Rezwan

0

將所有距離計算爲一個numpy數組。

然後用nparray.mean()來得到平均值。

0

這是一種方法。如果需要除歐幾里得以外的另一個距離度量,則可以在函數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)你應該看到這樣的事情:

kmeans clusters vs mean value

相關問題