Created
November 2, 2017 18:02
-
-
Save kogecoo/6227d73dcf171da1227dacd86cc9f26c to your computer and use it in GitHub Desktop.
Experimental implementation of simple Particle Swarm Optimization algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from numpy.random import rand, uniform | |
# reference: https://en.wikipedia.org/wiki/Particle_swarm_optimization#Parameter_selection | |
ob = lambda x: (np.power(x, 4.0) - x * x * 16 + x * 5).sum() / 2.0 # Styblinski-Tang function | |
lims = np.array([[-5.0, 4.0], [-3.0, 4.0]]) | |
loop = 100 | |
nps, ndim = 10, lims.shape[0] | |
h1, h2, h3 = 0.9, 0.9, 0.9 | |
gx = ob(rand(1, ndim)) | |
lxs = X = rand(nps, ndim) | |
vs = np.array([[uniform(-abs(u - l), abs(u - l)) for l, u in lims] for i in range(nps)]) | |
for c in range(loop): | |
for i in range(nps): | |
x, v = X[i, :], vs[i, :] | |
vs[i, :] = v = v * h1 + h2 * rand(ndim) * (lxs[i] - x) + h3 * rand(ndim) * (gx - x) | |
X[i, :] = x = x + v | |
if ob(x) < ob(lxs[i]): | |
lxs[i] = x | |
if ob(x) < ob(gx): | |
gx = x | |
print(c, ob(gx)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment