python 实现粒子群算法代码
时间: 2023-11-12 14:07:19 浏览: 75
下面是一个简单的 Python 粒子群算法的实现:
```python
import random
class Particle:
def __init__(self, x0):
self.position = []
self.velocity = []
self.best_position = []
self.fitness = -1
for i in range(0, num_dimensions):
self.velocity.append(random.uniform(-1, 1))
self.position.append(x0[i])
def evaluate(self, fitness_function):
self.fitness = fitness_function(self.position)
if self.fitness > self.best_fitness:
self.best_fitness = self.fitness
self.best_position = self.position
def update_velocity(self, best_global_position):
w = 0.5
c1 = 2
c2 = 2
for i in range(0, num_dimensions):
r1 = random.random()
r2 = random.random()
cognitive_velocity = c1 * r1 * (self.best_position[i] - self.position[i])
social_velocity = c2 * r2 * (best_global_position[i] - self.position[i])
self.velocity[i] = w * self.velocity[i] + cognitive_velocity + social_velocity
def update_position(self, bounds):
for i in range(0, num_dimensions):
self.position[i] = self.position[i] + self.velocity[i]
if self.position[i] > bounds[i][1]:
self.position[i] = bounds[i][1]
if self.position[i] < bounds[i][0]:
self.position[i] = bounds[i][0]
class PSO:
def __init__(self, fitness_function, x0, bounds, num_particles, maxiter):
global num_dimensions
num_dimensions = len(x0)
best_global_position = []
best_global_fitness = -1
swarm = []
for i in range(0, num_particles):
swarm.append(Particle(x0))
for i in range(0, maxiter):
for j in range(0, num_particles):
swarm[j].evaluate(fitness_function)
if swarm[j].fitness > best_global_fitness:
best_global_fitness = swarm[j].fitness
best_global_position = list(swarm[j].position)
for j in range(0, num_particles):
swarm[j].update_velocity(best_global_position)
swarm[j].update_position(bounds)
print('Best position:', best_global_position)
print('Best fitness:', best_global_fitness)
if __name__ == "__PSO__":
fitness_function = lambda x: x[0] ** 2 + x[1] ** 2
x0 = [random.uniform(-10, 10), random.uniform(-10, 10)]
bounds = [(-10, 10), (-10, 10)]
PSO(fitness_function, x0, bounds, num_particles=15, maxiter=30)
```
这里我们定义了 `Particle` 类,它包含了粒子的位置、速度、最佳位置和适应度等属性。`PSO` 类则是整个粒子群算法的实现,其中包括了初始化粒子群、更新粒子速度和位置等操作。在这个例子中,我们使用粒子群算法来最小化函数 $f(x) = x_1^2 + x_2^2$。
阅读全文