灰狼算法python代码
时间: 2023-10-12 18:10:42 浏览: 119
以下是灰狼算法的 Python 代码实现:
```python
import numpy as np
# 定义灰狼算法类
class GreyWolfOptimizer:
def __init__(self, cost_func, num_dim, num_wolves=5, alpha=2, beta=3, delta=5, lb=-100, ub=100):
self.cost_func = cost_func # 优化目标函数
self.num_dim = num_dim # 变量维度
self.num_wolves = num_wolves # 狼群数量
self.alpha = alpha # 常量 alpha
self.beta = beta # 常量 beta
self.delta = delta # 常量 delta
self.lb = lb # 变量下界
self.ub = ub # 变量上界
self.pos = np.zeros((self.num_wolves, self.num_dim)) # 狼群位置
self.obj_val = np.zeros(self.num_wolves) # 目标函数值
self.best_pos = np.zeros(self.num_dim) # 最优位置
self.best_obj_val = np.inf # 最优目标函数值
# 初始化狼群位置
def init_pos(self):
self.pos = np.random.uniform(self.lb, self.ub, (self.num_wolves, self.num_dim))
self.obj_val = np.array([self.cost_func(p) for p in self.pos])
self.best_pos = self.pos[np.argmin(self.obj_val)]
self.best_obj_val = np.min(self.obj_val)
# 狼群位置更新
def update_pos(self):
a = 2 - 2 * np.linspace(0, 1, self.num_wolves) # Eq. (3.3)
c = 2 * np.linspace(0, 1, self.num_wolves) # Eq. (3.4)
A = 2 * self.alpha * np.random.rand(self.num_dim) - self.alpha # Eq. (3.5)
C = 2 * self.beta * np.random.rand(self.num_dim) - self.beta # Eq. (3.6)
D = 2 * self.delta * np.random.rand(self.num_dim) - self.delta # Eq. (3.7)
for i in range(self.num_wolves):
X1 = self.pos[i]
X2 = self.best_pos
X3 = self.pos[np.random.randint(0, self.num_wolves)]
D_alpha = np.abs(C * X1 - X2) # Eq. (3.8)
D_beta = np.abs(A * X1 - X2) # Eq. (3.9)
D_delta = np.abs(D * X1 - X2) # Eq. (3.10)
X_new = (X1 + a[i] * (D_alpha * np.sign(C * X1 - X2) +
D_beta * np.sign(A * X1 - X2) +
D_delta * np.sign(D * X1 - X2))) # Eq. (3.1)
# 边界处理
X_new = np.clip(X_new, self.lb, self.ub)
# 更新目标函数值
obj_val_new = self.cost_func(X_new)
# 更新最优解
if obj_val_new < self.best_obj_val:
self.best_pos = X_new
self.best_obj_val = obj_val_new
# 更新狼群位置和目标函数值
self.pos[i] = X_new
self.obj_val[i] = obj_val_new
# 灰狼算法优化过程
def optimize(self, max_iter=100):
self.init_pos()
for i in range(max_iter):
self.update_pos()
return self.best_pos, self.best_obj_val
```
使用方法如下:
```python
# 定义目标函数
def cost_func(x):
return np.sum(x ** 2)
# 初始化灰狼算法
gwo = GreyWolfOptimizer(cost_func, num_dim=10, num_wolves=30, alpha=2, beta=3, delta=5, lb=-100, ub=100)
# 进行优化
best_pos, best_obj_val = gwo.optimize(max_iter=100)
# 输出结果
print('最优解:', best_pos)
print('最优目标函数值:', best_obj_val)
```
其中,`cost_func` 是待优化的目标函数,`num_dim` 是变量维度,`num_wolves` 是狼群数量,`alpha`、`beta` 和 `delta` 是常量,`lb` 和 `ub` 是变量的下界和上界。在优化过程中,可以通过调整 `max_iter` 参数来控制最大迭代次数。最终输出的是最优解和最优目标函数值。
阅读全文