PSO算法

简易粒子群优化教程(使用 Python)

粒子群优化(PSO)是一种基于群体智能的优化算法,由 Dr. Eberhart 和 Dr. Kennedy 于 1995 年提出。PSO 模仿了鸟群或鱼群的行为,寻找最优解。与其他进化计算技术(如遗传算法)类似,PSO 也是一种基于种群的搜索算法。PSO 的优势在于它简单易于实现,并且在许多情况下效果显著。

本文将逐步讲解如何在 Python 中实现简易的 PSO 算法。


粒子群优化概述

PSO 的核心思想是将一组解(称为粒子)在搜索空间中随机初始化,并通过不断更新它们的位置来寻找最优解。每个粒子都有一个位置、速度和适应度(fitness),以及个体最优位置 (pbest) 和群体最优位置 (gbest)。

PSO 公式如下:

v i ( t + 1 ) = v i ( t ) + c 1 r 1 ( p b e s t i − x i ) + c 2 r 2 ( g b e s t − x i ) v_{i}(t+1) = v_{i}(t) + c_1 r_1 (pbest_{i} - x_{i}) + c_2 r_2 (gbest - x_{i}) vi(t+1)=vi(t)+c1r1(pbesti−xi)+c2r2(gbest−xi)

x i ( t + 1 ) = x i ( t ) + v i ( t + 1 ) x_{i}(t+1) = x_{i}(t) + v_{i}(t+1) xi(t+1)=xi(t)+vi(t+1)

其中:

  • ( x i x_{i} xi) 是第 ( i i i) 个粒子的位置
  • ( v i v_{i} vi) 是第 ( i i i) 个粒子的速度
  • ( p b e s t i p_{best}^{i} pbesti) 是粒子的历史最优位置
  • ( g b e s t gbest gbest) 是当前群体中的最优位置
  • ( c 1 c_1 c1) 和 ( c 2 c_2 c2) 是加速常数,通常设为 2
  • ( r 1 r_1 r1) 和 ( r 2 r_2 r2) 是随机数,在 (0) 到 (1) 之间

实现步骤

1. 粒子类

首先,我们定义一个 Particle 类,用于表示 PSO 中的粒子。每个粒子都有位置、速度、个体最优位置和适应度值。

python 复制代码
import random

class Particle:
    def __init__(self, bounds):
        self.position = []          # 粒子当前位置
        self.velocity = []          # 粒子当前速度
        self.best_position = []     # 粒子最优位置
        self.best_score = float('inf')  # 粒子最优适应度
        self.score = float('inf')   # 当前适应度

        for i in range(len(bounds)):
            self.position.append(random.uniform(bounds[i][0], bounds[i][1]))
            self.velocity.append(random.uniform(-1, 1))

    def update_position(self, bounds):
        for i in range(len(self.position)):
            self.position[i] += self.velocity[i]
            if self.position[i] > bounds[i][1]:
                self.position[i] = bounds[i][1]
            if self.position[i] < bounds[i][0]:
                self.position[i] = bounds[i][0]
2. PSO 算法

接下来,我们定义一个 PSO 类,用于执行 PSO 算法。

python 复制代码
class PSO:
    def __init__(self, cost_function, bounds, num_particles, max_iter):
        self.cost_function = cost_function
        self.bounds = bounds
        self.num_particles = num_particles
        self.max_iter = max_iter

    def optimize(self):
        particles = [Particle(self.bounds) for _ in range(self.num_particles)]
        gbest_position = []
        gbest_score = float('inf')

        for t in range(self.max_iter):
            for particle in particles:
                particle.score = self.cost_function(particle.position)

                # 更新个体最优位置
                if particle.score < particle.best_score:
                    particle.best_score = particle.score
                    particle.best_position = particle.position

                # 更新群体最优位置
                if particle.score < gbest_score:
                    gbest_score = particle.score
                    gbest_position = particle.position

            # 更新每个粒子的位置和速度
            for particle in particles:
                for i in range(len(particle.position)):
                    r1 = random.random()
                    r2 = random.random()
                    cognitive = 2 * r1 * (particle.best_position[i] - particle.position[i])
                    social = 2 * r2 * (gbest_position[i] - particle.position[i])
                    particle.velocity[i] = particle.velocity[i] + cognitive + social
                particle.update_position(self.bounds)

            print(f'迭代: {t}, 最优解: {gbest_score}')
3. 适应度函数

为了测试 PSO 算法,我们定义了一个简单的适应度函数(如球函数)。

python 复制代码
def sphere_function(position):
    return sum([x**2 for x in position])
4. 主函数

最后,我们编写主函数,调用 PSO 类,并运行算法。

python 复制代码
if __name__ == "__main__":
    # 设置粒子的搜索空间边界
    bounds = [(-10, 10), (-10, 10)]

    # 创建 PSO 对象
    pso = PSO(cost_function=sphere_function, bounds=bounds, num_particles=30, max_iter=50)

    # 执行优化
    pso.optimize()

总结

PSO 是一种简单而强大的优化算法,可以用来解决各种优化问题。在本文中,我们实现了一个基础的 PSO 算法,演示了如何用 Python 编写并优化一个简单的适应度函数。

相关推荐
weixin_446260859 小时前
LLM智能体在社交模拟中的决策行为分析:有限状态与LLM-based策略对比研究
开发语言·php
牛肉在哪里9 小时前
ros2 从零开始28 监听广播C++
开发语言·c++·算法·机器人
hnxaoli9 小时前
统信程序(十二)档案归档文件管理
python
乐观勇敢坚强的老彭9 小时前
GESP一级核心算法:循环与条件判断的结合
java·数据结构·算法
noipp9 小时前
推荐题目:洛谷 P1737 [NOI2016] 旷野大计算
linux·数据结构·算法
techdashen9 小时前
Cargo 1.94 开发周期全解析
开发语言·后端·rust
love530love9 小时前
2026年终极防坑指南:基于 EPGF 架构彻底“本地化” UV 环境与工具
人工智能·windows·python·架构·devops·uv·epgf
QiLinkOS10 小时前
极客精神与商业思维的融合实践(2)
c语言·c++·人工智能·算法·开源协议
charlie11451419110 小时前
现代C++特性指南——constexpr 构造函数与字面类型
开发语言·c++
北城以北888810 小时前
虚拟机安装JDK,Tomcat,部署项目
java·开发语言·tomcat