Neuron 101

Nature-inspired optimization / Genetic algorithm

Türkçe

Plate58

Unit 6 · Topic 4 of 11

Genetic algorithm

Medium, 10 min, 10 steps

highest fitnessbest fitness
Keyboard: left and right arrows change the step, space plays and pauses.

Step 1 of 10 Population

A random population

Instead of a single ball there is a population of 8 individuals; each dot is a candidate solution. They were generated at random and spread over different parts of the landscape. The fitness of the best one is 0.69.

Open in Colab
  1. import random
  2. # f: optimizasyon arazisi konusundaki
  3. random.seed(5)
  4. def uygun(k):
  5. return f(int(k, 2) / 255 * 10)
  6. def turnuva(nufus):
  7. a, b = random.choices(nufus, k=2)
  8. return max(a, b, key=uygun)
  9. def mutasyon(k, oran):
  10. return ''.join(
  11. '10'[int(b)] if
  12. random.random() < oran
  13. else b for b in k)
  14. nufus = [''.join(random.choice('01')
  15. for _ in range(8))
  16. for _ in range(8)]
  17. for nesil in range(8):
  18. yeni = [max(nufus, key=uygun)]
  19. while len(yeni) < 8:
  20. a = turnuva(nufus)
  21. b = turnuva(nufus)
  22. kes = random.randint(1, 7)
  23. c = a[:kes] + b[kes:]
  24. yeni.append(
  25. mutasyon(c, 0.05))
  26. nufus = yeni
  27. en_iyi = max(nufus, key=uygun)
  28. print(en_iyi, uygun(en_iyi))
nesil
0
enIyiTam
184
enIyiX
7.22
enIyiF
0.69
oran
0.05
nufus
8