KNN Algorithm

This is an KNN algorithm made using dictionaries and for loops.


#KNN Algorithm by Kanishka Verose import math import operator #Data set: data = [(1, 10, "blue"), (3, 9, "blue"), (4,8, "red"),(6, 0, "blue"), (6, 7, "red"), (5,9, "red"),(3, 2, "blue"), (4, 6, "blue"), (4,2, "red"),(3, 0, "blue"), (4, 7, "blue"), (7,4, "red"),(3, 11, "blue"), (11, 9, "blue"), (4,54, "red"),(1, 14, "blue"), (2, 2, "blue"), (12,8, "red")] #Ask for number of clusters: def coord(x , y): distance = math.sqrt((x[1]-y[1])**2 + (x[0]-y[0])**2) return distance k = int(input("How many nearest neighbors? " )) xcoord = int(input("What is the x coordinate? ")) ycoord = int(input("What is the y coordinate? ")) data_point = (xcoord, ycoord) #Compare each piece of data to the point distances = {} for a in data: distance = coord(data_point, a) distances[a] = distance distances = sorted(distances.items(), key = lambda kv: kv[1]) #print(distances) #Find the nearest Neigbors and give the value nearest_neigbors = distances[0:k] colors = {} for x in nearest_neigbors: color = x[0][2] if color in colors: colors[color] +=1 else: colors[color] = 1 colors = sorted(colors.items(), key = lambda kv: kv[1]) print("The nearest neigbors are ", nearest_neigbors, " and the color is ", colors[-1])
1