python GWO-PSO
时间: 2023-12-19 10:32:26 浏览: 85
对比了GWO灰狼优化算法和PSO粒子群优化算法,对比十几个目标函数,GWO性能优于PSO
5星 · 资源好评率100%
```python
# Python GWO-PSO示例
# 这是一个简单的Python示例,演示了GWO-PSO算法的实现。
# 导入所需的库
import numpy as np
# 初始化参数
num_wolves = 5
num_dimensions = 10
max_iter = 100
c1 = 2.0
c2 = 2.0
w = 0.7
# 初始化狼群位置
wolves_position = np.random.uniform(-10, 10, (num_wolves, num_dimensions))
# 初始化速度
velocity = np.zeros((num_wolves, num_dimensions))
# 初始化个体最佳位置和适应度
p_best_position = wolves_position
p_best_fitness = np.inf
# 初始化全局最佳位置和适应度
g_best_position = np.zeros(num_dimensions)
g_best_fitness = np.inf
# 开始迭代
for t in range(max_iter):
for i in range(num_wolves):
fitness = calculate_fitness(wolves_position[i])
# 更新个体最佳位置和适应度
if fitness < p_best_fitness:
p_best_fitness = fitness
p_best_position[i] = wolves_position[i]
# 更新全局最佳位置和适应度
if fitness < g_best_fitness:
g_best_fitness = fitness
g_best_position = wolves_position[i]
# 更新速度和位置
for i in range(num_wolves):
r1 = np.random.rand(num_dimensions)
r2 = np.random.rand(num_dimensions)
velocity[i] = w * velocity[i] + c1 * r1 * (p_best_position[i] - wolves_position[i]) + c2 * r2 * (g_best_position - wolves_position[i])
wolves_position[i] = wolves_position[i] + velocity[i]
# 输出全局最佳位置和适应度
print("Global best position: ", g_best_position)
print("Global best fitness: ", g_best_fitness)
```
阅读全文