以下是一个Python实现的基本粒子群优化算法:
```python
import random
class Particle:
def __init__(self, dim, bound):
self.position = [random.uniform(bound[0], bound[1]) for _ in range(dim)]
self.velocity = [random.uniform(-1, 1) for _ in range(dim)]
self.fitness = None
self.best_position = []
self.best_fitness = None
class PSO:
def __init__(self, dim, size, iter_num, bound, eval_func, c1=2.0, c2=2.0, w=1.0):
self.dim = dim
self.size = size
self.iter_num = iter_num
self.bound = bound
self.eval_func = eval_func
self.c1 = c1
self.c2 = c2
self.w = w
self.swarm = [Particle(dim, bound) for _ in range(size)]
self.best_position = []
self.best_fitness = None
def evolve(self):
for i in range(self.iter_num):
for particle in self.swarm:
particle.fitness = self.eval_func(particle.position)
if particle.best_fitness is None or particle.fitness > particle.best_fitness:
particle.best_position = particle.position
particle.best_fitness = particle.fitness
if self.best_fitness is None or particle.fitness > self.best_fitness:
self.best_position = particle.position
self.best_fitness = particle.fitness
for particle in self.swarm:
r1 = random.random()
r2 = random.random()
for j in range(self.dim):
particle.velocity[j] = self.w * particle.velocity[j] \
+ self.c1 * r1 * (particle.best_position[j] - particle.position[j]) \
+ self.c2 * r2 * (self.best_position[j] - particle.position[j])
if particle.velocity[j] > (self.bound[1] - self.bound[0]) / 2:
particle.velocity[j] = (self.bound[1] - self.bound[0]) / 2
elif particle.velocity[j] < -(self.bound[1] - self.bound[0]) / 2:
particle.velocity[j] = -(self.bound[1] - self.bound[0]) / 2
particle.position[j] += particle.velocity[j]
if particle.position[j] > self.bound[1]:
particle.position[j] = self.bound[1]
elif particle.position[j] < self.bound[0]:
particle.position[j] = self.bound[0]
```
使用方法示例:
```python
def rastrigin(x):
return 10 * len(x) + sum([xi**2 - 10 * math.cos(2 * math.pi * xi) for xi in x])
pso = PSO(dim=5, size=50, iter_num=500, bound=(-5.12, 5.12), eval_func=rastrigin)
pso.evolve()
print(pso.best_position)
print(pso.best_fitness)
```
其中,`rastrigin`是优化目标函数,这里使用的是Rastrigin函数,可以自行替换为其他的优化目标函数。