Jump to content
Turry

Python Genetic Algorithm

Recommended Posts

  • Active Members
Posted

Cateva sugestii, majoritatea PEP8 related:

 

- constantele ar trebui sa fie UPPERCASEd: (e.g: targetRadius ar trebui redenumit ca TARGET_RADIUS)

- ar trebui sa lasi doua linii noi intre functiile din afara unei clase sau intre functii si clase

 

 Asta:

..
particleColor = sf.Color(255, 255, 255, 50)

def distance(x1, y1, x2, y2):
    """
    Calculate the distance from 2 points. (X1, Y1) and (X2, Y2)
    Formula: (  (X1-X2)**2 + (Y1-Y2)**2  )**1/2
    """
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)

class DNA():
    ...

Ar trebui sa arate asa:

 

..
particleColor = sf.Color(255, 255, 255, 50)


def distance(x1, y1, x2, y2):
    """
    Calculate the distance from 2 points. (X1, Y1) and (X2, Y2)
    Formula: (  (X1-X2)**2 + (Y1-Y2)**2  )**1/2.
    """
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)


class DNA():
    ...

 

- denumirea variabilelor tre' sa fie snake_cased (la fel si numele metodelor): e.g: def applyForce -> def apply_force etc

- cand iterezi printr-o lista, si ai nevoie si de index si de valoare, e recomandat sa faci asa:

lista_mea = ['malai', 'faina', 'pui', 'clatite']

for i, value in enumerate(lista_mea):
    print(i, value)

"""
output:

(0, 'malai')
(1, 'faina')
(2, 'pui')
(3, 'clatite')
"""

- cand creezi o clasa care nu are nici-un argument poti renunta la paranteze: class DNA() -> class DNA:

- urmatoarea functie:

 

def crossover(self, partner):
        """
        Take the genes from 2 parents and create 1 offspring
        """

        newDNA = []
        # Pick one random point from the genes
        randomPoint = random.randint(0, len(self.genes))
        for x in range(len(self.genes)):
            if x < randomPoint:
                newDNA.append(self.genes[x])
            else:
                newDNA.append(partner.genes[x])
        return DNA(newDNA)

Poate fi rescrisa cu recomandarea de mai sus si folosind list comprehensions astfel:

def crossover(self, partner):
        """
        Take the genes from 2 parents and create 1 offspring.
        """
        random_point = random.randint(0, len(self.genes))
        new_dna = [
            value if i < random_point else partner.genes[i]               
            for i, value in enumerate(self.genes)
        ]

        return DNA(new_dna)

 

Probabil ca se pot face mai multe schimbari insa nu am timp sa ma uit peste tot codu'. Felicitari oricum pentru efort si keep it goin' :) 

  • Upvote 5
Posted (edited)

Faina idee de algoritm!

Nu pare cam "eficient" in practica pt ca necesita o populatie fmare pt convergenta. 

In general, in practica costul generatii*indivizi se vrea mic.

(si toate celelalte dezavantave genetice: random walk, local optimum etc.)

 

E frumos programul ca exemplu de solutie pur genetica.

Felicitari.

Edited by yoyois
  • Upvote 1
Posted
4 hours ago, MrGrj said:

Cateva sugestii, majoritatea PEP8 related:

 

- constantele ar trebui sa fie UPPERCASEd: (e.g: targetRadius ar trebui redenumit ca TARGET_RADIUS)

- ar trebui sa lasi doua linii noi intre functiile din afara unei clase sau intre functii si clase

 

 Asta:


..
particleColor = sf.Color(255, 255, 255, 50)

def distance(x1, y1, x2, y2):
    """
    Calculate the distance from 2 points. (X1, Y1) and (X2, Y2)
    Formula: (  (X1-X2)**2 + (Y1-Y2)**2  )**1/2
    """
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)

class DNA():
    ...

Ar trebui sa arate asa:

 


..
particleColor = sf.Color(255, 255, 255, 50)


def distance(x1, y1, x2, y2):
    """
    Calculate the distance from 2 points. (X1, Y1) and (X2, Y2)
    Formula: (  (X1-X2)**2 + (Y1-Y2)**2  )**1/2.
    """
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)


class DNA():
    ...

 

- denumirea variabilelor tre' sa fie snake_cased (la fel si numele metodelor): e.g: def applyForce -> def apply_force etc

- cand iterezi printr-o lista, si ai nevoie si de index si de valoare, e recomandat sa faci asa:


lista_mea = ['malai', 'faina', 'pui', 'clatite']

for i, value in enumerate(lista_mea):
    print(i, value)

"""
output:

(0, 'malai')
(1, 'faina')
(2, 'pui')
(3, 'clatite')
"""

- cand creezi o clasa care nu are nici-un argument poti renunta la paranteze: class DNA() -> class DNA:

- urmatoarea functie:

 


def crossover(self, partner):
        """
        Take the genes from 2 parents and create 1 offspring
        """

        newDNA = []
        # Pick one random point from the genes
        randomPoint = random.randint(0, len(self.genes))
        for x in range(len(self.genes)):
            if x < randomPoint:
                newDNA.append(self.genes[x])
            else:
                newDNA.append(partner.genes[x])
        return DNA(newDNA)

Poate fi rescrisa cu recomandarea de mai sus si folosind list comprehensions astfel:


def crossover(self, partner):
        """
        Take the genes from 2 parents and create 1 offspring.
        """
        random_point = random.randint(0, len(self.genes))
        new_dna = [
            value if i < random_point else partner.genes[i]               
            for i, value in enumerate(self.genes)
        ]

        return DNA(new_dna)

 

Probabil ca se pot face mai multe schimbari insa nu am timp sa ma uit peste tot codu'. Felicitari oricum pentru efort si keep it goin' :) 

Multumesc mult pentru sfaturi. Am sa corectez greselile si am sa incerc sa respect PEP8.

2 hours ago, yoyois said:

Faina idee de algoritm!

Nu pare cam "eficient" in practica pt ca necesita o populatie fmare pt convergenta. 

In general, in practica costul generatii*indivizi se vrea mic.

(si toate celelalte dezavantave genetice: random walk, local optimum etc.)

 

E frumos programul ca exemplu de solutie pur genetica.

Felicitari.

Stiu ca nu este cel mai eficient dar mi se pare extrem de interesanta ideea de a nu programa explicit cum trebuie sa rezolve problema iar calculatorul sa "descopere" o solutie cat de cat optima.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...