赞
踩
- import random
- 鸟群初始化 = random.random()
- 鸟群 = 鸟群初始化
-
- def 个体发现的最优位置():
- return 1
- def 群体发现的最优位置():
- return 1
-
- class 鸟个体():
- def __init__(self, 鸟初始位置):
- self.鸟位置 = 鸟初始位置
-
- def 鸟个体位置更新(self, 群体最优位置, 个体最优位置):
- 个体学习因子 = 0.5
- 群体学习因子 = 0.5
- assert (个体学习因子+群体学习因子)==1,"学习因子设置错误!"
- ####
- self.鸟位置 = 鸟更新位置
-
-
- 群体迭代限制 = 100
- for 群体迭代次数 in range(群体迭代限制):
- 群体最优位置 = 群体发现的最优位置()
- for 鸟个体 in 鸟群:
- 个体最优位置 = 个体发现的最优位置()
- 鸟个体.鸟个体位置更新(群体最优位置, 个体最优位置)
遗传算法与粒子群算法的Python实现 这篇博客里面有一个很棒的例子,我相信是可以用作参考的
Help on package pyswarm:
NAME
pyswarm
DESCRIPTION
=========================================================================
pyswarm: Particl swarm optimization (PSO) with constraint support =========================================================================
Author: Abraham Lee
Copyright: 2013-2014
PACKAGE CONTENTS
pso
VERSION
0.6
AUTHOR
Abraham Lee
FILE
....
- from pyswarm import pso
- import numpy as np
- import pyswarm
-
- def opt(x):
- x1 = x[0]
- x2 = x[1]
- x3 = x[2]
- x4 = x[3]
-
- return (x1 + 2)**2 +\
- (x2 - 3)**2 +\
- (x3 + 2)**2 +\
- x4
-
- def con(x):
- tol = 1e-4
-
- x1 = x[0]
- x2 = x[1]
- x3 = x[2]
- x4 = x[3]
-
- return [ x2 - x1 ,tol-(x4-3)**2]
-
- lb = [-5, -5, -5, -5]
- ub = [ 5, 5, 5, 5]
-
- xopt, fopt = pso(opt, lb, ub, f_ieqcons=con)
- print("xopt:", xopt)
- print("fopt:", fopt)
Stopping search: maximum iterations reached --> 100
xopt: [-2.04252256 2.86597889 -1.96153295 2.9900635 ]
fopt: 3.0113130416323957
tol(1e-n) | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
opt(should be 3) | 2.68 | 2.90 | 2.98 | 3.43 | 6.81 | 19.91 | 13.89 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。