灰狼优化算法python程序
时间: 2023-06-30 12:08:39 浏览: 157
Python,灰狼优化算法
5星 · 资源好评率100%
灰狼优化算法(Grey Wolf Optimizer,GWO)是一种基于群体智能的优化算法,受到灰狼群行为的启发而提出。下面是一个用 Python 实现的简单的灰狼优化算法程序:
```python
import numpy as np
# 目标函数
def f(x):
return np.sum(np.square(x))
# 灰狼优化算法
def GWO(f, lb, ub, dim, SearchAgents_no, Max_iter):
# 初始化灰狼群
Positions = np.zeros((SearchAgents_no, dim))
for i in range(dim):
Positions[:, i] = np.random.uniform(lb[i], ub[i], SearchAgents_no)
# 初始化 alpha、beta、delta 灰狼
Alpha_pos = np.zeros(dim)
Alpha_score = float("inf")
Beta_pos = np.zeros(dim)
Beta_score = float("inf")
Delta_pos = np.zeros(dim)
Delta_score = float("inf")
# 迭代寻优
for l in range(0, Max_iter):
for i in range(0, SearchAgents_no):
# 计算适应度值
fitness = f(Positions[i, :])
# 更新 alpha、beta、delta 灰狼
if fitness < Alpha_score:
Alpha_score = fitness
Alpha_pos = Positions[i, :].copy()
if fitness > Alpha_score and fitness < Beta_score:
Beta_score = fitness
Beta_pos = Positions[i, :].copy()
if fitness > Alpha_score and fitness > Beta_score and fitness < Delta_score:
Delta_score = fitness
Delta_pos = Positions[i, :].copy()
# 调整灰狼群的位置
a = 2 - l * (2 / Max_iter) # a 衰减
for i in range(0, SearchAgents_no):
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A = 2 * a * r1 - a
C = 2 * r2
D_alpha = np.abs(C * Alpha_pos - Positions[i, :])
X1 = Alpha_pos - A * D_alpha
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A = 2 * a * r1 - a
C = 2 * r2
D_beta = np.abs(C * Beta_pos - Positions[i, :])
X2 = Beta_pos - A * D_beta
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A = 2 * a * r1 - a
C = 2 * r2
D_delta = np.abs(C * Delta_pos - Positions[i, :])
X3 = Delta_pos - A * D_delta
Positions[i, :] = (X1 + X2 + X3) / 3
# 返回最优解和最优值
Best_pos = Alpha_pos
Best_score = Alpha_score
return Best_pos, Best_score
# 测试
if __name__ == "__main__":
lb = [-10, -10, -10] # 搜索区间下界
ub = [10, 10, 10] # 搜索区间上界
dim = 3 # 变量维数
SearchAgents_no = 30 # 灰狼数量
Max_iter = 100 # 最大迭代次数
Best_pos, Best_score = GWO(f, lb, ub, dim, SearchAgents_no, Max_iter)
print("Best position: ", Best_pos)
print("Best score: ", Best_score)
```
上面的程序中,目标函数为 $f(x) = \sum_{i=1}^{dim}x_i^2$,搜索区间为 $[-10, 10]$,变量维数为 3,灰狼数量为 30,最大迭代次数为 100。程序输出搜索到的最优解和最优值。你可以根据需要修改这些参数和目标函数,来解决不同的优化问题。
阅读全文