我有一个向量数组,我想建立一个矩阵,显示它自己向量之间的距离。例如,我有两个向量的矩阵:
[[a, b , c]
[d, e , f]]
我想得到dist是欧几里德距离,例如:
[[dist(vect1,vect1), dist(vect1,vect2)]
[dist(vect2,vect1), dist(vect2,vect2)]]
显然,我期望一个对角线上有空值的对称矩阵。我试着用scikit学习一些东西。你知道吗
#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]]
函数^{} 和^{} 将实现以下功能:
正如所料,
result
是一个对称数组:默认情况下
pdist
计算欧氏距离。您可以通过在函数调用中指定适当的度量来计算不同的距离。例如:相关问题 更多 >
编程相关推荐