Python Genetic Algorithms With Artificial Intelligence

Python Genetic Algorithms With Artificial IntelligenceRinu GourBlockedUnblockFollowFollowingFeb 28Python Genetic Algorithms With AIWhat are Genetic Algorithms With Python?A Genetic Algorithm (GA) is a metaheuristic inspired by natural selection and is a part of the class of Evolutionary Algorithms (EA).

We use these to generate high-quality solutions to optimization and search problems, for which, these use bio-inspired operators like mutation, crossover, and selection.

In other words, using these, we hope to achieve optimal or near-optimal solutions to difficult problems.

Such algorithms simulate natural selection.

Have a look at Python Machine Learning AlgorithmsFor any problem, we have a pool of possible solutions.

These undergo processes like recombination and mutation to bear new children over generations.

The search space is the set of all possible solutions and values the inputs may take.

In optimization, we try to find within this search space the point or set of points that gives us the optimal solution.

Each individual is like a string of characters/integers/floats and the stringsare like chromosomes.

What are Genetic Algorithms With PythonThe fitness value (from a fitness function) for a candidate tells us how close it is to the optimal solution.

This is on the lines of Darwin’s theory of ‘Survival of the Fittest’ and is how we keep producing better (evolving) individuals/ solutions over generations before reaching a criterion where to stop.

These algorithms work in four steps:Individuals in population compete for resources, mateFittest individuals mate to create more offsprings than othersFittest parent propagates genes through generation; parents may produce offsprings better than either parentEach successive generation evolves to suit its ambienceSince the population size is constant, some individuals must die to make room for newer ones.

We arrive at a situation of convergence when the difference between offsprings produced by the current and ancestral populations is no longer significant.

Then, the algorithm converges to a set of solutions for the problem.

Do you know about Python NLTKOperators of Python Genetic AlgorithmsTo evolve through the generations, an algorithm may make use of one of many operators.

Some of those are:Operators in Python Genetic Algorithmsa.

Selection OperatorIt prefers individuals with better fitness scores and lets them pass genes on to successive generations.


Crossover OperatorThis lets individuals mate.

We apply the selection operator to select two individuals, and randomly choose crossover sites.

We then exchange the genes at these sites- this produces an entirely new individual.

Crossover Operator in Python Genetic AlgorithmsYou must know about Python Ternary Operatorsc.

Mutation OperatorIn mutation, we insert random genes in offsprings to maintain diversity and avoid premature convergence.

Mutation Operator in Python Genetic AlgorithmsPython Genetic Algorithm ExampleLet’s try to build a Genetic Algorithm in Python that can play something like Guess the Number better than us humans.

This is a game where I randomly select a number between 1 and 10 (both inclusive) and you guess what number I have picked.

Is it 7?.NoIs it 3?.NoIs it 6?.NoIs is 2?.YesSeems like no big deal, but when we start talking about 100 or 1000 numbers, it quickly becomes a problem.

How do we improve our guesses?.What can we do but depend on sheer luck?.This ultimately turns into a mechanical process.

Maybe we could decide if a certain guess is closer to the solution in a certain direction?Is it 7?.LowerIs it 1?.HigherIs it 5?.LowerIs it 4?.LowerIs it 3?.YesPossession of such domain knowledge means we can get to the solution faster.

To make informed and improved guesses, the algorithms make use of random exploration of the problem space.

Along with that, they also use evolutionary processes like mutation and crossover (see above).

Without experience in the problem domain, they also try out things humans never would dare attempt.

Have a look at Python AI Heuristic SearchOkay, now let’s try implementing this in Python.

Bear in mind that the fitness value for a candidate is how close it is to the optimal.

Here, it means how many letters match what it should be- “Hello World!”.

Let’s start with building a gene set.

>>> geneSet=”abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.

”>>> target=”Hello World!”Now, let’s generate a guess.

>>> import random>>> def gen_parent(length):genes=[]while len(genes)<length:sampleSize=min(length-len(genes),len(geneSet))genes.


sample(geneSet,sampleSize))return ‘’.

join(genes)Here, random.

sample() chooses sampleSize random elements from geneSet.

Now, let’s do something to calculate the fitness value.

>>> def get_fitness(guess):return sum(1 for expected,actual in zip(target,guess) if expected==actual)With zip(), we can iterate over two lists at once.

Now, let’s perform mutation.

>>> def mutate(parent):index=random.


sample(geneSet,2)childGenes[index]=alternate if newGene==childGenes[index] else newGenereturn ‘’.

join(childGenes)This is to convert the parent into an array with list(parent).

Then, we replace 1 letter with one that we randomly select from geneSet.

Finally, we recombine the result into a string with .


To avoid wasted guesses, this uses an alternate replacement if the randomly selected newGene is equal to that we expect it to replace.

The next functionlets us display what is happening.

>>> def display(guess):timeDiff=datetime.


now()-startTimefitness=get_fitness(guess)print(“{} {} {}”.

format(guess,fitness,timeDiff))We’re all set.

Let’s begin with the main program now.

>>> random.

seed()>>> startTime=datetime.


now()>>> bestParent=gen_parent(len(target))>>> bestFitness=get_fitness(bestParent)>>> display(bestParent)umaBL.

WdlUYj 1 0:00:51.

469944And now, a loop to generate a guess, request its fitness, compare that to that of the previous best guess, and keep the guess with the better fitness.

>>> while True:child=mutate(bestParent)childFitness=get_fitness(child)if bestFitness>=childFitness:continuedisplay(child)if childFitness>=len(bestParent):breakbestFitness=childFitnessbestParent=childumaBL.

WolUYj 2 0:00:55.


WollYj 3 0:00:56.


WollY!. More details

Leave a Reply