我有一个向量数组,我想建立一个矩阵,向我显示它自己的向量之间的距离。例如,我有包含这两个向量的矩阵:
[[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]]
expected_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
和 squareform
将完成:
In [897]: import numpy as np
...: from scipy.spatial.distance import pdist, squareform
In [898]: 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]])
In [899]: squareform(pdist(input_matrix))
Out[899]:
array([[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
计算欧氏距离。您可以通过在函数调用中将正确的值传递给参数metric
来计算不同的距离。例如:
In [900]: squareform(pdist(input_matrix, metric='jaccard'))
Out[900]:
array([[0. , 1. , 0.875 , 0.71428571],
[1. , 0. , 0.875 , 0.85714286],
[0.875 , 0.875 , 0. , 1. ],
[0.71428571, 0.85714286, 1. , 0. ]])