灰狼算法Python代码
时间: 2023-11-05 07:29:25 浏览: 96
以下是基于Python的灰狼算法代码示例:
```python
import numpy as np
def obj_func(x):
# 目标函数,这里以f(x) = x^2为例
return np.sum(np.power(x, 2))
def grey_wolf_optimizer(obj_func, lb, ub, dim, search_agent_num, max_iter):
# obj_func: 目标函数
# lb: 取值下界
# ub: 取值上界
# dim: 变量个数
# search_agent_num: 狼群数量
# max_iter: 最大迭代次数
# 初始化搜索代理
positions = np.random.uniform(lb, ub, (search_agent_num, dim))
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 i in range(max_iter):
# 计算每个搜索代理到三个灰狼的距离
for j in range(search_agent_num):
fitness = obj_func(positions[j])
if fitness < alpha_score:
alpha_score = fitness
alpha_pos = positions[j]
if fitness > alpha_score and fitness < beta_score:
beta_score = fitness
beta_pos = positions[j]
if fitness > alpha_score and fitness > beta_score and fitness < delta_score:
delta_score = fitness
delta_pos = positions[j]
a = 2 - 2 * i / max_iter # 确定a值
for j in range(search_agent_num):
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A1 = 2 * a * r1 - a
C1 = 2 * r2
D_alpha = np.abs(C1 * alpha_pos - positions[j])
X1 = alpha_pos - A1 * D_alpha
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A2 = 2 * a * r1 - a
C2 = 2 * r2
D_beta = np.abs(C2 * beta_pos - positions[j])
X2 = beta_pos - A2 * D_beta
r1 = np.random.rand(dim)
r2 = np.random.rand(dim)
A3 = 2 * a * r1 - a
C3 = 2 * r2
D_delta = np.abs(C3 * delta_pos - positions[j])
X3 = delta_pos - A3 * D_delta
positions[j] = (X1 + X2 + X3) / 3
return alpha_pos, alpha_score
```
其中,`obj_func`是目标函数,`lb`和`ub`是取值下界和上界,`dim`是变量个数,`search_agent_num`是狼群数量,`max_iter`是最大迭代次数。函数返回最优解和最优解对应的函数值。
阅读全文