使用numpy.linalg.norm()函数查找数组最近点的技术实现
如何用numpy.linalg.norm()查找数组中的最近点
我来分享一个用numpy.linalg.norm()函数在数组中查找最近点的实用方法,直接看代码和详细解释:
import numpy as np def find_nearest_vector(array, value): # 计算每个点与目标点的差值向量的范数(欧氏距离),找到最小距离的索引 idx = np.array([np.linalg.norm(x - value) for x in array]).argmin() return array[idx] # 生成一个10行2列的随机数组,元素范围0-100 A = np.random.random((10,2))*100
代码逻辑说明
array - value:对数组中的每个点和目标点执行逐元素减法,得到每个点相对于目标点的差值向量np.linalg.norm(x - value):计算每个差值向量的欧氏距离(也就是两点间的直线距离)argmin():找出距离最小的元素索引,最后返回数组中对应索引的点
示例数组A(随机生成,每次运行结果不同)
array([[ 34.19762933, 43.14534123], [ 48.79558706, 47.79243283], [ 38.42774411, 84.87155478], [ 63.64371943, 50.7722317 ], [ 73.56362857, 27.87895698], [ 96.67790593, 77.76150486], [ 68.86202147, 21.38735169], [ 5.21796467, 59.17051276], [ 82.92389467, 99.90387851], [ 6.76626539, 30.50128714]])
内容的提问来源于stack exchange,提问作者Charlotte Sampiano
相关产品推荐
相关产品推荐

