粒子群算法求解七维函数
时间: 2023-11-21 16:55:29 浏览: 69
以下是使用粒子群算法求解七维函数的Python代码示例:
```python
import random
# 定义目标函数
def target_function(x):
return x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2 + x[4]**2 + x[5]**2 + x[6]**2
# 粒子群算法
class ParticleSwarmOptimization:
def __init__(self, target_function, dim, size, max_iter, c1, c2, w):
self.target_function = target_function # 目标函数
self.dim = dim # 搜索空间维度
self.size = size # 粒子群规模
self.max_iter = max_iter # 最大迭代次数
self.c1 = c1 # 学习因子1
self.c2 = c2 # 学习因子2
self.w = w # 惯性权重
self.x = [[random.uniform(-100, 100) for _ in range(dim)] for _ in range(size)] # 粒子位置
self.v = [[random.uniform(-1, 1) for _ in range(dim)] for _ in range(size)] # 粒子速度
self.pbest = self.x # 个体最优位置
self.gbest = self.x[0] # 全局最优位置
self.gbest_fitness = float('inf') # 全局最优适应度
def optimize(self):
for i in range(self.max_iter):
for j in range(self.size):
fitness = self.target_function(self.x[j])
if fitness < self.target_function(self.pbest[j]):
self.pbest[j] = self.x[j]
if fitness < self.gbest_fitness:
self.gbest = self.x[j]
self.gbest_fitness = fitness
for j in range(self.size):
for k in range(self.dim):
r1 = random.random()
r2 = random.random()
self.v[j][k] = self.w * self.v[j][k] + self.c1 * r1 * (self.pbest[j][k] - self.x[j][k]) + self.c2 * r2 * (self.gbest[k] - self.x[j][k])
self.x[j][k] += self.v[j][k]
return self.gbest, self.gbest_fitness
# 使用粒子群算法求解七维函数
pso = ParticleSwarmOptimization(target_function, dim=7, size=50, max_iter=100, c1=2, c2=2, w=0.8)
result = pso.optimize()
print("最优解:", result[0])
print("最优适应度:", result[1])
```
阅读全文