Vityou
Vityou

Reputation: 135

python - genetic algorithm not working

I made a genetic algorithm with a goal to get an "organism's" y position above 20. The problem is in the part under the class:

import random as r

class Organism(object):
    def __init__(self, genes,ID):
        self.genes = genes
        self.position = [0,0]
        self.thisTime=str()
        self.geneTranslation = []
        self.ID=ID

    def move(self,d):
        if d == "f" or d == "forward":
            self.position[1] += 1
        elif d == "b" or d == "back":
            self.position[1] -= 1
        elif d == "r" or d == "right":
            self.position[0] += 1
        elif d == "l" or d == "left":
            self.position[0] -= 1

        print(self.position)


    def isInContactWith(self,point):
        point = list(point)
        if self.position == point:
            return True
        else:
            return False


    def run(self):
        for i in range(0,4):
            if i == 0:
                self.geneTranslation.extend(["f"] * self.genes[0])
            elif i == 1:
                self.geneTranslation.extend(["b"] * self.genes[1])
            elif i == 2:
                self.geneTranslation.extend(["r"] * self.genes[2])
            elif i == 3:
                self.geneTranslation.extend(["l"] * self.genes[3])
        r.shuffle(self.geneTranslation)
        for x in range(1,20):
            try:
                self.thisTime = r.choice(self.geneTranslation)
                self.move(self.thisTime)
            except:
                pass


population = []
yValues={}

running = True
BestOrganism=Organism([25,25,25,25],0)
for count in range(50):
    for x in range(100):
        a = lambda: r.randint(-3, 3)

        b = BestOrganism.genes[:]
        anOrganism = Organism(b[:],x)
        for count in range(len(anOrganism.genes[:])):
            anOrganism.genes[count] += int(a())
        population.append(anOrganism)

    for j in range(len(population)):
        print("Organism " + str(population[j].ID) + str(population[j].genes))
        population[j].run()
        yValues[population[j].ID]=population[j].position[1]
        if population[j].position[1]>=20:
            print(population[j].genes)
            running = False
            break

    BestOrganism=max(yValues)

    for k in range(len(population[:])):
        if population[k].ID==BestOrganism:
            BestOrganism=population[k]
    print(yValues[max(yValues)])
    print(BestOrganism.genes[:])
    population=[]
    yValues={}

As you can see, the genes determine the probability for the organism to go in a certain direction. The genes that produce lower y values are weeded out, and the new generation is made from the BestOrganism mutated a little. It seems that this should produce more organisms which have genes with a higher percent chance of going forward, but it doesn't. Is there any other factor which I'm not taking into account?

Upvotes: 0

Views: 223

Answers (1)

mgiuffrida
mgiuffrida

Reputation: 3579

The main issue is just that you are misusing max: you're finding the organism with the largest key (ID) instead of the largest Y value. Try max(yValues, key=yValues.get).

You could also try increasing the number of move steps from 20 to something much larger.

Finally, cleaning up the code a bit will help make things clearer.

Upvotes: 2

Related Questions