粒子群算法python代码实例
时间: 2024-03-05 10:46:47 浏览: 167
粒子群算法(Particle Swarm Optimization,PSO)是一种优化算法,用于解决各种优化问题。下面是一个使用Python实现的粒子群算法的代码示例:
```python
import random
class Particle:
def __init__(self, dim):
self.position = [random.uniform(-5, 5) for _ in range(dim)]
self.velocity = [random.uniform(-1, 1) for _ in range(dim)]
self.best_position = self.position.copy()
self.best_fitness = float('inf')
def update_velocity(self, global_best_position, w, c1, c2):
for i in range(len(self.velocity)):
r1 = random.random()
r2 = random.random()
cognitive_component = c1 * r1 * (self.best_position[i] - self.position[i])
social_component = c2 * r2 * (global_best_position[i] - self.position[i])
self.velocity[i] = w * self.velocity[i] + cognitive_component + social_component
def update_position(self):
for i in range(len(self.position)):
self.position[i] += self.velocity[i]
if self.position[i] < -5:
self.position[i] = -5
elif self.position[i] > 5:
self.position[i] = 5
def evaluate_fitness(self):
# 这里根据具体的优化问题来定义适应度函数
x, y = self.position[0], self.position[1]
fitness = (x - 2) ** 2 + (y - 3) ** 2
if fitness < self.best_fitness:
self.best_fitness = fitness
self.best_position = self.position.copy()
def particle_swarm_optimization(dim, num_particles, max_iterations):
particles = [Particle(dim) for _ in range(num_particles)]
global_best_position = None
global_best_fitness = float('inf')
for _ in range(max_iterations):
for particle in particles:
particle.evaluate_fitness()
if particle.best_fitness < global_best_fitness:
global_best_fitness = particle.best_fitness
global_best_position = particle.best_position.copy()
for particle in particles:
particle.update_velocity(global_best_position, 0.5, 1, 2)
particle.update_position()
return global_best_position, global_best_fitness
# 示例使用二维空间中的粒子群算法来求解(x-2)^2 + (y-3)^2 的最小值
best_position, best_fitness = particle_swarm_optimization(2, 50, 100)
print("Best position:", best_position)
print("Best fitness:", best_fitness)
```
这段代码实现了一个简单的粒子群算法,用于求解二维空间中函数 (x-2)^2 + (y-3)^2 的最小值。代码中的参数可以根据具体问题进行调整。在每次迭代中,粒子根据自身的速度和位置更新策略来更新自己的位置,并根据新位置计算适应度值。全局最优解是所有粒子中适应度值最小的解。最后,算法返回全局最优解的位置和适应度值。
阅读全文