scipy.spatial.KDTree.
sparse_distance_matrix#
- KDTree.sparse_distance_matrix(other, max_distance, p=2.0, output_type='dok_matrix')[來源]#
計算稀疏距離矩陣。
計算兩個 KDTree 之間的距離矩陣,將大於 max_distance 的任何距離設為零。
- 參數:
- otherKDTree
- max_distance正浮點數
- pfloat, 1<=p<=infinity
要使用的 Minkowski p-範數。如果可能發生溢位,有限大的 p 可能會導致 ValueError。
- output_type字串,選用
用於輸出資料的容器。選項:‘dok_matrix’、‘coo_matrix’、‘dict’ 或 ‘ndarray’。預設值:‘dok_matrix’。
在 1.6.0 版本中新增。
- 返回:
- resultdok_matrix、coo_matrix、dict 或 ndarray
以「dictionary of keys」格式表示結果的稀疏矩陣。如果返回的是 dict,則鍵是 (i,j) 索引元組。如果 output_type 是 ‘ndarray’,則會返回帶有欄位 ‘i’、‘j’ 和 ‘v’ 的記錄陣列。
範例
您可以計算兩個 kd-tree 之間的稀疏距離矩陣
>>> import numpy as np >>> from scipy.spatial import KDTree >>> rng = np.random.default_rng() >>> points1 = rng.random((5, 2)) >>> points2 = rng.random((5, 2)) >>> kd_tree1 = KDTree(points1) >>> kd_tree2 = KDTree(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 ]])