pso算法python
时间: 2023-09-11 14:04:14 浏览: 179
以下是一个简单的PSO算法Python实现:
```
import random
# PSO算法参数设置
w = 0.5
c1 = 0.8
c2 = 0.9
# 求解的目标函数
def objective_function(x):
return x ** 2
# 粒子类
class Particle:
def __init__(self, x0):
self.position_i = [] # 粒子的位置
self.velocity_i = [] # 粒子的速度
self.pos_best_i = [] # 粒子最好的位置
self.err_best_i = -1 # 粒子最好的适应度值
self.err_i = -1 # 粒子当前适应度值
for i in range(0, num_dimensions):
self.velocity_i.append(random.uniform(-1, 1))
self.position_i.append(x0[i])
# 更新粒子的位置和速度
def update(self, pos_best_g):
for i in range(0, num_dimensions):
r1 = random.random()
r2 = random.random()
vel_cognitive = c1 * r1 * (self.pos_best_i[i] - self.position_i[i])
vel_social = c2 * r2 * (pos_best_g[i] - self.position_i[i])
self.velocity_i[i] = w * self.velocity_i[i] + vel_cognitive + vel_social
self.position_i[i] += self.velocity_i[i]
# 计算粒子的适应度值
def evaluate(self, objective_function):
self.err_i = objective_function(self.position_i)
if self.err_i < self.err_best_i or self.err_best_i == -1:
self.pos_best_i = self.position_i
self.err_best_i = self.err_i
# PSO算法主函数
class PSO:
def __init__(self, objective_function, x0, bounds, num_particles, maxiter):
global num_dimensions
num_dimensions = len(x0)
err_best_g = -1
pos_best_g = []
swarm = []
for i in range(0, num_particles):
swarm.append(Particle(x0))
i = 0
while i < maxiter:
# 遍历所有粒子,更新其位置和速度
for j in range(0, num_particles):
swarm[j].evaluate(objective_function)
if swarm[j].err_i < err_best_g or err_best_g == -1:
pos_best_g = list(swarm[j].position_i)
err_best_g = float(swarm[j].err_i)
for j in range(0, num_particles):
swarm[j].update(pos_best_g)
i += 1
# 输出最优解和适应度值
print('Best Position: ', pos_best_g)
print('Best Error: ', err_best_g)
if __name__ == "__PSO__":
initial = [5] # 初始解
bounds = [(-10, 10)] # 取值范围
PSO(objective_function, initial, bounds, num_particles=15, maxiter=30)
```
该实现中定义了一个Particle类来表示粒子,它包含了粒子的位置、速度等信息,同时还定义了更新位置和速度、计算适应度值等方法。在PSO类中,首先定义了一些PSO算法的参数,然后生成了一个粒子群,遍历所有粒子,计算每个粒子的适应度值,并记录全局最优解。接着更新所有粒子的位置和速度,循环迭代直到满足停止条件。最后输出最优解和适应度值。
阅读全文