Neuron 101

Nature-inspired optimization / Particle swarm optimization

Türkçe

Plate62

Unit 6 · Topic 8 of 11

Particle swarm optimization

Medium, 9 min, 9 steps

Height01Swarm best
Keyboard: left and right arrows change the step, space plays and pauses.

Step 1 of 9 Swarm

Particles spread over the surface

The map shows a surface from above: darker tones are higher. 12 particles were spread over the surface at random, each with a random velocity. The triangle marks the highest point. The particles do not know where it is; they can only measure the height where they stand.

Open in Colab
  1. import random
  2. # f(p): p noktasının yüksekliği
  3. # k(v): v'yi −5 ile 5 arasına çeker
  4. random.seed(4)
  5. w, c1, c2 = 0.7, 1.5, 1.5
  6. X = [[random.uniform(-5, 5)
  7. for _ in range(2)]
  8. for _ in range(12)]
  9. V = [[random.uniform(-1, 1)
  10. for _ in range(2)]
  11. for _ in range(12)]
  12. P = [x[:] for x in X]
  13. g = max(P, key=f)
  14. def adim(x, v, p):
  15. for d in range(2):
  16. r1 = random.random()
  17. r2 = random.random()
  18. v[d] = (w * v[d]
  19. + c1 * r1 * (p[d] - x[d])
  20. + c2 * r2 * (g[d] - x[d]))
  21. v[d] = max(-2, min(2, v[d]))
  22. x[d] = k(x[d] + v[d])
  23. for tur in range(40):
  24. for x, v, p in zip(X, V, P):
  25. adim(x, v, p)
  26. for i, x in enumerate(X):
  27. if f(x) > f(P[i]):
  28. P[i] = x[:]
  29. g = max(P + [g], key=f)
  30. print(g, f(g))
tur
0
enIyiDeger
0.60