Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Hi I am somewhat new to python and i'm having a hard time with the output with my genetic algorithm

import random
from pip._vendor.html5lib._ihatexml import digit
def randomGenome(length): #generates a random Genome
    genome = ""
    for i in range(length):
        genome = genome + str(random.randrange(0,2))
    return genome

def makePopulation(size,length): #generates a population
population = []
for i in range(size):
    population.append(randomGenome(length))
return population

def fitness(genome):    # calculates fitness
fitness = 0     
digits =[int(x) for x in str(genome)] #turns genome into single digits
fitness = sum(digits) #adds all of the items in the array
return fitness

a = makePopulation(4,4)
def evaluateFitness(population):            # Evaluates every single genome in the array
avgFit = 0
populationTot= list(item.count('1') for item in population)
ssum = sum(populationTot)

avgFit = ssum/len(population)
bestFit= max(populationTot)

return avgFit,bestFit

def crossover(genome1,genome2): # crosses over in random parts of the genome
parent1 = [int(x) for x in str(genome1)]
parent2 = [int(x) for x in str(genome2)]

firstcrosspoint = random.randint(1,len(parent1)) # takes random positions
secondcrosspoint = firstcrosspoint # takes the rest


child1 = parent1[:firstcrosspoint] + parent2[secondcrosspoint:] 

child2 = parent2[:firstcrosspoint] + parent1[secondcrosspoint:]

newChild = ''.join([str(x) for x in child1])
newChildO = ''.join([str(x) for x in child2])

newpopChild = []
newpopChild.append(newChild)
newpopChild.append(newChildO)

return newpopChild

def mutate(genome,mutationRate):                #mutation of a random bit


mutGenome = [int(x) for x in str(genome)]

mutate = random.randint(0,len(mutGenome))

if random.random() <= mutationRate:          #still iffy on this one, but it works
    mutGenome[mutate] = mutGenome[mutate]^1
    return mutGenome

popop= makePopulation(5, 5)

def selectPair(population):                     #takes in a population, randomly selects 2 genomes, this is the roulette wheel

 randomGenome1= random.choice(population)
randomGenome2= random.choice(population)


genomeA = randomGenome1
genomeB = randomGenome2
"""
genomeA = [int(x) for x in str(randomGenome1)]
genomeB = [int(x) for x in str(randomGenome2)]
"""
twogenomes = []
twogenomes.append(genomeA)
twogenomes.append(genomeB)


return twogenomes
def runGA(populationSize,crossoverRate,mutationRate,size,length):
newGeneration = []
genome = ""
createPop = makePopulation(size, length)

for i in range(21):

    if random.random() <= crossoverRate:   

        nPop = selectPair(createPop)
        newgenG = crossover(nPop[0],nPop[1])

        createPop.remove(nPop[0])
        createPop.remove(nPop[1])

        createPop.append(newgenG[0])
        createPop.append(newgenG[1])

    elif random.random() <= mutationRate:
        randomGenome =random.choice(createPop)

        mutatedGenome=mutate(randomGenome,mutationRate)

        createPop.remove(randomGenome)
        createPop.append(randomGenome)



    avgandBest=evaluateFitness(createPop)
    avgFit = avgandBest[0]
    bestFit = avgandBest[1]

    if bestFit == 20:
        break

    print("generation:",i,"average fitness:", avgFit,"best fitness:",bestFit)
runGA(100,0.7,0.001,100,20)

The output for the code was this:

generation: 0 average fitness: 10.23 best fitness: 16
generation: 1 average fitness: 10.23 best fitness: 16
generation: 2 average fitness: 10.23 best fitness: 16
generation: 3 average fitness: 10.23 best fitness: 16
generation: 4 average fitness: 10.23 best fitness: 16
generation: 5 average fitness: 10.23 best fitness: 16
generation: 6 average fitness: 10.23 best fitness: 16
generation: 7 average fitness: 10.23 best fitness: 16
generation: 8 average fitness: 10.23 best fitness: 16
generation: 9 average fitness: 10.23 best fitness: 16
generation: 10 average fitness: 10.23 best fitness: 16
generation: 11 average fitness: 10.23 best fitness: 16
generation: 12 average fitness: 10.23 best fitness: 16
generation: 13 average fitness: 10.23 best fitness: 16
generation: 14 average fitness: 10.23 best fitness: 16
generation: 15 average fitness: 10.23 best fitness: 16
generation: 16 average fitness: 10.23 best fitness: 16
generation: 17 average fitness: 10.23 best fitness: 16
generation: 18 average fitness: 10.23 best fitness: 16
generation: 19 average fitness: 10.23 best fitness: 16
generation: 20 average fitness: 10.23 best fitness: 16

For the correct output I need this:

>>> runGA(100, 0.7, 0.001, "run1.txt")
Population size: 100
Genome length: 20
Generation    0: average fitness 10.07, best fitness 15.00
Generation    1: average fitness 10.91, best fitness 15.00
Generation    2: average fitness 11.45, best fitness 16.00
Generation    3: average fitness 12.02, best fitness 16.00
...
Generation   18: average fitness 16.09, best fitness 19.00
Generation   19: average fitness 16.38, best fitness 20.00
19
>>>

I am not sure if the problem is with the code itself, the final function, or just the data for imputing the numbers. These are the what each of the functions are supposed to do:

  • randomGenome(length) returns a random genome (bit string) of a given length.
  • makePopulation(size, length) returns a new randomly created population of the specified size, represented as a list of genomes of the specified length.
  • fitness(genome) returns the fitness value of a genome.
  • evaluateFitness(population) returns a pair of values: the average fitness of the population as a whole and the fitness of the best individual in the population.
  • crossover(genome1, genome2) returns two new genomes produced by crossing over the given genomes at a random crossover point.
  • mutate(genome, mutationRate) returns a new mutated version of the given genome.
  • selectPair(population) selects and returns two genomes from the given population using fitness-proportionate selection. This function should use weightedChoice, which was provided, as a helper function.
  • runGA(populationSize, crossoverRate, mutationRate) is the main GA program, which takes the population size, crossover rate (pc), and mutation rate

So again I your assistance will be greatly appreciated.

Comments