gpt4 book ai didi

python - 压缩距离矩阵如何工作? (pdist)

转载 作者:IT老高 更新时间:2023-10-28 20:21:25 24 4
gpt4 key购买 nike

scipy.spatial.distance.pdist 返回一个压缩的距离矩阵。来自 the documentation :

Returns a condensed distance matrix Y. For each and (where ), the metric dist(u=X[i], v=X[j]) is computed and stored in entry ij.

我认为 ij 的意思是 i*j。但我想我可能错了。考虑

X = array([[1,2], [1,2], [3,4]])
dist_matrix = pdist(X)

然后文档说 dist(X[0], X[2]) 应该是 dist_matrix[0*2]。但是,dist_matrix[0*2] 是 0——而不是应该的 2.8。

在给定 ij 的情况下,我应该使用什么公式来访问两个向量的相似性?

最佳答案

你可以这样看:假设 x 是 m × n。一次选择两个可能的 m 行对是 itertools.combinations(range(m), 2),例如,对于 m=3:

>>> import itertools
>>> list(combinations(range(3),2))
[(0, 1), (0, 2), (1, 2)]

所以如果 d = pdist(x)combinations(range(m), 2)) 中的第 k 个元组给出与 d[k] 关联的 x 行的索引。

例子:

>>> x = array([[0,10],[10,10],[20,20]])
>>> pdist(x)
array([ 10. , 22.36067977, 14.14213562])

第一个元素是 dist(x[0], x[1]),第二个是 dist(x[0], x[2]) 和第三个是dist(x[1], x[2])

或者您可以将其视为平方距离矩阵的上三角部分中的元素,串在一起形成一维数组。

例如

>>> squareform(pdist(x)) 
array([[ 0. , 10. , 22.361],
[ 10. , 0. , 14.142],
[ 22.361, 14.142, 0. ]])

>>> y = array([[0,10],[10,10],[20,20],[10,0]])
>>> squareform(pdist(y))
array([[ 0. , 10. , 22.361, 14.142],
[ 10. , 0. , 14.142, 10. ],
[ 22.361, 14.142, 0. , 22.361],
[ 14.142, 10. , 22.361, 0. ]])
>>> pdist(y)
array([ 10. , 22.361, 14.142, 14.142, 10. , 22.361])

关于python - 压缩距离矩阵如何工作? (pdist),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com