用python解决用粒子群算法求最小值
时间: 2024-01-05 07:03:09 浏览: 107
粒子群算法寻最小值程序
粒子群优化算法(Particle Swarm Optimization, PSO)是一种常用的优化算法,它模拟鸟群或鱼群等生物的群体行为,通过不断地迭代寻找最优解。下面是使用Python实现粒子群算法求解最小值的代码示例:
```python
import random
class Particle:
def __init__(self, dim, max_iter):
# 粒子的维度
self.dim = dim
# 最大迭代次数
self.max_iter = max_iter
# 当前迭代次数
self.iter = 0
# 粒子的位置和速度
self.position = [random.uniform(-10, 10) for _ in range(dim)]
self.velocity = [random.uniform(-1, 1) for _ in range(dim)]
# 粒子的最佳位置和最佳适应度值
self.best_position = self.position
self.best_fitness = self.fitness()
# 计算粒子的适应度值
def fitness(self):
# 这里以 Rosenbrock 函数为例
x = self.position
return sum(100.0 * (x[i + 1] - x[i] ** 2) ** 2 + (1 - x[i]) ** 2 for i in range(self.dim - 1))
# 更新粒子的位置和速度
def update(self, global_best_position, omega, phi_p, phi_g):
r_p = [random.uniform(0, 1) for _ in range(self.dim)]
r_g = [random.uniform(0, 1) for _ in range(self.dim)]
for i in range(self.dim):
self.velocity[i] = omega * self.velocity[i] + phi_p * r_p[i] * (self.best_position[i] - self.position[i]) + phi_g * r_g[i] * (global_best_position[i] - self.position[i])
self.position[i] += self.velocity[i]
self.iter += 1
fitness = self.fitness()
if fitness < self.best_fitness:
self.best_position = self.position
self.best_fitness = fitness
class PSO:
def __init__(self, dim, size, max_iter):
# 粒子的维度
self.dim = dim
# 粒子的数量
self.size = size
# 最大迭代次数
self.max_iter = max_iter
# 全局最佳位置和最佳适应度值
self.global_best_position = [random.uniform(-10, 10) for _ in range(dim)]
self.global_best_fitness = float('inf')
# 初始化粒子群
self.particles = [Particle(dim, max_iter) for _ in range(size)]
# 运行 PSO 算法
def run(self, omega=0.5, phi_p=0.5, phi_g=0.5):
for i in range(self.max_iter):
for particle in self.particles:
if particle.best_fitness < self.global_best_fitness:
self.global_best_position = particle.best_position
self.global_best_fitness = particle.best_fitness
for particle in self.particles:
particle.update(self.global_best_position, omega, phi_p, phi_g)
print('Iteration {}: global best fitness = {}'.format(i + 1, self.global_best_fitness))
if __name__ == '__main__':
pso = PSO(dim=2, size=30, max_iter=100)
pso.run()
```
上面的代码实现了一个简单的二维粒子群算法,在 Rosenbrock 函数上寻找最小值。你可以根据实际情况修改代码中的函数和参数来适应不同的问题。
阅读全文