粒子群算法的python实现
时间: 2023-10-13 13:57:28 浏览: 132
粒子群算法的Python实现可以参考以下代码:
```python
import random
class ParticleSwarmOptimization:
def __init__(self, N, dim, x_bound, w, c1, c2, T, fun):
self.N = N # 粒子数量
self.dim = dim # 粒子维度
self.x_bound = x_bound # 粒子位置范围
self.w = w # 惯性权重
self.c1 = c1 # 学习因子1
self.c2 = c2 # 学习因子2
self.T = T # 迭代次数
self.fun = fun # 适应度函数
def optimize(self):
x = [] # 粒子位置
v = [] # 粒子速度
p = [] # 个体极值
fitness = [] # 适应度值
# 初始化粒子位置和速度
for j in range(self.N):
x.append([random.uniform(self.x_bound[0], self.x_bound[1]) for i in range(self.dim)])
v.append([random.uniform(self.x_bound[0], self.x_bound[1]) for m in range(self.dim)])
# 计算初始适应度值和个体极值
for j in range(self.N):
fitness.append(self.fun(x[j]))
p.append(x[j])
# 全局极值
best_fitness = min(fitness)
best_particle = x[fitness.index(best_fitness)]
# 迭代更新粒子位置和速度
for t in range(self.T):
for j in range(self.N):
for m in range(self.dim):
v[j][m] = self.w * v[j][m] + self.c1 * random.random() * (p[j][m] - x[j][m]) + self.c2 * random.random() * (best_particle[m] - x[j][m])
x[j][m] = x[j][m] + v[j][m]
# 限制粒子位置在范围内
if x[j][m] > self.x_bound[1]:
x[j][m] = self.x_bound[1]
if x[j][m] < self.x_bound[0]:
x[j][m] = self.x_bound[0]
# 更新个体极值和全局极值
fitness_j = self.fun(x[j])
if fitness_j < fitness[j]:
p[j] = x[j]
fitness[j] = fitness_j
if fitness_j < best_fitness:
best_particle = x[j]
best_fitness = fitness_j
return best_particle, best_fitness
```
这段代码实现了粒子群算法的优化过程。你可以根据自己的需求,定义适应度函数和问题的维度,并调用`optimize`方法来获得最优解和最优适应度值。
阅读全文