2015-10-08 59 views
5

我有一個四個用戶之間的相似矩陣。我想做一個凝聚聚類。代碼是這樣的:sklearn凝聚聚類輸入數據

lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1') 
X = np.reshape(lena, (-1, 1)) 

print("Compute structured hierarchical clustering...") 
st = time.time() 
n_clusters = 3 # number of regionsle 


ward = AgglomerativeClustering(n_clusters=n_clusters, 
     linkage='complete').fit(X) 
print ward 
label = np.reshape(ward.labels_, lena.shape) 
print("Elapsed time: ", time.time() - st) 
print("Number of pixels: ", label.size) 
print("Number of clusters: ", np.unique(label).size) 
print label 

標籤的打印結果是這樣的:

[[1 1 0 0] 
[1 1 0 0] 
[0 0 1 2] 
[0 0 2 1]] 

這是否意味着它給人的可能集羣結果列表中,我們可以選擇一個從他們身上?喜歡選擇:[0,0,2,1]。如果是錯誤的,你能告訴我怎麼做基於相似性的凝聚算法嗎?如果它是正確的,相似矩陣是巨大的,我怎麼能從一個巨大的列表中選擇最優的聚類結果?由於

回答

1

我覺得這裏的問題是,你適合你的模型錯誤的數據

# This will return a 4x4 matrix (similarity matrix) 
lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1') 

# However this will return 16x1 matrix 
X = np.reshape(lena, (-1, 1)) 

真正的結果你得到的是這樣的:

ward.labels_ 
>> array([1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 2, 0, 0, 2, 1]) 

這是每個元素的標籤, X矢量,它不會使敏感

如果我很好理解你的問題,你需要通過它們之間的距離(相似性)來分類你的用戶。那麼,在這種情況下,我會建議使用這樣的譜聚類:

import numpy as np 
from sklearn.cluster import SpectralClustering 

lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1') 

n_clusters = 3 
SpectralClustering(n_clusters).fit_predict(lena) 

>> array([1, 1, 0, 2], dtype=int32) 
+0

但是,如果他需要一個層次聚類呢? – Itay