为了账号安全,请及时绑定邮箱和手机立即绑定

vtkSplineRepresentation 的 Actor ()

vtkSplineRepresentation 的 Actor ()

MMMHUHU 2021-12-09 15:28:43
我有几个 numpy 数组,我想比较它们并为给定数组找到最接近的数组。我可以使用https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html计算这些数组之间的距离。但是,有没有办法从几个 numpy 数组中找到两个最接近的数组?因为我得到了阵列print(arr.shape)给(300,)
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

要找到最接近的两个,您需要计算距离矩阵,然后找到该矩阵中的最小值以获得彼此最接近的坐标(使用矩阵您将获得坐标的索引)。


from scipy.spatial import distance

import numpy as np 


coords = np.array([

  (35.0456, -85.2672),

  (35.1174, -89.9711),

  (35.9728, -83.9422),

  (36.1667, -86.7833)

])


distances = distance.cdist(coords, coords, 'euclidean')


# If you don't do that then the distance to self will always 

# be the min. distance in the matrix (always 0): 

np.fill_diagonal(distances, np.inf)


min_index = (np.argmin(distances))

closest = np.unravel_index(min_index, distances.shape)

一旦closest定义了索引,您就可以获得关于最近坐标对的所有信息:


print(f"The two closest are {closest}")

print(f"They are at distance {distances[closest]}")

print(f"Resp. coordinates {coords[closest[0]]} and {coords[closest[1]]}")

输出:


The two closest are (0, 2)

They are at distance 1.6171965990565296

Resp. coordinates [ 35.0456 -85.2672] and [ 35.9728-83.9422]

最后,请注意所有这些输入也将起作用:


coords = np.array([ [35.0456, -85.2672], [35.1174, -89.9711] ])


arr1 = [35.0456, -85.2672]

arr2 = [35.1174, -89.9711]

coords = np.array([arr1, arr2])


查看完整回答
反对 回复 2021-12-09
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

编写一个距离函数,然后使用 itertools 计算列表对之间的距离如何?


例如:


a_1 = [0,3,4,5]

a_2 = [4,7,8,9]

a_3 = [12, 34, 44]


from itertools import combinations


def distance(list1, list2):

    """Distance between two vectors."""

    squares = [(p-q) ** 2 for p, q in zip(list1, list2)]

    return sum(squares) ** .5


distances = []

for pair in combinations([a_1, a_2, a_3], 2):

    distances.append(pair)

    distances.append(distance(list(pair[0]), list(pair[1])))

结果:


 [([0, 3, 4, 5], [4, 7, 8, 9]), 8.0, ([0, 3, 4, 5], [12, 34, 44]), 52.009614495783374, ([4, 7, 8, 9], [12, 34, 44]), 45.70557952810576]



查看完整回答
反对 回复 2021-12-09
  • 2 回答
  • 0 关注
  • 239 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号