当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python SciPy cKDTree.sparse_distance_matrix用法及代码示例


本文简要介绍 python 语言中 scipy.spatial.cKDTree.sparse_distance_matrix 的用法。

用法:

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

计算稀疏距离矩阵

计算两个 cKDTree 之间的距离矩阵,任何大于 max_distance 的距离都为零。

参数

other cKD树
max_distance 正浮点数
p 浮点数,1<=p<=无穷大

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

output_type 字符串,可选

使用哪个容器来输出数据。选项:‘dok_matrix’, ‘coo_matrix’、‘dict’ 或‘ndarray’。默认值:‘dok_matrix’。

返回

result dok_matrix、coo_matrix、dict 或 ndarray

表示结果的稀疏矩阵,采用 “dictionary of keys” 格式。如果返回字典,则键是索引的 (i,j) 元组。如果output_type是‘ndarray’,包含字段‘i’, ‘j’的记录数组,并且返回‘v’,

例子

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

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

相关用法


注:本文由纯净天空筛选整理自scipy.org大神的英文原创作品 scipy.spatial.cKDTree.sparse_distance_matrix。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。