灰狼优化算法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
相关推荐
盼小辉丶2 小时前
Transformer实战——Transformer跨语言零样本学习
深度学习·transformer·零样本学习
sheyuDemo2 小时前
关于深度学习的d2l库的安装
人工智能·python·深度学习·机器学习·numpy
政安晨2 小时前
政安晨【人工智能项目随笔】OpenClaw网关与子节点完整配对指南——从零构建分布式AI助手网络
人工智能·ai网关·openclaw·分布式ai助手网络·openclaw分布式子节点·分布式ai节点·主节点-子节点
shenxianasi2 小时前
【论文精读】Language Is Not All You Need: Aligning Perceptionwith Language Models
人工智能·机器学习·计算机视觉·语言模型·自然语言处理·vllm·audiolm
这是个栗子2 小时前
AI辅助编程工具(八) - Baidu Comate
人工智能·ai·baidu comate
Caesar Zou2 小时前
深度学习14: Adversarial attacks
人工智能·深度学习
SmartBrain2 小时前
FastAPI 进阶(第二部分):SQLAlchemy ORM(含考题)
数据库·人工智能·aigc·fastapi
向哆哆2 小时前
道路表面多类型缺陷的图像识别数据集分享(适用于目标检测任务)
人工智能·目标检测·计算机视觉
格林威2 小时前
Baumer相机药瓶铝盖压合完整性检测:防止密封失效的 7 个关键技术,附 OpenCV+Halcon 实战代码!
人工智能·opencv·计算机视觉·视觉检测·工业相机·智能相机·堡盟相机