genetic algorithm python


from random import randint
from random import random

def newChar():
    r = randint(63,122)
    if r == 64:
        r = ord(' ')
    if r == 63:
        r = ord('.')
        
    return chr(r)
def mapit(i,m,M, a = 0, b = 1):
    return (b - a)*(i - m)/(M-m)

  
  
  class DNA:
    def __init__(self, num):
        self.num = num
        self.genes = [newChar() for i in range(num)]
        self.fitnes = 0
    
    def getPhrase(self):
        s = ''
        return s.join(self.genes)
    
    def calcFitness(self, target):
        scor = 0
        for idx, gen in enumerate(self.genes):
            if gen == target[idx]:
                scor += 1
        self.score = scor/len(target)
        return scor/len(target)
    
    def Reproduction(self, partner):
        child = DNA(self.num)
        midpoint = randint(0, len(self.genes))
        for i in range(self.num):
            if i < midpoint: 
                child.genes[i] = self.genes[i]
            else:
                child.genes[i] = partner.genes[i]
        return child
    
    def mutate(self, mutRate):
        for i in range(self.num):
            r = random()
            if r < mutRate:
                self.genes[i] = newChar()
            
        
            
        




class Papulation:
    def __init__(self, target, pmax, mutationRate, max_mat_pool = 1e5):
        self.target = target
        self.pmax = pmax
        self.mutationRate = mutationRate
        self.papulation = []
        for i in range(pmax):
            self.papulation.append(DNA(len(target)))
        self.matinPool = []
        self.bestfit = None
        self.max_mat_pool = max_mat_pool
        
    def calcFitness(self):
        for i in self.papulation:
            i.calcFitness(self.target)
    def naturalSelaction(self):
        maxfit = 0
        for i in self.papulation:
            if i.score > maxfit:
                maxfit = i.score
                self.bestfit = i
                
        for i in self.papulation:
            n  = int(mapit(i.score, 0, maxfit)*100)
            for j in range(n):
                self.matinPool.append(i)
                
    def died(self):
        diff = int(len(self.matinPool) - self.max_mat_pool)
        if diff > 0:
            del self.matinPool[0:diff]
                
                
    def newGenration(self):
        for i in range(self.pmax):
            partnarA = self.matinPool[randint(0,len(self.matinPool) -1)]
            partnarB = self.matinPool[randint(0,len(self.matinPool) - 1)]
            child = partnarA.Reproduction(partnarB)
            child.mutate(self.mutationRate)
            self.papulation[i] = child

target = '''Hello world'''

pmax = 1000
mutationRate = 0.01
genrations = 100

k = 0
p = Papulation(target,pmax, mutationRate)

for i in range(genrations):
    p.calcFitness()
    p.naturalSelaction()
    p.newGenration()
    if p.bestfit.getPhrase() == target:
        k+=1
#         print('**gen: ', i, p.bestfit.getPhrase())
    print('gin: ', i,  p.bestfit.getPhrase())
    p.died()

3.71
7
Rena 110 points

                                    def crossover(parents, offspring_size):     offspring = numpy.empty(offspring_size)     # The point at which crossover takes place between two parents. Usually, it is at the center.     crossover_point = numpy.uint8(offspring_size[1]/2)      for k in range(offspring_size[0]):         # Index of the first parent to mate.         parent1_idx = k%parents.shape[0]         # Index of the second parent to mate.         parent2_idx = (k+1)%parents.shape[0]         # The new offspring will have its first half of its genes taken from the first parent.         offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]         # The new offspring will have its second half of its genes taken from the second parent.         offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]     return offspring

3.71 (7 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
genetic algorithm fitness python genetic algorithms in python genetic algorithm library in python genetic algorithm python package python genetic algorithm package genetic algorithm optimization in python genetic algorithmns in python genetic algorithm2 python genetic algorithm optimization python genetic algorithms solution python genetic algorithm simple implementation in python implementing genetic algorithm in python genetic programming python genetic algorithm code in python genetic algorithm tsp python how to code genetic algorithm in python python genetic algorithms genetic search algorithm python genetic algorithm implementation in python genetic algorithm data python optimization genetic algorithm with python genetic algorithm in python genetic algorithm in python code python neural network genetic algorithm genetic algorithm tutorial python python genetic algorithm library genetic algorithm library pytohn genetic algorithm python code simple genetic algorithm code in python what is a genetic python algorithm write simple genetic algorithm in python genetic algorithm with pycaret genetic algortihm code python genetic algorithm example python import genetic algorithm in python Continuous genetic algorithm Python Genetic Algorithms with Python referene write genetic algorithm python classification using a genetic algorithm python genetic algorithm python library how to write genetic algorithm in python genetic algorithm python programiz how to create genetic algorithm in python python genetic algorithm genetic algorithm python
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source