粒子群优化算法python
时间: 2023-07-03 17:33:35 浏览: 163
粒子群优化算法(Particle Swarm Optimization,PSO)是一种基于群体智能的优化算法,常用于求解优化问题。下面是一个简单的Python实现:
```python
import random
import math
class Particle:
def __init__(self, dim, lb, ub):
self.position = [random.uniform(lb, ub) for i in range(dim)]
self.velocity = [random.uniform(lb, ub) for i in range(dim)]
self.best_position = self.position.copy()
self.best_fitness = float('inf')
def update_velocity(self, global_best_position, w, c1, c2):
for i in range(len(self.velocity)):
r1, r2 = random.uniform(0, 1), random.uniform(0, 1)
cognitive = c1 * r1 * (self.best_position[i] - self.position[i])
social = c2 * r2 * (global_best_position[i] - self.position[i])
self.velocity[i] = w * self.velocity[i] + cognitive + social
def update_position(self, lb, ub):
for i in range(len(self.position)):
self.position[i] += self.velocity[i]
if self.position[i] < lb:
self.position[i] = lb
elif self.position[i] > ub:
self.position[i] = ub
def evaluate(self, obj_func):
fitness = obj_func(self.position)
if fitness < self.best_fitness:
self.best_fitness = fitness
self.best_position = self.position.copy()
class PSO:
def __init__(self, obj_func, dim, size, lb, ub, max_iter):
self.obj_func = obj_func
self.dim = dim
self.size = size
self.lb = lb
self.ub = ub
self.max_iter = max_iter
self.particles = [Particle(dim, lb, ub) for i in range(size)]
self.global_best_fitness = float('inf')
self.global_best_position = [0] * dim
def optimize(self):
for iter in range(self.max_iter):
for particle in self.particles:
particle.evaluate(self.obj_func)
if particle.best_fitness < self.global_best_fitness:
self.global_best_fitness = particle.best_fitness
self.global_best_position = particle.best_position.copy()
for particle in self.particles:
particle.update_velocity(self.global_best_position, 0.7, 1.5, 1.5)
particle.update_position(self.lb, self.ub)
return self.global_best_position, self.global_best_fitness
```
其中,Particle类表示粒子,包含位置、速度、最佳位置和最佳适应度;PSO类表示粒子群优化算法,包含目标函数、维度、粒子数、搜索范围、最大迭代次数、粒子列表和全局最佳位置和适应度。optimize方法是优化函数,其中先遍历所有粒子并计算其适应度和最佳位置,然后更新全局最佳位置。接着更新所有粒子的速度和位置,最后返回全局最佳位置和适应度。
使用方法如下:
```python
def sphere(x):
return sum([xi ** 2 for xi in x])
pso = PSO(sphere, 30, 50, -100, 100, 100)
best_position, best_fitness = pso.optimize()
print(best_position, best_fitness)
```
这里定义了一个目标函数sphere,是一个标准的多维球形函数。然后创建一个PSO对象,设置维度为30,粒子数为50,搜索范围为-100到100,最大迭代次数为100。最后调用optimize方法求解最优解。
阅读全文