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


Messages In This Thread
Class issue - by Reldaing - Mar-31-2020, 09:55 PM
RE: Class issue - by deanhystad - Mar-31-2020, 10:05 PM
RE: Class issue - by Reldaing - Mar-31-2020, 10:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Child class inheritance issue eakanathan 3 1,329 Apr-21-2022, 12:03 PM
Last Post: deanhystad
  Issue referencing new instance from other class nanok66 3 2,214 Jul-31-2020, 02:07 AM
Last Post: nanok66
  Issue with def norm in class Vector DimosG 4 2,478 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