2016-04-20 32 views
0

我有一個矢量數組,我想要建立一個矩陣,顯示它自己的矢量之間的距離。比如我有一個矩陣與向量2:從它自己的元素的矢量陣列的距離

[[a, b , c] 
[d, e , f]] 

,我想拿到哪裏DIST例如是歐幾里得距離:obvisously我期待一個對稱的

[[dist(vect1,vect1), dist(vect1,vect2)] 
[dist(vect2,vect1), dist(vect2,vect2)]] 

所以在對角線上具有空值的矩陣。我嘗試使用scikit-learn。

#Create clusters containing the similar vectors from the clustering algo 
labels = db.labels_ 
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) 
list_cluster = [[] for x in range(0,n_clusters_ + 1)] 
for index, label in enumerate(labels): 
    if label == -1: 
     list_cluster[n_clusters_].append(sparse_matrix[index]) 
    else: 
     list_cluster[label].append(sparse_matrix[index]) 
vector_rows = [] 
for cluster in list_cluster: 
    for row in cluster: 
     vector_rows.append(row) 
#Create my array of vectors per cluster order 
sim_matrix = np.array(vector_rows) 
#Build my resulting matrix 
sim_matrix = metrics.pairwise.pairwise_distances(sim_matrix, sim_matrix) 

問題是我得到的矩陣不是對稱的,所以我想有一些錯誤在我的代碼。

我加入少許樣本,如果你想測試,我每個向量的歐氏距離矢量做到了:

input_matrix = [[0, 0, 0, 3, 4, 1, 0, 2],[0, 0, 0, 2, 5, 2, 0, 3],[2, 1, 1, 0, 4, 0, 2, 3],[3, 0, 2, 0, 5, 1, 1, 2]] 

expecting_result = [[0, 2, 4.58257569, 4.89897949],[2, 0, 4.35889894, 4.47213595],[4.58257569, 4.35889894, 0, 2.64575131],[4.89897949, 4.47213595, 2.64575131, 0]] 
+1

多麼神祕,你的最後一行肯定看起來應該返回一個對稱矩陣?!你能否在你的代碼中包含一些數據,以便我們可以運行並驗證你的結果? – maxymoo

+0

我知道該方法不起作用,但我仍試圖測試它,所以...我添加一個例子,如果你想。 – mel

回答

1

功能pdistsquareform將這樣的伎倆:

import numpy as np 
from scipy.spatial.distance import pdist 
from scipy.spatial.distance import squareform 
input_matrix = np.asarray([[0, 0, 0, 3, 4, 1, 0, 2], 
          [0, 0, 0, 2, 5, 2, 0, 3], 
          [2, 1, 1, 0, 4, 0, 2, 3], 
          [3, 0, 2, 0, 5, 1, 1, 2]]) 
result = squareform(pdist(input_matrix)) 
print(result) 

正如預期的那樣,result是一個對稱陣列:

[[ 0.   2.   4.58257569 4.89897949] 
[ 2.   0.   4.35889894 4.47213595] 
[ 4.58257569 4.35889894 0.   2.64575131] 
[ 4.89897949 4.47213595 2.64575131 0.  ]] 

默認情況下,pdist計算歐幾里得距離。您可以通過在函數調用中指定適當的度量來計算不同的距離。例如:

result = squareform(pdist(input_matrix, metric='jaccard')) 
+0

我可以改變像jaccard等距離嗎? – mel