📅  最后修改于: 2023-12-03 15:11:09.537000             🧑  作者: Mango
灰狼优化算法是一种新兴的优化算法,基于狼群的社会行为进行优化搜索。
import numpy as np
# 目标函数
def f(x):
return np.sum(np.square(x))
# 初始化灰狼群
def init_wolves(num_wolves, x_min, x_max, dim):
wolves = []
for i in range(num_wolves):
wolf_pos = np.random.uniform(x_min, x_max, dim)
wolves.append({'position': wolf_pos, 'cost': f(wolf_pos)})
return wolves
# 获取最优解
def get_best_wolf(wolves):
sorted_wolves = sorted(wolves, key=lambda k: k['cost'])
best_wolf = sorted_wolves[0]
return best_wolf
# 更新猎物位置
def update_prey_position(wolf, best_wolf, a):
x_pre = wolf['position']
r1 = np.random.rand(len(x_pre))
r2 = np.random.rand(len(x_pre))
A = 2 * a * r1 - a
C = 2 * r2
D = np.abs(C * best_wolf['position'] - x_pre)
x_new = np.clip(best_wolf['position'] - A*D, -1, 1)
return x_new
# 更新猎人位置
def update_hunter_position(wolf, wolves, A, alpha):
x_hunter = wolf['position']
idx_wolves = [i for i in range(len(wolves))]
idx_wolves.remove(wolves.index(wolf))
leader_wolf = wolves[np.argmin([w['cost'] for w in wolves])]
x_leader = leader_wolf['position']
D_alpha = np.abs(alpha * x_leader - x_hunter)
A_ = 2 * A * np.random.rand(len(x_hunter)) - A
x_new = np.clip(x_leader - A_ * D_alpha, -1, 1)
return x_new
# 灰狼优化算法
def GWO(num_iter, num_wolves, x_min, x_max, dim):
alpha = 1
a = 2 * alpha
wolves = init_wolves(num_wolves, x_min, x_max, dim)
best_wolf = get_best_wolf(wolves)
for i in range(num_iter):
for wolf in wolves:
x_pre = wolf['position']
if wolf == best_wolf:
x_new = update_prey_position(wolf, best_wolf, a)
else:
x_new = update_hunter_position(wolf, wolves, a, alpha)
cost_new = f(x_new)
if cost_new < wolf['cost']:
wolf['position'] = x_new.copy()
wolf['cost'] = cost_new
best_wolf = get_best_wolf(wolves)
return best_wolf['position'], best_wolf['cost']
# Test GWO function
x_min, x_max, dim = -1, 1, 10
num_iter = 200
num_wolves = 30
best_pos, best_cost = GWO(num_iter, num_wolves, x_min, x_max, dim)
print(f"Best position: {best_pos}")
print(f"Best cost: {best_cost}")
灰狼优化算法是一种新兴的优化算法,它是基于狼群的社会行为进行优化搜索。本文实现了灰狼优化算法,并使用一个简单的测试函数进行测试。该算法的性能表现表明它可以在多元函数优化问题中发挥作用。