Este team especializado pasados algunos días de investigación y de juntar de información, han obtenido los datos necesarios, nuestro deseo es que te sea de gran utilidad en tu plan.
Ejemplo: algoritmo genético python
from random import randint
from random import random
defnewChar():
r = randint(63,122)if r ==64:
r =ord(' ')if r ==63:
r =ord('.')returnchr(r)defmapit(i,m,M, a =0, b =1):return(b - a)*(i - m)/(M-m)classDNA:def__init__(self, num):
self.num = num
self.genes =[newChar()for i inrange(num)]
self.fitnes =0defgetPhrase(self):
s =''return s.join(self.genes)defcalcFitness(self, target):
scor =0for idx, gen inenumerate(self.genes):if gen == target[idx]:
scor +=1
self.score = scor/len(target)return scor/len(target)defReproduction(self, partner):
child = DNA(self.num)
midpoint = randint(0,len(self.genes))for i inrange(self.num):if i < midpoint:
child.genes[i]= self.genes[i]else:
child.genes[i]= partner.genes[i]return child
defmutate(self, mutRate):for i inrange(self.num):
r = random()if r < mutRate:
self.genes[i]= newChar()classPapulation:def__init__(self, target, pmax, mutationRate, max_mat_pool =1e5):
self.target = target
self.pmax = pmax
self.mutationRate = mutationRate
self.papulation =[]for i inrange(pmax):
self.papulation.append(DNA(len(target)))
self.matinPool =[]
self.bestfit =None
self.max_mat_pool = max_mat_pool
defcalcFitness(self):for i in self.papulation:
i.calcFitness(self.target)defnaturalSelaction(self):
maxfit =0for 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 inrange(n):
self.matinPool.append(i)defdied(self):
diff =int(len(self.matinPool)- self.max_mat_pool)if diff >0:del self.matinPool[0:diff]defnewGenration(self):for i inrange(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 inrange(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()
Tienes la posibilidad recomendar esta crónica si lograste el éxito.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)