其中,
是粒子
在时间
的速度,
是粒子
在时间
的位置,
是粒
子
的个人最佳位置,
是全局最佳位置,
是惯性权重,
和
是加速常数,
和
是[0,1]范围内的随机数。
1.2.3 示例代码:基于 Python 的粒子群优化算法实现
import numpy as np
import random
#
定义适应度函数,这里以一个简单的函数为例
def fitness_function(x):
return -(x[0] - 2)**2 - (x[1] - 2)**2 + 4
#
初始化粒子群
def init_particles(num_particles, num_dimensions):
particles = np.random.uniform(-10, 10, (num_particles, num_dimensions))
velocities = np.random.uniform(-1, 1, (num_particles, num_dimensions))
pbest = particles.copy()
pbest_fitness = np.array([fitness_function(p) for p in particles])
gbest = particles[np.argmax(pbest_fitness)]
return particles, velocities, pbest, gbest
#
更新粒子速度和位置
def update_particles(particles, velocities, pbest, gbest, w, c1, c2):
for i in range(len(particles)):
r1, r2 = random.random(), random.random()
velocities[i] = w * velocities[i] + c1 * r1 * (pbest[i] - particles[i]) + c2 * r2 * (gbest - particles[i]
)
particles[i] += velocities[i]
return particles, velocities
#
主循环
def pso(num_particles, num_dimensions, num_iterations, w, c1, c2):
particles, velocities, pbest, gbest = init_particles(num_particles, num_dimensions)
for _ in range(num_iterations):
for i in range(len(particles)):
fitness = fitness_function(particles[i])
if fitness > pbest_fitness[i]:
pbest[i] = particles[i].copy()
pbest_fitness[i] = fitness
gbest = particles[np.argmax(pbest_fitness)]
particles, velocities = update_particles(particles, velocities, pbest, gbest, w, c1, c2)
return gbest