
KNN color sorting
This code used the K Nearest Neighbors to classify a given C point as red or blue.
from math import sqrt
#defining varibles
data=[(1,2,'red'),(2,3,'blue'),(3,4,'red'),(4,5,'blue'),(5,6,'red'),(6,7,'blue'),(7,8,'red'),(8,9,'blue'),(9,10,'red'),(10,11,'blue'),(11,12,'red'),(12,13,'blue'),(13,14,'red'),(14,15,'blue')]
xx=int(input("x cordinate of c: "))
yy=int(input("y cordinate of c: "))
kkk=int(input("value of k: "))
kk=(input("What do you want k written as k=_: "))
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(x,current[0],current[1],y)
current=current+(dist,)
a.append(current)
d.pop(0)
return(d_recur(x,y,a,d))
#calling the functions
x=(Knn(xx,yy,kk))
#catogrizing by distance to c, and finding color
listA=[]
count_red=0
count_blue=0
for i in range(0,kkk):
z=x[i]
yy=z[2]
if yy=='red':
count_red+=1
if yy == 'blue':
count_blue+=1
#Finding what color it is clasified with
if count_red > count_blue:
print('It is classified as red')
if count_blue > count_red:
print('It is classified as blue')