Skip to content

Instantly share code, notes, and snippets.

@bryanyang0528
Created October 28, 2015 03:16
Show Gist options
  • Save bryanyang0528/4d0f49dd4f89f06d6929 to your computer and use it in GitHub Desktop.
Save bryanyang0528/4d0f49dd4f89f06d6929 to your computer and use it in GitHub Desktop.
knn
import numpy as np
import operator
point = [0,0]
k = 3
listOfPoint=[(1,1),(1,0),(2,1),(0,-1),(2,2)]
def knn(point, k, lists):
#create a dic to store distance for each point
dic={}
for p in lists:
#compute the distance between each point in list and target point
d = dist(point, p)
dic[p]=d
res = []
#sorted the dict by value
sorted_dic = sorted(dic.items(), key=operator.itemgetter(1))
#take the kth small point
for key in sorted_dic:
if len(res) < 3:
res.append(key[0])
return res
#compute distance between two points
def dist(pointA, pointB):
pointA = np.array(pointA)
pointB = np.array(pointB)
return sum((pointA - pointB)**2)**0.5
#call the function
knn(point,k,listOfPoint)
#result
[(0, -1), (1, 0), (1, 1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment