Python实现的粒子群优化算法

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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值