Class issue - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Class issue (/thread-25480.html) |
Class issue - Reldaing - Mar-31-2020 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]) RE: Class issue - deanhystad - Mar-31-2020 def dist(self, sample) instead of def dist(sample, self) When you call self.func(a, b, c) the actual function call is func(self, a, b, c). RE: Class issue - Reldaing - Mar-31-2020 (Mar-31-2020, 10:05 PM)deanhystad Wrote: def dist(self, sample) instead of def dist(sample, self)Thanks it worked! However, I'm sure I tried it :/ but nevermind . Thanks a lot mate |