python粒子群算法
时间: 2023-07-10 08:04:18 浏览: 68
粒子群算法(Particle Swarm Optimization,PSO)是一种优化算法,它通过模拟鸟群或鱼群等生物群体的行为,来寻找最优解。PSO 算法基于一组粒子在解空间中寻找最优解。每个粒子代表一个解向量,它们通过互相交换信息来寻找全局最优解。
Python实现粒子群算法的步骤如下:
1.初始化粒子群,包括粒子数、位置、速度等参数。
2.计算每个粒子的适应度函数值。
3.更新全局最优解和每个粒子的最优解。
4.更新每个粒子的速度和位置。
5.重复执行步骤 2-4,直到满足停止条件。
下面是一个简单的 Python 粒子群算法示例代码:
```python
import random
# 适应度函数
def fitness(x):
return x*x
# 初始化粒子群
def init_pso(num_particles, num_dimensions):
particles = []
for i in range(num_particles):
particle = []
for j in range(num_dimensions):
particle.append(random.uniform(-10, 10))
particles.append({'position': particle, 'velocity': [0]*num_dimensions, 'best_position': particle, 'best_fitness': fitness(particle)})
return particles
# 更新每个粒子的速度和位置
def update_particle(particle, global_best_position, w, c1, c2):
for i in range(len(particle['velocity'])):
r1 = random.random()
r2 = random.random()
particle['velocity'][i] = w*particle['velocity'][i] + c1*r1*(particle['best_position'][i] - particle['position'][i]) + c2*r2*(global_best_position[i] - particle['position'][i])
particle['position'][i] += particle['velocity'][i]
particle_fitness = fitness(particle['position'])
if particle_fitness < particle['best_fitness']:
particle['best_fitness'] = particle_fitness
particle['best_position'] = particle['position'][:]
return particle
# 执行 PSO 算法
def pso(num_particles, num_dimensions, num_iterations, w, c1, c2):
particles = init_pso(num_particles, num_dimensions)
global_best_fitness = float('inf')
global_best_position = None
for i in range(num_iterations):
for particle in particles:
particle = update_particle(particle, global_best_position, w, c1, c2)
if particle['best_fitness'] < global_best_fitness:
global_best_fitness = particle['best_fitness']
global_best_position = particle['best_position'][:]
return global_best_position, global_best_fitness
# 示例运行
num_particles = 50
num_dimensions = 2
num_iterations = 100
w = 0.7
c1 = 1.5
c2 = 1.5
best_position, best_fitness = pso(num_particles, num_dimensions, num_iterations, w, c1, c2)
print('最优解:', best_position)
print('最优解的适应度值:', best_fitness)
```
该示例中,适应度函数为 $f(x) = x^2$,粒子数为 50,维度为 2,迭代次数为 100,惯性权重 w 为 0.7,自我认知因子 c1 和社会认知因子 c2 均为 1.5。运行结果如下:
```
最优解: [-0.0019305071809707066, 0.02241322202304724]
最优解的适应度值: 0.0004647110670625105
```
可以看到,该算法成功找到了适应度函数的最小值。
阅读全文