Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
NumPy
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Nearest-neighbor search === Iterative Python algorithm and vectorized NumPy version. <syntaxhighlight lang="numpy"> >>> # # # Pure iterative Python # # # >>> points = [[9,2,8],[4,7,2],[3,4,4],[5,6,9],[5,0,7],[8,2,7],[0,3,2],[7,3,0],[6,1,1],[2,9,6]] >>> qPoint = [4,5,3] >>> minIdx = -1 >>> minDist = -1 >>> for idx, point in enumerate(points): # iterate over all points ... dist = sum([(dp-dq)**2 for dp,dq in zip(point,qPoint)])**0.5 # compute the euclidean distance for each point to q ... if dist < minDist or minDist < 0: # if necessary, update minimum distance and index of the corresponding point ... minDist = dist ... minIdx = idx >>> print(f"Nearest point to q: {points[minIdx]}") Nearest point to q: [3, 4, 4] >>> # # # Equivalent NumPy vectorization # # # >>> import numpy as np >>> points = np.array([[9,2,8],[4,7,2],[3,4,4],[5,6,9],[5,0,7],[8,2,7],[0,3,2],[7,3,0],[6,1,1],[2,9,6]]) >>> qPoint = np.array([4,5,3]) >>> minIdx = np.argmin(np.linalg.norm(points-qPoint, axis=1)) # compute all euclidean distances at once and return the index of the smallest one >>> print(f"Nearest point to q: {points[minIdx]}") Nearest point to q: [3 4 4] </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)