灰狼优化算法GWO

1.基本原理

1.1. 社会等级制度 (Social Hierarchy)

GWO 将狼群严格划分为四个等级,用以模拟寻优过程中的领导力:

Alpha (α): 领头狼,代表当前找到的最优解。负责决策。

Beta (β): 副手,代表第二优解。协助 Alpha 决策。

Delta (δ): 侦察兵、捕食者等,代表第三优解。负责执行指令。

Omega (ω): 底层狼,代表其他候选解。它们必须服从上述三者的指引。

1.2. 捕猎机制 (Hunting Mechanism)

算法通过模拟以下三个主要步骤来寻找全局最优解:

包围 (Encircling): 狼群根据猎物(目标点)的位置更新自己的位置。

狩猎 (Hunting): 认为 α、β 和 δ 对猎物潜在位置有更好的认知。其他狼(ω)根据这前三者的位置更新自己的坐标。

攻击 (Attacking): 通过调整参数,算法在探索(寻找新区域)和开发(精细搜索已知区域)之间取得平衡。

2.代码实现

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

def objective_function(x):
    d = len(x)
    shift = 1.5 
    z = x - shift
    
    z_rotated = np.copy(z)
    for i in range(1, d):
        z_rotated[i] = z[i] + 0.5 * z[i-1] 

    return 10 * d + np.sum(z_rotated**2 - 10 * np.cos(2 * np.pi * z_rotated))

class GWO:
    def __init__(self, obj_func, dim, search_range, num_wolves=30, max_iter=100):
        self.obj_func = obj_func
        self.dim = dim
        self.lb, self.ub = search_range
        self.num_wolves = num_wolves
        self.max_iter = max_iter
        self.positions = np.random.uniform(self.lb, self.ub, (num_wolves, dim))
        self.alpha_pos = np.zeros(dim)
        self.alpha_score = float("inf")
        self.beta_pos, self.beta_score = np.zeros(dim), float("inf")
        self.delta_pos, self.delta_score = np.zeros(dim), float("inf")
        self.convergence_curve = []

    def optimize(self):
        for t in range(self.max_iter):
            for i in range(self.num_wolves):
                self.positions[i] = np.clip(self.positions[i], self.lb, self.ub)
                fitness = self.obj_func(self.positions[i])
                
                if fitness < self.alpha_score:
                    self.delta_score, self.delta_pos = self.beta_score, self.beta_pos.copy()
                    self.beta_score, self.beta_pos = self.alpha_score, self.alpha_pos.copy()
                    self.alpha_score, self.alpha_pos = fitness, self.positions[i].copy()
                elif fitness < self.beta_score:
                    self.delta_score, self.delta_pos = self.beta_score, self.beta_pos.copy()
                    self.beta_score, self.beta_pos = fitness, self.positions[i].copy()
                elif fitness < self.delta_score:
                    self.delta_score, self.delta_pos = fitness, self.positions[i].copy()

            if t % 10 == 0:
                print(f"Iteration {t}: Best Fitness = {self.alpha_score:.6f}")

            a = 2 - t * (2 / self.max_iter)
            for i in range(self.num_wolves):
                for j in range(self.dim):
                    def get_X(p_pos, curr_pos, a_val):
                        r1, r2 = np.random.rand(), np.random.rand()
                        A, C = 2 * a_val * r1 - a_val, 2 * r2
                        D = abs(C * p_pos - curr_pos)
                        return p_pos - A * D

                    X1 = get_X(self.alpha_pos[j], self.positions[i, j], a)
                    X2 = get_X(self.beta_pos[j], self.positions[i, j], a)
                    X3 = get_X(self.delta_pos[j], self.positions[i, j], a)
                    self.positions[i, j] = (X1 + X2 + X3) / 3

            self.convergence_curve.append(self.alpha_score)
        return self.alpha_pos, self.alpha_score, self.convergence_curve

dim = 2
search_range = (-5, 5)
max_iter = 500

gwo = GWO(objective_function, dim, search_range, num_wolves=60, max_iter=max_iter)
best_pos, best_score, curve = gwo.optimize()
print("-" * 30)
print(f"最终优化结果:")
print(f"找到的最优坐标: {best_pos}")
print(f"最优得分: {best_score:.8f}")

fig = plt.figure(figsize=(16, 7))

ax1 = fig.add_subplot(1, 2, 1, projection='3d')
x = np.linspace(search_range[0], search_range[1], 100)
y = np.linspace(search_range[0], search_range[1], 100)
X, Y = np.meshgrid(x, y)

Z = np.zeros(X.shape)
for i in range(X.shape[0]):
    for j in range(X.shape[1]):
        Z[i, j] = objective_function(np.array([X[i, j], Y[i, j]]))

surf = ax1.plot_surface(X, Y, Z, cmap=cm.coolwarm, alpha=0.6, antialiased=True)

ax1.scatter(best_pos[0], best_pos[1], best_score, color='red', marker='*', s=200, label='GWO Best Point', zorder=20)
ax1.plot([best_pos[0], best_pos[0]], [best_pos[1], best_pos[1]], [0, best_score], color='black', linestyle='--', linewidth=1.5)

ax1.set_title("Target Function Surface & Optimal Point", fontsize=12)
ax1.set_xlabel('X1')
ax1.set_ylabel('X2')
ax1.set_zlabel('Fitness')
ax1.legend()

ax2 = fig.add_subplot(1, 2, 2)
ax2.semilogy(curve, color='teal', linewidth=2)
ax2.set_title("Convergence Process (Log Scale)", fontsize=12)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Fitness (Best Score)")
ax2.grid(True, which="both", linestyle='--', alpha=0.5)

plt.tight_layout()
plt.show()

运行效果

bash 复制代码
Iteration 0: Best Fitness = 14.571307
Iteration 10: Best Fitness = 1.144426
Iteration 20: Best Fitness = 0.143754
Iteration 30: Best Fitness = 0.143754
Iteration 40: Best Fitness = 0.143754
Iteration 50: Best Fitness = 0.031024
Iteration 60: Best Fitness = 0.031024
Iteration 70: Best Fitness = 0.031024
Iteration 80: Best Fitness = 0.031024
Iteration 90: Best Fitness = 0.031024
Iteration 100: Best Fitness = 0.031024
Iteration 110: Best Fitness = 0.002521
Iteration 120: Best Fitness = 0.002521
Iteration 130: Best Fitness = 0.002521
Iteration 140: Best Fitness = 0.002521
Iteration 150: Best Fitness = 0.002521
Iteration 160: Best Fitness = 0.002521
Iteration 170: Best Fitness = 0.002521
Iteration 180: Best Fitness = 0.002521
Iteration 190: Best Fitness = 0.002521
Iteration 200: Best Fitness = 0.002521
Iteration 210: Best Fitness = 0.002521
Iteration 220: Best Fitness = 0.002521
Iteration 230: Best Fitness = 0.002521
Iteration 240: Best Fitness = 0.002521
Iteration 250: Best Fitness = 0.002521
Iteration 260: Best Fitness = 0.002521
Iteration 270: Best Fitness = 0.002521
Iteration 280: Best Fitness = 0.002521
Iteration 290: Best Fitness = 0.002521
Iteration 300: Best Fitness = 0.002521
Iteration 310: Best Fitness = 0.002521
Iteration 320: Best Fitness = 0.002521
Iteration 330: Best Fitness = 0.000500
Iteration 340: Best Fitness = 0.000500
Iteration 350: Best Fitness = 0.000500
Iteration 360: Best Fitness = 0.000500
Iteration 370: Best Fitness = 0.000500
Iteration 380: Best Fitness = 0.000500
Iteration 390: Best Fitness = 0.000500
Iteration 400: Best Fitness = 0.000500
Iteration 410: Best Fitness = 0.000500
Iteration 420: Best Fitness = 0.000500
Iteration 430: Best Fitness = 0.000500
Iteration 440: Best Fitness = 0.000500
Iteration 450: Best Fitness = 0.000500
Iteration 460: Best Fitness = 0.000500
Iteration 470: Best Fitness = 0.000403
Iteration 480: Best Fitness = 0.000403
Iteration 490: Best Fitness = 0.000086
------------------------------
最终优化结果:
找到的最优坐标: [1.500069   1.50001847]
最优得分: 0.00000150
相关推荐
生信研究猿6 小时前
#P4475.第2题-终端款型聚类识别
机器学习·数据挖掘·聚类
用泥种荷花6 小时前
我把一次小程序像素风改版,沉淀成了一个可复用的 Trae Skill
人工智能
deephub6 小时前
【无标题】
人工智能·prompt·大语言模型·claude
数字供应链安全产品选型6 小时前
从模型投毒到提示词注入:悬镜安全如何用AI原生安全体系覆盖AI攻击全链路?
人工智能·安全·ai-native
FluxMelodySun6 小时前
机器学习(三十四) 概率图模型-马尔可夫随机场与条件随机场
人工智能·机器学习
用户5191495848456 小时前
Windows Hypervisor 分区漏洞利用与 IOCTL 通信测试工具
人工智能·aigc
CHENKONG_CK6 小时前
智流链驱动 RFID 混流装配,赋能汽车精益生产
网络·人工智能·tcp/ip·自动化·射频工程·rfid
天天代码码天天6 小时前
C# OnnxRuntime 部署 DAViD 深度估计
人工智能·david 深度估计
qyz_hr6 小时前
2026年AI招聘选购:5大品牌核心差异对比(红海云 / Moka / 北森 / 肯耐珂萨 / 金蝶)
大数据·人工智能
俊哥V6 小时前
每日 AI 研究简报 · 2026-04-20
人工智能·ai