粒子群算法python代码实例实现
时间: 2023-11-15 10:57:28 浏览: 115
粒子群算法的python实现
以下是一个简单的粒子群算法的Python代码实现,用于求解函数最小值问题:
```python
import random
# 定义目标函数
def objective_function(x):
return x**2
# 定义粒子类
class Particle:
def __init__(self, dim):
self.position = [random.uniform(-5.0, 5.0) for i in range(dim)]
self.velocity = [random.uniform(-1.0, 1.0) for i in range(dim)]
self.best_position = self.position.copy()
self.best_fitness = objective_function(self.position)
def update(self, global_best_position, omega, phi_p, phi_g):
for i in range(len(self.position)):
r_p = random.uniform(0.0, 1.0)
r_g = random.uniform(0.0, 1.0)
self.velocity[i] = omega * self.velocity[i] + phi_p * r_p * (self.best_position[i] - self.position[i]) + phi_g * r_g * (global_best_position[i] - self.position[i])
self.position[i] += self.velocity[i]
fitness = objective_function(self.position)
if fitness < self.best_fitness:
self.best_position = self.position.copy()
self.best_fitness = fitness
# 定义粒子群类
class ParticleSwarm:
def __init__(self, num_particles, dim, max_iter):
self.num_particles = num_particles
self.dim = dim
self.max_iter = max_iter
self.particles = [Particle(dim) for i in range(num_particles)]
self.global_best_position = self.particles[0].position.copy()
self.global_best_fitness = objective_function(self.global_best_position)
def optimize(self, omega, phi_p, phi_g):
for i in range(self.max_iter):
for particle in self.particles:
particle.update(self.global_best_position, omega, phi_p, phi_g)
if particle.best_fitness < self.global_best_fitness:
self.global_best_position = particle.best_position.copy()
self.global_best_fitness = particle.best_fitness
print("Iteration {}: Best Fitness = {}".format(i+1, self.global_best_fitness))
# 运行粒子群算法
swarm = ParticleSwarm(num_particles=20, dim=1, max_iter=50)
swarm.optimize(omega=0.5, phi_p=0.5, phi_g=0.5)
print("Global Best Position = {}, Global Best Fitness = {}".format(swarm.global_best_position, swarm.global_best_fitness))
```
阅读全文