码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现的粒子群优化算法

时间:2016-05-30 01:09:32      阅读:585      评论:0      收藏:0      [点我收藏+]

标签:

01.from numpy import array 
02.from random import random 
03.from math import sin, sqrt 
04.  
05.iter_max = 10000
06.pop_size = 100
07.dimensions = 2
08.c1 = 2
09.c2 = 2
10.err_crit = 0.00001
11.  
12.class Particle: 
13.    pass
14.  
15.def f6(param): 
16.    ‘‘‘Schaffer‘s F6 function‘‘‘
17.    para = param*10
18.    para = param[0:2] 
19.    num = (sin(sqrt((para[0] * para[0]) + (para[1] * para[1])))) * \ 
20.        (sin(sqrt((para[0] * para[0]) + (para[1] * para[1])))) - 0.5
21.    denom = (1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1]))) * \ 
22.            (1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1]))) 
23.    f6 =  0.5 - (num/denom) 
24.    errorf6 = 1 - f6 
25.    return f6, errorf6; 
26.  
27.#initialize the particles 
28.particles = [] 
29.for i in range(pop_size): 
30.    p = Particle() 
31.    p.params = array([random() for i in range(dimensions)]) 
32.    p.fitness = 0.0
33.    p.v = 0.0
34.    particles.append(p) 
35.  
36.# let the first particle be the global best 
37.gbest = particles[0] 
38.err = 999999999
39.while i < iter_max : 
40.    for p in particles: 
41.        fitness,err = f6(p.params) 
42.        if fitness > p.fitness: 
43.            p.fitness = fitness 
44.            p.best = p.params 
45.  
46.        if fitness > gbest.fitness: 
47.            gbest = p 
48.        v = p.v + c1 * random() * (p.best - p.params) \ 
49.                + c2 * random() * (gbest.params - p.params) 
50.        p.params = p.params + v 
51.  
52.    i  += 1
53.    if err < err_crit: 
54.        break
55.    #progress bar. ‘.‘ = 10% 
56.    if i % (iter_max/10) == 0: 
57.        print .
58.  
59.print \nParticle Swarm Optimisation\n
60.print PARAMETERS\n,-*9
61.print Population size : , pop_size 
62.print Dimensions      : , dimensions 
63.print Error Criterion : , err_crit 
64.print c1              : , c1 
65.print c2              : , c2 
66.print function        :  f6
67.  
68.print RESULTS\n, -*7
69.print gbest fitness   : , gbest.fitness 
70.print gbest params    : , gbest.params 
71.print iterations      : , i+1
72.## Uncomment to print particles 
73.#for p in particles: 
74.#    print ‘params: %s, fitness: %s, best: %s‘ % (p.params, p.fitness, p.best)

 

Python实现的粒子群优化算法

标签:

原文地址:http://www.cnblogs.com/felixzh/p/5540886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!