Implementation of the KNN Algorithm

This code uses the concept of K Nearest Neighbors to classify a given point "C" as either red or blue based on its surrounding icons.


""" By: Kush Arora (4/30/19) """ #imports from math import sqrt #prior generated information data= [(1,5,"red"), (10,10,"blue"), (15, 3,"red"), (23,9, "blue"), (21, 2, "red"), (18, 34, "blue"), (3, 24, "red"), (14, 41, "blue"), (13, 10,"red"), (4,20,"blue"), (13, 10,"red"), (9, 11,"blue"), (13, 3,"red")] #defining variables listA=[] count_red=0 count_blue=0 def distance(x1, x2, y1, y2): return sqrt ((x2-x1)**2+(y2-y1)**2) def knn(x,y, k=0): return distance_two(x,y) def distance_two(x,y): a=[] d= data return d_recur(x,y,a,d) def d_recur(x,y,a,d): if len(d) == 0: return a else: current=d[0] dist= distance(current[0], x, current[1], y) current = current + (dist,) a.append(current) d.pop(0) return d_recur(x, y, a, d) x=knn(1,2,k=3) for i in range(0,3): #extracting the red/blue from the list z=x[i] yy=z[2] #checks to see what color chips r within the cirlce radius if yy=="red": count_red += 1 if yy=="blue": count_blue += 1 if count_red > count_blue: print("classified as red") if count_blue > count_red: print("classified as red")
1