基于 鲸鱼优化算法 (Whale Optimization Algorithm, WOA) 优化 VMD(变分模态分解)参数 K
和 α
的 Python 实现。
文章目录
WOA 是一种元启发式优化算法,可用于寻找最优的 VMD 参数组合。
1. 安装依赖
确保安装了必要的库:
pip install numpy scipy matplotlib scikit-learn
2. 鲸鱼优化算法 (WOA) 核心code
WOA 的核心实现代码:
import numpy as np
from scipy.optimize import minimize
# WOA 算法实现
def whale_optimization_algorithm(objective_func, lb, ub, dim, search_agents=30, max_iter=100):
# 初始化种群
X = np.random.uniform(lb, ub, (search_agents, dim))
best_position = np.zeros(dim)
best_score = float('inf')
for t in range(max_iter):
a = 2 - t * (2 / max_iter) # 线性递减参数 a
for i in range(search_agents):
# 计算适应度
fitness = objective_func(X[i])
if fitness < best_score:
best_score = fitness
best_position = X[i]
# 更新位置
r1 = np.random.rand()
r2 = np.random.rand()
A = 2 * a * r1 - a
C = 2 * r2
b = 1 # 螺旋形状参数
l = np.random.uniform(-1, 1)
p = np.random.rand()
if p < 0.5:
if abs(A) < 1:
D = abs(C * best_position - X[i])
X[i] = best_position - A * D
else:
rand_leader_index = np.random.randint(0, search_agents)
X_rand = X[rand_leader_index]
D_X_rand = abs(C * X_rand - X[i])
X[i] = X_rand - A * D_X_rand
else:
D_best = abs(best_position - X[i])
X[i] = D_best * np.exp(b * l) * np.cos(2 * np.pi * l) + best_position
# 边界处理
X[i] = np.clip(X[i], lb, ub)
return best_position, best_score
3. VMD 模态分解与目标函数
VMD 的目标是通过优化参数 K
和 α
来最小化重构误差或其他指标。我们使用 scipy
中的 minimize
函数来辅助优化,并定义目标函数。
from vmdpy import VMD # 需要安装 vmdpy 库:pip install vmdpy
# 目标函数:基于 VMD 的重构误差
def objective_function(params, signal):
K, alpha = params
K = int(K) # 模态数量必须为整数
alpha = max(0, alpha) # 确保 α 为正数
# 执行 VMD 分解
try:
u, u_hat, omega = VMD(signal, alpha=alpha, tau=0, K=K, DC=0, init=1, tol=1e-7)
reconstructed_signal = np.sum(u, axis=0) # 重构信号
error = np.mean((signal - reconstructed_signal) ** 2) # 均方误差
except Exception:
error = float('inf') # 如果参数无效,返回极大值
return error
4. 主程序:结合 WOA 和 VMD
xiamianzhege市 主程序,结合 WOA 和 VMD 进行参数优化:
import numpy as np
import matplotlib.pyplot as plt
# 示例信号
def generate_signal():
t = np.linspace(0, 1, 500)
signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 120 * t) # 合成信号
return t, signal
if __name__ == "__main__":
# 生成信号
t, signal = generate_signal()
# 定义搜索空间
lb = [2, 0.1] # K 和 α 的下界
ub = [10, 5000] # K 和 α 的上界
dim = 2 # 参数维度 (K 和 α)
# 使用 WOA 优化 VMD 参数
def wrapper(params):
return objective_function(params, signal)
best_params, best_score = whale_optimization_algorithm(
objective_func=wrapper,
lb=lb,
ub=ub,
dim=dim,
search_agents=20,
max_iter=50
)
# 输出优化结果
K_optimal, alpha_optimal = int(best_params[0]), best_params[1]
print(f"Optimal K: {K_optimal}, Optimal Alpha: {alpha_optimal:.2f}")
print(f"Best Objective Score: {best_score:.4f}")
# 使用最优参数进行 VMD 分解
u, u_hat, omega = VMD(signal, alpha=alpha_optimal, tau=0, K=K_optimal, DC=0, init=1, tol=1e-7)
# 可视化结果
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(t, signal, label="Original Signal")
plt.title("Original Signal")
plt.legend()
plt.subplot(2, 1, 2)
for i in range(K_optimal):
plt.plot(t, u[i], label=f"IMF {i+1}")
plt.title("VMD Decomposition")
plt.legend()
plt.show()
5. 结果说明
-
优化过程:
- WOA 会根据目标函数(如均方误差)调整
K
和α
的值。 - 最终输出优化后的
K
和α
参数。
- WOA 会根据目标函数(如均方误差)调整
-
VMD 分解:
- 使用优化后的参数对信号进行 VMD 分解,得到多个固有模态函数(IMFs)。
- 可视化原始信号和分解后的 IMFs。
6. 注意
-
参数范围:
K
的取值范围通常在[2, 10]
之间。α
的取值范围可以根据信号特性调整。
-
目标函数:
- 可根据具体需求修改目标函数,例如使用其他性能指标(如能量熵、频谱误差等)。
-
计算效率:
- VMD 的计算复杂度较高,建议在小规模数据集上测试。
以上代码仅供参考。
使用鲸鱼优化算法(WOA)来优化VMD参数的Python项目。,图表展示了迭代次数与目标函数值的关系。
完整的代码示例,包括如何运行这个项目以及如何生成类似的图表。
仅供参考。
1. 安装依赖
确保安装了必要的库:
pip install numpy scipy matplotlib vmdpy
2. 主要文件结构
假设你的项目文件结构如下:
- WOA.py
- VMD.py
- fitness_function.py
- main.py
3. 各个文件的内容
WOA.py
- 鲸鱼优化算法实现
import numpy as np
def whale_optimization_algorithm(objective_func, lb, ub, dim, search_agents=30, max_iter=100):
# 初始化种群
X = np.random.uniform(lb, ub, (search_agents, dim))
best_position = np.zeros(dim)
best_score = float('inf')
scores = []
for t in range(max_iter):
a = 2 - t * (2 / max_iter) # 线性递减参数 a
for i in range(search_agents):
# 计算适应度
fitness = objective_func(X[i])
if fitness < best_score:
best_score = fitness
best_position = X[i]
# 更新位置
r1 = np.random.rand()
r2 = np.random.rand()
A = 2 * a * r1 - a
C = 2 * r2
b = 1 # 螺旋形状参数
l = np.random.uniform(-1, 1)
p = np.random.rand()
if p < 0.5:
if abs(A) < 1:
D = abs(C * best_position - X[i])
X[i] = best_position - A * D
else:
rand_leader_index = np.random.randint(0, search_agents)
X_rand = X[rand_leader_index]
D_X_rand = abs(C * X_rand - X[i])
X[i] = X_rand - A * D_X_rand
else:
D_best = abs(best_position - X[i])
X[i] = D_best * np.exp(b * l) * np.cos(2 * np.pi * l) + best_position
# 边界处理
X[i] = np.clip(X[i], lb, ub)
scores.append(best_score)
return best_position, best_score, scores
VMD.py
- VMD 模态分解
from vmdpy import VMD
def vmd_decomposition(signal, K, alpha):
u, u_hat, omega = VMD(signal, alpha=alpha, tau=0, K=K, DC=0, init=1, tol=1e-7)
return u, u_hat, omega
fitness_function.py
- 目标函数
import numpy as np
def objective_function(params, signal):
K, alpha = params
K = int(K) # 模态数量必须为整数
alpha = max(0, alpha) # 确保 α 为正数
try:
u, u_hat, omega = vmd_decomposition(signal, K, alpha)
reconstructed_signal = np.sum(u, axis=0) # 重构信号
error = np.mean((signal - reconstructed_signal) ** 2) # 均方误差
except Exception:
error = float('inf') # 如果参数无效,返回极大值
return error
main.py
- 主程序
import numpy as np
import matplotlib.pyplot as plt
from WOA import whale_optimization_algorithm
from fitness_function import objective_function
from VMD import vmd_decomposition
# 示例信号
def generate_signal():
t = np.linspace(0, 1, 500)
signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 120 * t) # 合成信号
return t, signal
if __name__ == "__main__":
# 生成信号
t, signal = generate_signal()
# 定义搜索空间
lb = [2, 0.1] # K 和 α 的下界
ub = [10, 5000] # K 和 α 的上界
dim = 2 # 参数维度 (K 和 α)
# 使用 WOA 优化 VMD 参数
def wrapper(params):
return objective_function(params, signal)
best_params, best_score, scores = whale_optimization_algorithm(
objective_func=wrapper,
lb=lb,
ub=ub,
dim=dim,
search_agents=20,
max_iter=50
)
# 输出优化结果
K_optimal, alpha_optimal = int(best_params[0]), best_params[1]
print(f"Optimal K: {K_optimal}, Optimal Alpha: {alpha_optimal:.2f}")
print(f"Best Objective Score: {best_score:.4f}")
# 使用最优参数进行 VMD 分解
u, u_hat, omega = vmd_decomposition(signal, K_optimal, alpha_optimal)
# 可视化结果
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(t, signal, label="Original Signal")
plt.title("Original Signal")
plt.legend()
plt.subplot(2, 1, 2)
for i in range(K_optimal):
plt.plot(t, u[i], label=f"IMF {i+1}")
plt.title("VMD Decomposition")
plt.legend()
plt.show()
# 绘制迭代过程中的目标函数值
plt.figure(figsize=(8, 6))
plt.plot(scores, label="Objective Function Value")
plt.xlabel("Iteration")
plt.ylabel("Objective Function Value")
plt.title("Convergence Curve")
plt.legend()
plt.show()
4. 运行项目
确保所有文件都在同一目录下,并且已经安装了所需的库。然后在命令行中运行:
python main.py
这将执行鲸鱼优化算法来优化VMD参数,并绘制原始信号和分解后的IMFs,以及收敛曲线。