import random
class Particle:
def __init__(self, dim):
self.position = [random.uniform(-10, 10) for i in range(dim)]
self.velocity = [random.uniform(-1, 1) for i in range(dim)]
self.best_position = self.position[:]
self.best_fitness = float('inf')
self.fitness = None
def update_position(self):
self.position = [self.position[i] + self.velocity[i] for i in range(len(self.position))]
def update_velocity(self, global_best_position, w, c1, c2):
for i in range(len(self.velocity)):
r1 = random.random()
r2 = random.random()
cognitive_component = c1 * r1 * (self.best_position[i] - self.position[i])
social_component = c2 * r2 * (global_best_position[i] - self.position[i])
self.velocity[i] = w * self.velocity[i] + cognitive_component + social_component
class PSO:
def __init__(self, num_particles, dim, w, c1, c2, num_iterations):
self.num_particles = num_particles
self.dim = dim
self.w = w
self.c1 = c1
self.c2 = c2
self.num_iterations = num_iterations
self.particles = [Particle(dim) for i in range(num_particles)]
def optimize(self):
global_best_position = None
global_best_fitness = float('inf')
for i in range(self.num_iterations):
for particle in self.particles:
fitness = particle.position[0] ** 2
particle.fitness = fitness
if fitness < particle.best_fitness:
particle.best_fitness = fitness
particle.best_position = particle.position[:]
if fitness < global_best_fitness:
global_best_fitness = fitness
global_best_position = particle.position[:]
for particle in self.particles:
particle.update_velocity(global_best_position, self.w, self.c1, self.c2)
particle.update_position()
return global_best_position, global_best_fitness
if __name__ == '__main__':
pso = PSO(num_particles=30, dim=1, w=0.8, c1=2, c2=2, num_iterations=1000)
best_position, best_fitness = pso.optimize()
print("Best position: ", best_position)
print("Best fitness: ", best_fitness)
以上代码实现了一个粒子群算法,用于求解函数f(x)=x^2在[-10,10]范围内的最小值。
代码中定义了Particle类和PSO类,其中Particle类表示一个粒子,包含了其位置、速度、最佳位置和最佳适应度。PSO类是粒子群算法的主要实现,包括了初始化粒子、优化过程中的位置和速度更新,以及求解全局最优解等功能。
在主函数中,我们创建了一个PSO对象,设置了算法的超参数,包括粒子数、维度、惯性权重、个体和社会因子、迭代次数。我们运行了optimize方法,得到了最优解和最优适应度。
代码中使用了随机数生成器来初始化粒子位置和速度,以及在位置和速度更新中使用随机数生成器生成随机数。在每次迭代中,对于每个粒子,计算其适应度,并更新其最佳位置和最佳适应度,同时更新全局最优位置和最优适应度。然后更新粒子的速度和位置。
最后输出了求解得到的最优解和最优适应度。
需要注意的是,这个示例实现的是一维粒子群算法,只有一个维度。如果需要求解高维函数的最小值,需要将粒子的维度增加。
Python版的粒子群算法
import random
import math
# 粒子群算法
class ParticleSwarmOptimization:
def _init_(self, cost_func, x_min, x_max, swarm_size=50, max_iter=10, c1=2, c2=2):
self.cost_func = cost_func
self.x_min = x_min
self.x_max = x_max
self.swarm_size = swarm_size
self.max_iter = max_iter
self.c1 = c1
self.c2 = c2
self.swarm = []
self.gbest = {'position': None, 'cost': math.inf}
# 初始化粒子群
def init_swarm(self):
for _ in range(self.swarm_size):
position = [random.uniform(self.x_min, self.x_max) for _ in range(len(self.x_min))]
cost = self.cost_func(position)
particle = {
'position': position,
'cost': cost,
'pbest': {'position': position, 'cost': cost},
'velocity': [0 for _ in range(len(self.x_min))]
}
self.swarm.append(particle)
if particle['cost'] < self.gbest['cost']:
self.gbest = particle['pbest']
# 更新粒子群
def update_swarm(self):
for particle in self.swarm:
# 更新速度
for i in range(len(particle['velocity'])):
r1 = random.random(i)
r2 = random.random(i)
particle['velocity'][i] = particle['velocity'][i] + self.c1 * r1 * (particle['pbest']['position'][i] - particle['position'][i]) + self.c2 * r2 * (self.gbest['position'][i] - particle['position'][i])
# 更新位置
for _ in range(len(particle['position'])):
particle['position'][i] = particle['position'][i] + particle['velocity'][i]
# 更新个体最优
particle['cost'] = self.cost_func(particle['position'])
if particle['cost'] < particle['pbest']['cost']:
particle['pbest'] = {'position': particle['position'], 'cost': particle['cost']}
# 更新全局最优
if particle['pbest']['cost'] < self.gbest['cost']:
self.gbest = particle['pbest']
# 运行粒子群算法
def run(self):
self.init_swarm()
for _ in range(self.max_iter):
self.update_swarm()
return self.gbest
在上面的代码中,Particle类表示一个粒子,包含了其位置、速度、最佳位置和最佳适应度。PSO类是粒子群算法的主要实现,包括了初始化粒子、优化过程中的位置和速度更新,以及求解全局最优解等功能。在主函数中,我们定义了一个PSO对象,设置了算法的超参数,并运行了optimize方法,得到了最优解和最优适应度。