PSO算法代码
时间: 2023-07-05 21:06:07 浏览: 72
以下是基于Python的PSO算法代码示例:
```python
import random
class PSO:
def __init__(self, objective_function, num_particles, num_iterations, bounds):
self.objective_function = objective_function
self.num_particles = num_particles
self.num_iterations = num_iterations
self.bounds = bounds
self.particles = []
for i in range(num_particles):
particle = {}
for j in range(len(bounds)):
particle[j] = random.uniform(bounds[j][0], bounds[j][1])
particle['velocity'] = [random.uniform(-1, 1) for _ in range(len(bounds))]
particle['best_position'] = particle.copy()
self.particles.append(particle)
self.global_best_position = None
def run(self):
for i in range(self.num_iterations):
for particle in self.particles:
fitness = self.objective_function(*[particle[i] for i in range(len(self.bounds))])
if particle['best_position'] is None or fitness < self.objective_function(*[particle['best_position'][i] for i in range(len(self.bounds))]):
particle['best_position'] = particle.copy()
if self.global_best_position is None or fitness < self.objective_function(*[self.global_best_position[i] for i in range(len(self.bounds))]):
self.global_best_position = particle.copy()
for particle in self.particles:
for j in range(len(self.bounds)):
v = particle['velocity'][j] + 2 * random.random() * (particle['best_position'][j] - particle[j]) + 2 * random.random() * (self.global_best_position[j] - particle[j])
particle['velocity'][j] = min(1, max(-1, v))
particle[j] = particle[j] + particle['velocity'][j]
if particle[j] < self.bounds[j][0]:
particle[j] = self.bounds[j][0]
if particle[j] > self.bounds[j][1]:
particle[j] = self.bounds[j][1]
return self.global_best_position
```
其中,objective_function表示优化的目标函数,num_particles为粒子群的数量,num_iterations为迭代次数,bounds为变量的取值范围。在运行PSO算法时,可以调用该类的run方法,返回全局最优解的位置。
阅读全文