What is a genetic algorithm?
Overview
Genetic algorithm (GA) is the name given to the new (rather exotic) class of optimization techniques which were discovered by John Holland in the late 70s.
GAs are similar to conventional evolutionary algorithms. GAs are not concerned with how to solve particular problems, but rather the speed of problem-solving. One of the major contributions of genetic algorithms is the “evolutionary optimization” of problems.
Note: GA is a class of search algorithms that uses a probabilistic approach to find a solution to a problem.
When it comes to the structure of the algorithm, it is divided into the following five phases: initial population, fitness function, selection, crossover, and mutation.
Let’s try out a very basic example where the initial population is random characters. The algorithm will regenerate the required solution.
Note: Enter your name as an example.
geneSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!,. ?"import randomimport datetimedef Calculate_Fitness(guess):return sum(1 for expected,actual in zip(target,guess) if expected==actual)def Cross_Over(length):genes=[]while len(genes)<length:sampleSize=min(length-len(genes),len(geneSet))genes.extend(random.sample(geneSet,sampleSize))return "".join(genes)def Mutation(parent):index=random.randrange(0,len(parent))childGenes=list(parent)newGene,alternate=random.sample(geneSet,2)childGenes[index]=alternate if newGene==childGenes[index] else newGenereturn "".join(childGenes)def Display(guess, startTime):timeDiff=datetime.datetime.now()-startTimefitness=Calculate_Fitness(guess)print("{}\t{}\t{}".format(guess,fitness,timeDiff))def run_genetic_algo(target):random.seed()startTime=datetime.datetime.now()bestParent=Cross_Over(len(target))bestFitness=Calculate_Fitness(bestParent)Display(bestParent, startTime)while True:child=Mutation(bestParent)childFitness=Calculate_Fitness(child)if bestFitness>=childFitness:continueDisplay(child, startTime)if childFitness>=len(bestParent):breakexit(0)bestFitness=childFitnessbestParent=childtarget = input()run_genetic_algo(target)
Enter the input below
Code explanation
-
Lines 4–5: We are iterating over both the given target and the population in
Calculate_Fitnessfunction. We’ll return1when the expected and actual values are equal to one another. -
Lines 7–12: We are taking a genes list and continue iterating, in the
Cross_Overfunction, until the length of thegenesarray is greater than the given parameter length. Inside the loop, we first calculate thesampleSizeand then extract asampleSizerandom sample from thegeneSetand add that to thegenesarray. -
Lines 14–19: We are creating the
Mutationfunction, where we first use therandrangefunction to calculate a randomindex. Next, we extract two random samples from thegeneSetand store them in the variablesnewGeneandalternate. After this, we check and see if thenewGeneis equal to the value of thechildGenespresent at the specificindex. If it is, we store the value ofalternateinsidechildGenesat that specificindex. Otherwise, we storenewGene. -
Lines 21–24: We use the
Displayfunction for showing the value of the chromosome along with itsfitness. -
Lines 26–42: We are creating the
run_genetic_algofunction, which takes atarget, which will be your name in this case. After this, we set aseedso that we generate the same random fitness values. -
Line 29: We are calling the
Cross_Overfunction, which generates a new offspring. -
Line 30: We are calling the
Calculate_Fitnessfunction defined above to calculate thebestFitnessvalue. We display the value of the chromosome along with its fitness. -
We call the
Mutationfunction to get a population of genetic diversified chromosomes, inside thewhileloop. Next, we call theCalculate_Fitnessfunction, this time on the mutated chromosome. We then compare the fitness values of the old chromosome and the mutated chromosome. We also have set up a condition, which checks if the fitness of the mutated chromosome is greater than the length of our old chromosome. If this happens, we simply exit the loop and stop the process. -
Lines 41–42: We are replacing the chromosome with the mutated chromosome along with its fitness value, if neither of our terminating conditions is met.
-
This entire process continues until either of the terminating conditions is met.
Free Resources