Last active
August 2, 2016 12:30
-
-
Save mintisan/8a7a9f1a82305640c152 to your computer and use it in GitHub Desktop.
A Simple Heuristic Optimization in Python
This file contains hidden or 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 | |
import random | |
def sphere(x): | |
tmp = 0 | |
for i,d in enumerate(x): | |
tmp += (d - 0.1*i)*(d - 0.1*i); | |
return tmp | |
class swarm(object): | |
p = [] | |
r = [] | |
"""docstring for swarm""" | |
def __init__(self, num, dim, lb, ub): | |
super(swarm, self).__init__() | |
self.num = num | |
self.dim = dim | |
self.lb = lb | |
self.ub = ub | |
self.p = np.random.uniform(self.lb,self.ub,(self.num,self.dim)) | |
for row in range(0,self.p.shape[0]): | |
self.r.append(sphere(self.p[row])) | |
def update(self): | |
# 2.1 select random particles | |
r0, r1 = random.sample(range(0,self.num),2) | |
rj = random.sample(range(0,self.dim),2) # random dimension | |
# 2.2 generate new_sol particle from sol via slice | |
new_sol = np.copy(self.p[r0]) | |
new_sol[rj] = self.p[r0][rj] + np.random.uniform(-1, 1)*(self.p[r0][rj] - self.p[r1][rj]) | |
#new_sol[rj] = self.p[self.r.index(min(self.r))][rj] + np.random.uniform(-1, 1)*(self.p[r0][rj] - self.p[r1][rj]) | |
# 2.3 greedy select | |
if sphere(new_sol) < sphere(self.p[r0]): | |
self.p[r0][rj] = new_sol[rj] | |
self.r[r0] = sphere(new_sol) | |
def gbest(self): | |
return min(self.r) | |
def show(self): | |
print('sphere',self.p[self.r.index(min(self.r))],' =', min(self.r)) | |
def main(): | |
s = swarm(5,5,-100,100) | |
for x in range(0,6000): | |
s.update() | |
s.show() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment