Python 向量数组与其之间的距离';自身因素

Python 向量数组与其之间的距离';自身因素,python,numpy,matrix,vector,scikit-learn,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学习一些东西 #Create clusters containing t

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

[[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]]
预期结果=[[0,2,4.58257569,4.897949],
[2, 0, 4.35889894, 4.47213595], 
[4.58257569,  4.35889894, 0, 2.64575131], 
[4.89897949, 4.47213595, 2.64575131, 0]]
函数和将执行以下操作:

[897]中的
:将numpy作为np导入
…:从scipy.spatial.distance导入pdist,squareform
在[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]])
在[899]中:正方形(pdist(输入矩阵))
出[899]:
数组([[0,2,4.58257569,4.897949],
[2.        , 0.        , 4.35889894, 4.47213595],
[4.58257569, 4.35889894, 0.        , 2.64575131],
[4.89897949, 4.47213595, 2.64575131, 0.        ]])
正如预期的那样,生成的距离矩阵是对称阵列

默认情况下,
pdist
计算欧几里德距离。通过在函数调用中将适当的值传递给参数
metric
,可以计算不同的距离。例如:

[[dist(vect1,vect1), dist(vect1,vect2)]
 [dist(vect2,vect1), dist(vect2,vect2)]]
[900]中的
:方形(pdist(输入矩阵,公制='jaccard'))
出[900]:
数组([[0,1,0.875,0.71428571],
[1.        , 0.        , 0.875     , 0.85714286],
[0.875     , 0.875     , 0.        , 1.        ],
[0.71428571, 0.85714286, 1.        , 0.        ]])

多么神秘啊,你的最后一行看起来应该返回一个对称矩阵?!你能在你的代码中包含一些数据,这样我们就可以运行并验证你的结果吗?我知道这个方法不起作用,但我仍然尝试测试它,所以。。。如果你想的话,我可以添加一个例子。我可以像jaccard这样改变距离吗?