粒子群算法python代码实现
时间: 2023-11-14 09:10:26 浏览: 91
以下是粒子群算法的Python代码实现:
```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(minx - maxx, maxx - minx) for i in range(dim)]
self.__best_pos = self.__pos
self.__fitness = float('inf')
self.__best_fitness = float('inf')
def update(self, func):
self.__pos = [self.__pos[i] + self.__vel[i] for i in range(len(self.__pos))]
self.__fitness = func(self.__pos)
if self.__fitness < self.__best_fitness:
self.__best_fitness = self.__fitness
self.__best_pos = self.__pos
def get_pos(self):
return self.__pos
def get_best_pos(self):
return self.__best_pos
def get_fitness(self):
return self.__fitness
class PSO:
def __init__(self, dim, size, iter_num, minx, maxx):
self.__particles = [Particle(dim, minx, maxx) for i in range(size)]
self.__gbest_fitness = float('inf')
self.__gbest_pos = [random.uniform(minx, maxx) for i in range(dim)]
self.__iter_num = iter_num
def update(self, func):
for i in range(self.__iter_num):
for particle in self.__particles:
particle.update(func)
if particle.get_fitness() < self.__gbest_fitness:
self.__gbest_fitness = particle.get_fitness()
self.__gbest_pos = particle.get_pos()
def get_gbest_pos(self):
return self.__gbest_pos
def get_gbest_fitness(self):
return self.__gbest_fitness
```
这段代码实现了一个简单的粒子群算法,其中Particle类表示一个粒子,PSO类表示整个粒子群。在PSO类的update方法中,每个粒子都会根据当前的速度和位置更新自己,并更新全局最优解。最后,get_gbest_pos和get_gbest_fitness方法可以分别获取全局最优解的位置和适应度值。
阅读全文