粒子群算法的python代码
时间: 2024-04-16 17:23:22 浏览: 194
粒子群算法(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, self.position
fitness = x**2 + y**2
return fitness
class PSO:
def __init__(self, num_particles, num_iterations, dim, w, c1, c2):
self.num_particles = num_particles
self.num_iterations = num_iterations
self.dim = dim
self.w = w
self.c1 = c1
self.c2 = c2
self.global_best_position = * dim
self.global_best_fitness = float('inf')
self.particles = [Particle(dim) for _ in range(num_particles)]
def optimize(self):
for _ in range(self.num_iterations):
for particle in self.particles:
fitness = particle.evaluate_fitness()
if fitness < particle.best_fitness:
particle.best_fitness = fitness
particle.best_position = particle.position.copy()
if fitness < self.global_best_fitness:
self.global_best_fitness = fitness
self.global_best_position = particle.position.copy()
for particle in self.particles:
particle.update_velocity(self.global_best_position, self.w, self.c1, self.c2)
particle.update_position()
if __name__ == '__main__':
num_particles = 30
num_iterations = 100
dim = 2
w = 0.5
c1 = 1
c2 = 2
pso = PSO(num_particles, num_iterations, dim, w, c1, c2)
pso.optimize()
print("Optimal solution:", pso.global_best_position)
print("Optimal fitness:", pso.global_best_fitness)
```
这段代码实现了一个简单的粒子群算法,用于求解二维目标函数的最小值。你可以根据需要修改目标函数和算法参数来适应不同的问题。
阅读全文