Mar-31-2020, 09:55 PM
Hi . I'm new to Algorithms with Python. Well, actualy, I'm trying to code one: K nearest Neighbors. My code worked perfectly until I try to automatize it and create a Class. Idk why I doesn't work. Maybe because of the sample but I'm not sure. The function that doesn't work is the method NearestNeighbors (because of the dist() one. Here's my code if you can solve it please:
import numpy as np
import random
def sample():
new = [ [0,]*2 for _ in range(random.randint(10,40))]
for i in range (len(new)):
new[i][0]=random.randint(0,200000)
new[i][1]=random.randint(0,100000)
while new[i][0]<new[i][1]:
new[i][1]=random.randint(0,10000)
return new
class Knn:
def __init__(self):
self.data= sample()
r=len(self.data)
self.k=random.randint(0,r)
self.etude = self.data[self.k]
self.data.remove(self.data[self.k])
def NearestNeighbors(self):
d_voisins=[]
for index, sample in enumerate(self.data):
print(sample)
distance= self.dist(sample)
d_voisins.append((distance, index))
d_voisins = sorted(d_voisins)
indice_voisins=[index for distance,index in d_voisins[:self.k]]
return indice_voisins
def dist(sample,self):
dist=0
X= sample[0]
Y= sample[1]
print(X)
print(Y)
dist+=(self.etude[0]-X)**2+(self.etude[1]-Y)**2
dist= np.sqrt(dist)
return dist
def Echantillon(self):
Indice = self.NearestNeighbors()
print(Indice)
for i in Indice:
print(Indice[i])
