粒子群算法Python
时间: 2024-01-15 13:18:41 浏览: 123
粒子群算法(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):
# 计算适应度函数值,这里以目标函数的值作为适应度
fitness = sum([x ** 2 for x in self.position])
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, 1)
particle.update_position()
return global_best_position, global_best_fitness
# 示例使用
dim = 2 # 维度
num_particles = 20 # 粒子数量
max_iterations = 100 # 最大迭代次数
best_position, best_fitness = particle_swarm_optimization(dim, num_particles, max_iterations)
print("Best position: ", best_position)
print("Best fitness: ", best_fitness)
```
这个例子中,我们定义了一个粒子类(Particle),每个粒子有自己的位置(position)、速度(velocity)、最佳位置(best_position)和最佳适应度(best_fitness)。粒子群算法的核心是通过更新速度和位置来搜索最优解。在每次迭代中,粒子根据自身的最佳位置和全局最佳位置来更新速度,然后根据新的速度更新位置。最终,算法会返回全局最佳位置和最佳适应度。
阅读全文