python - 向量数组与其自身元素的距离

标签 python numpy matrix vector scikit-learn

我有一个向量数组,我想构建一个矩阵来显示它自己的向量之间的距离。例如,我得到了包含这两个向量的矩阵:

[[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]]

最佳答案

函数pdistsquareform会成功的:

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 计算euclidean 距离。您可以通过将适当的值传递给函数调用中的参数 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.        ]])

关于python - 向量数组与其自身元素的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36756427/

相关文章:

python - 使用 BFS 在二叉树中查找并排序表兄弟

python - 从大流中选择一个随机元素有什么大不了的?

python - Matplotlib 按钮生成随机圆圈

python - 将代码从 Tensorflow 1 迁移到 Tensorflow 2 时,如何处理属性错误 : 'Adam' object has no attribute 'compute_gradient' ?

python - 音频组的成员无法访问/dev/dsp 来播放声音

matlab - 确保矩阵是对称的(并且是正半定的)

matlab - 在 MATLAB 中删除统一列

r - 计算R中逻辑矩阵的列数

python - 如何使用 np.where 使用先前的行创建新列?

python - 用于python回归聚类的库?