使用numpy.linarg.norm()函数查找数组的最接近点 [英] Finding the closest point of an array using numpy.linarg.norm() function

查看:115
本文介绍了使用numpy.linarg.norm()函数查找数组的最接近点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Python代码:

This is the Python Code:

 import numpy as np

  def find_nearest_vector(array, value):
      idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
      return array[idx]

  A = np.random.random((10,2))*100
  """ 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.50661753]])"""

  pt = [6, 30]  

  print find_nearest_vector(A,pt)

  #array([  6.76626539,  30.50661753])

有人可以向我解释获取最近向量的分步过程吗?函数"find_nearest_vector()"的整个过程.有人可以告诉我此功能的跟踪过程吗?谢谢.

Can somebody explain me the step-by-step process of getting the nearest vector? The whole process of function "find_nearest_vector()". Can someone show me the tracing process of this function? Thank you.

推荐答案

来自维基百科; L2(欧几里得)范数定义为

From Wikipedia; the L2 (Euclidean) norm is defined as

np.linalg.norm只是在numpy中实现此公式,但一次仅适用于两点.另外,正如@unutbu指出的那样,您的实现似乎是不正确,只是偶然地在某些情况下起作用.

np.linalg.norm simply implements this formula in numpy, but only works for two points at a time. Additionally, it appears your implementation is incorrect, as @unutbu pointed out, it only happens to work by chance in some cases.

如果要对此向量化,我建议您使用向量化的numpy自己实现L2规范.

If you want to vectorize this, I'd recommend implementing the L2 norm yourself with vectorised numpy.

pt是一维数组时,此方法有效:

This works when pt is a 1D array:

>>> pt = np.array(pt)
>>> A[((A - pt[ None, :]) ** 2).sum(1).argmin()]
array([ 6.76626539, 30.50661753])  

请注意,最接近的点将具有最小的L2范数以及最小的平方 L2范数,因此,从某种意义上讲,它比另外计算平方的np.linalg.norm效率更高.根.

Note, the closest point will have the smallest L2 norm as well as the smallest squared L2 norm, so this is, in a sense, even more efficient than np.linalg.norm which additionally computes the square root.

这篇关于使用numpy.linarg.norm()函数查找数组的最接近点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆