python PSO算法
时间: 2023-11-26 17:48:54 浏览: 119
以下是使用Python实现PSO算法的示例代码:
```python
import random
class Particle:
def __init__(self, dim, minx, maxx):
self.__pos = [random.uniform(minx, maxx) for i in range(dim)]
self.__vel = [random.uniform(-1, 1) for i in range(dim)]
self.__best_pos = self.__pos
self.__fitness = float('inf')
self.__best_fitness = float('inf')
def update_fitness(self, fitness_func):
self.__fitness = fitness_func(self.__pos)
if self.__fitness < self.__best_fitness:
self.__best_fitness = self.__fitness
self.__best_pos = self.__pos
def move(self):
for i in range(len(self.__pos)):
self.__pos[i] = self.__pos[i] + self.__vel[i]
def set_pos(self, pos):
self.__pos = pos
def set_vel(self, vel):
self.__vel = vel
def get_pos(self):
return self.__pos
def get_vel(self):
return self.__vel
def get_best_pos(self):
return self.__best_pos
def get_fitness(self):
return self.__fitness
def get_best_fitness(self):
return self.__best_fitness
class PSO:
def __init__(self, dim, size, minx, maxx, fitness_func, max_iter=100, phi1=2.0, phi2=2.0, inertia_weight=0.7):
self.__particles = [Particle(dim, minx, maxx) for i in range(size)]
self.__fitness_func = fitness_func
self.__max_iter = max_iter
self.__phi1 = phi1
self.__phi2 = phi2
self.__inertia_weight = inertia_weight
self.__best_fitness = float('inf')
self.__best_pos = None
def run(self):
for i in range(self.__max_iter):
for p in self.__particles:
p.update_fitness(self.__fitness_func)
if p.get_fitness() < self.__best_fitness:
self.__best_fitness = p.get_fitness()
self.__best_pos = p.get_pos()
for p in self.__particles:
new_vel = []
for j in range(len(p.get_vel())):
r1 = random.uniform(0, 1)
r2 = random.uniform(0, 1)
cognitive_vel = self.__phi1 * r1 * (p.get_best_pos()[j] - p.get_pos()[j])
social_vel = self.__phi2 * r2 * (self.__best_pos[j] - p.get_pos()[j])
new_vel.append(self.__inertia_weight * p.get_vel()[j] + cognitive_vel + social_vel)
p.set_vel(new_vel)
p.move()
def get_best_fitness(self):
return self.__best_fitness
def get_best_pos(self):
return self.__best_pos
```
使用示例:
```python
def sphere(x):
return sum([xi ** 2 for xi in x])
pso = PSO(dim=10, size=50, minx=-10, maxx=10, fitness_func=sphere)
pso.run()
print("Best fitness: ", pso.get_best_fitness())
print("Best position: ", pso.get_best_pos())
```
该示例实现了一个简单的PSO算法,用于求解10维的Sphere函数的最小值。用户可以根据自己的需求修改fitness_func函数,来求解不同的优化问题。
阅读全文