我有一个矢量数组,我想构建一个矩阵,向我展示它自己的矢量之间的距离。例如,我有这两个向量的矩阵:
[[a, b , c]
[d, e , f]]
我想知道dist是一个欧几里德距离,例如:
[[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]]
答案 0 :(得分:1)
函数pdist
和squareform
可以解决问题:
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'))