Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class issue
#1
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])

     


    
Reply
#2
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).
Reply
#3
(Mar-31-2020, 10:05 PM)deanhystad Wrote: 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).
Thanks it worked! However, I'm sure I tried it :/ but nevermind . Thanks a lot mate
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue referencing new instance from other class nanok66 3 715 Jul-31-2020, 02:07 AM
Last Post: nanok66
  Issue with def norm in class Vector DimosG 4 742 Mar-26-2020, 05:03 PM
Last Post: DimosG

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020