pso代码
时间: 2023-07-02 15:13:40 浏览: 88
PSO算法代码
以下是一个简单的PSO算法的Python实现,可以用于解决优化问题:
```python
import numpy as np
class Particle:
def __init__(self, bounds):
self.position = np.random.uniform(bounds[0], bounds[1])
self.velocity = np.zeros_like(self.position)
self.best_position = self.position
self.best_fitness = np.inf
def update(self, omega, phi_p, phi_g, swarm_best_position):
r_p = np.random.uniform(size=self.position.shape)
r_g = np.random.uniform(size=self.position.shape)
self.velocity = omega * self.velocity \
+ phi_p * r_p * (self.best_position - self.position) \
+ phi_g * r_g * (swarm_best_position - self.position)
self.position += self.velocity
def evaluate(self, fitness_func):
fitness = fitness_func(self.position)
if fitness < self.best_fitness:
self.best_position = self.position
self.best_fitness = fitness
class PSO:
def __init__(self, bounds, num_particles, max_iter, fitness_func):
self.bounds = bounds
self.num_particles = num_particles
self.max_iter = max_iter
self.fitness_func = fitness_func
self.swarm = [Particle(bounds) for _ in range(num_particles)]
self.swarm_best_position = np.inf * np.ones_like(bounds[0])
self.swarm_best_fitness = np.inf
def optimize(self, omega=0.5, phi_p=0.5, phi_g=0.5):
for i in range(self.max_iter):
for particle in self.swarm:
particle.evaluate(self.fitness_func)
if particle.best_fitness < self.swarm_best_fitness:
self.swarm_best_position = particle.best_position
self.swarm_best_fitness = particle.best_fitness
for particle in self.swarm:
particle.update(omega, phi_p, phi_g, self.swarm_best_position)
return self.swarm_best_position, self.swarm_best_fitness
```
使用示例:
```python
# 定义要优化的函数
def sphere(x):
return np.sum(x**2)
# 实例化PSO类并运行PSO算法
bounds = (-5.12, 5.12)
num_particles = 50
max_iter = 100
pso = PSO(bounds, num_particles, max_iter, sphere)
best_position, best_fitness = pso.optimize()
print('Optimal solution:', best_position)
print('Optimal value:', best_fitness)
```
阅读全文