scipy.spatial.cKDTree.sparse_distance_matrix

cKDTree.sparse_distance_matrix(self, other, max_distance, p=2.)

计算稀疏距离矩阵

计算两个cKDTree之间的距离矩阵,将大于max_Distance的任何距离保留为零。

参数
othercKDTree
max_distance正浮点
p浮动,1<=p<=无穷大

使用哪个Minkowski p-范数。如果可能发生溢出,有限大的p可能会导致ValueError。

output_type字符串,可选

用于输出数据的容器。选项:‘DOK_MATRIX’、‘COO_MATRIX’、‘DICT’或‘ndarray’。默认值:‘DOK_MATRIX’。

退货
resultDOK_MATRAME、COO_MATRIX、DICT或NDARRAY

以“键字典”格式表示结果的稀疏矩阵。如果返回字典,则键是索引的(i,j)元组。如果output_type为‘ndarray’,则返回具有字段‘i’、‘j’和‘v’的记录数组,

示例

您可以计算两个kd-树之间的稀疏距离矩阵:

>>> import numpy as np
>>> from scipy.spatial import cKDTree
>>> rng = np.random.default_rng()
>>> points1 = rng.random((5, 2))
>>> points2 = rng.random((5, 2))
>>> kd_tree1 = cKDTree(points1)
>>> kd_tree2 = cKDTree(points2)
>>> sdm = kd_tree1.sparse_distance_matrix(kd_tree2, 0.3)
>>> sdm.toarray()
array([[0.        , 0.        , 0.12295571, 0.        , 0.        ],
   [0.        , 0.        , 0.        , 0.        , 0.        ],
   [0.28942611, 0.        , 0.        , 0.2333084 , 0.        ],
   [0.        , 0.        , 0.        , 0.        , 0.        ],
   [0.24617575, 0.29571802, 0.26836782, 0.        , 0.        ]])

您可以检查 max_distance 是零:

>>> from scipy.spatial import distance_matrix
>>> distance_matrix(points1, points2)
array([[0.56906522, 0.39923701, 0.12295571, 0.8658745 , 0.79428925],
   [0.37327919, 0.7225693 , 0.87665969, 0.32580855, 0.75679479],
   [0.28942611, 0.30088013, 0.6395831 , 0.2333084 , 0.33630734],
   [0.31994999, 0.72658602, 0.71124834, 0.55396483, 0.90785663],
   [0.24617575, 0.29571802, 0.26836782, 0.57714465, 0.6473269 ]])