本文共 2720 字,大约阅读时间需要 9 分钟。
`算法介绍
粒子群算法(particle swarm optimization,PSO)由Kennedy和Eberhart在1995年提出,该算法对于Hepper的模拟鸟群(鱼群)的模型进行修正,以使粒子能够飞向解空间,并在最好解处降落,从而得到了粒子群优化算法。同遗传算法类似,也是一种基于群体叠代的,但并没有遗传算法用的交叉以及变异,而是粒子在解空间追随最优的粒子进行搜索PSO的优势在于简单,容易实现,无需梯度信息,参数少,特别是其天然的实数编码特点特别适合于处理实优化问题。同时又有深刻的智能背景,既适合科学研究,又特别适合工程应用。
设想这样一个场景:一群鸟在随机的搜索食物。在这个区域里只有一块食物,所有的鸟都不知道食物在哪。但是它们知道自己当前的位置距离食物还有多远。那么找到食物的最优策略是什么?最简单有效的就是搜寻目前离食物最近的鸟的周围区域。算法流程
参数定义每个寻优的问题解都被想像成一只鸟,称为“粒子”。所有粒子都在一个d维空间进行搜索。所有的粒子都由一个fitness-function确定适应值以判断目前的位置好坏。每一个粒子必须赋予记忆功能,能记住所搜寻到的最佳位置。每一个粒子还有一个速度以决定飞行 转载https://blog.csdn.net/winycg/article/details/79120154 算法参考https://blog.csdn.net/zhaozx19950803/article/details/79854466"""粒子群算法求解函数最大值(最小值)f(x)= x + 10*sin5x + 7*cos4x"""import numpy as npimport matplotlib.pyplot as plt #粒子(鸟)class Particle: def __init__(self): self.p = 0 # 粒子当前位置 self.v = 0 # 粒子当前速度 self.pbest = 0 # 粒子历史最好位置 class PSO: def __init__(self,N=20,iter_N=100): self.w = 0.2 # 惯性因子 self.c1 = 1 # 自我认知学习因子 self.c2 = 2 # 社会认知学习因子 self.gbest = 0 # 种群当前最好位置 self.N = N # 种群中粒子数量 self.POP = [] # 种群 self.iter_N = iter_N # 迭代次数 # 适应度值计算函数 def fitness(self,x): return x + 10 * np.sin(5 * x) + 7 * np.cos(4 * x) # 找到全局最优解 def g_best(self,pop): for bird in pop: if bird.fitness > self.fitness(self.gbest): self.gbest = bird.p # 初始化种群 def initPopulation(self,pop,N): for i in range(N): bird = Particle() bird.p = np.random.uniform(-10,10) bird.fitness = self.fitness(bird.p) bird.pbest = bird.fitness pop.append(bird) # 找到种群中的最优位置 self.g_best(pop) # 更新速度和位置 def update(self,pop): for bird in pop: v = self.w * bird.v + self.c1 * np.random.random() * (bird.pbest - bird.p) + self.c2 * np.random.random() * (self.gbest - bird.p) p = bird.p + v if -10 < p < 10: bird.p = p bird.v = v # 更新适应度 bird.fitness = self.fitness(bird.p) # 是否需要更新本粒子历史最好位置 if bird.fitness > self.fitness(bird.pbest): bird.pbest = bird.p def implement(self): # 初始化种群 self.initPopulation(self.POP,self.N) def func(x): return x + 10 * np.sin(5 * x) + 7 * np.cos(4 * x) x = np.linspace(-10, 10, 1000) y = func(x) # 迭代 for i in range(self.iter_N): # 更新速度和位置 self.update(self.POP) # 更新种群中最好位置 self.g_best(self.POP) # 绘制动画 plt.clf() scatter_x = np.array([ind.p for ind in pso.POP]) scatter_y = np.array([ind.fitness for ind in pso.POP]) scatter_x1 = pso.gbest scatter_y1 = pso.fitness(pso.gbest) plt.plot(x, y) plt.scatter(scatter_x, scatter_y, c='b') plt.scatter(scatter_x1, scatter_y1, c='r') plt.pause(0.01) pso = PSO(N=20,iter_N=2)pso.implement() for ind in pso.POP: print("x = ",ind.p,"f(x) = ",ind.fitness) print("最优解 x = ",pso.gbest,"相应最大值 f(x) = ",pso.fitness(pso.gbest)) plt.show()