粒子群算法代码python
时间: 2024-05-03 17:15:54 浏览: 90
粒子群算法(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)
print("最优适应度:", best_fitness)
```
这段代码实现了一个简单的粒子群算法,用于求解一个二维目标函数的最小值。你可以根据需要修改目标函数和算法参数来适应不同的问题。
阅读全文