Overview
A simple method of computing {% k %} nearest neighbors is to compute a distance between each point and the point in question. The the dataset is sorted by the computed distance. The top {% k %} records are used to infer the result of the algorithm.Example
The following example sorts a dataset by the distance from each point to the given point.
from davinci.python import url
data = url('https://server.com/sample.json');
def metric(p,q):
#return a distance meaure between p and q
return math.sqrt((p['point1'] - q['point1'])*(p['point1'] - q['point1']) + (p['point2'] - q['point2'])*(p['point2'] - q['point2']))
q = data[0]
neighbors = [
{'item':p, 'distance':metric(p,q)}
for p in data
]
sorted = sort(neighbors, key=lambda x:x['distance'])