粒子群算法python代码
时间: 2023-10-21 21:27:39 浏览: 168
下面是一个简单的粒子群优化算法的 Python 代码示例:
```python
import random
class Particle:
def __init__(self, dimensions, bounds):
self.position = [random.uniform(bounds[i][0], bounds[i][1]) for i in range(dimensions)]
self.velocity = [random.uniform(-1, 1) for _ in range(dimensions)]
self.best_position = self.position.copy()
self.best_fitness = float('inf')
def update_velocity(self, global_best_position, inertia_weight, cognitive_weight, social_weight):
for i in range(len(self.velocity)):
r1 = random.random()
r2 = random.random()
cognitive = cognitive_weight * r1 * (self.best_position[i] - self.position[i])
social = social_weight * r2 * (global_best_position[i] - self.position[i])
self.velocity[i] = inertia_weight * self.velocity[i] + cognitive + social
def update_position(self, bounds):
for i in range(len(self.position)):
self.position[i] += self.velocity[i]
if self.position[i] < bounds[i][0]:
self.position[i] = bounds[i][0]
elif self.position[i] > bounds[i][1]:
self.position[i] = bounds[i][1]
def evaluate_fitness(self, objective_function):
fitness = objective_function(self.position)
if fitness < self.best_fitness:
self.best_fitness = fitness
self.best_position = self.position.copy()
def particle_swarm_optimization(objective_function, dimensions, bounds, num_particles, max_iterations, inertia_weight, cognitive_weight, social_weight):
particles = [Particle(dimensions, bounds) for _ in range(num_particles)]
global_best_fitness = float('inf')
global_best_position = None
for _ in range(max_iterations):
for particle in particles:
particle.update_velocity(global_best_position, inertia_weight, cognitive_weight, social_weight)
particle.update_position(bounds)
particle.evaluate_fitness(objective_function)
if particle.best_fitness < global_best_fitness:
global_best_fitness = particle.best_fitness
global_best_position = particle.best_position.copy()
return global_best_position, global_best_fitness
# 示例目标函数:求解 f(x) = x^2 的最小值
def objective_function(x):
return x[0] ** 2
# 算法参数设置
dimensions = 1
bounds = [(-10, 10)] # 变量的取值范围
num_particles = 20
max_iterations = 100
inertia_weight = 0.5
cognitive_weight = 1.0
social_weight = 1.0
# 运行粒子群优化算法
best_position, best_fitness = particle_swarm_optimization(objective_function, dimensions, bounds, num_particles, max_iterations, inertia_weight, cognitive_weight, social_weight)
print("Best position:", best_position)
print("Best fitness:", best_fitness)
```
请注意,这只是一个简单示例,可能不适用于所有情况。你可以根据自己的需求进行修改和优化。
阅读全文