灰狼优化算法 Python 代码实现
import numpy as np
def GreyWolfOptimizer(objf, lb, ub, dim, SearchAgents_no, Max_iter): # 灰狼算法参数 # lb——下界;ub——上界;dim——变量维数;SearchAgents_no——搜索种群数目;Max_iter——最大迭代次数
# 初始化算法
# 生成搜索种群(位置)
Positions = np.random.uniform(0, 1, (SearchAgents_no, dim)) * (ub - lb) + lb
# 生成灰狼,三只
Alpha_pos = np.random.uniform(0, 1, (1, dim)) * (ub - lb) + lb
Beta_pos = np.random.uniform(0, 1, (1, dim)) * (ub - lb) + lb
Delta_pos = np.random.uniform(0, 1, (1, dim)) * (ub - lb) + lb
# 初始化灰狼的评价值
Alpha_score = objf(Alpha_pos)
Beta_score = objf(Beta_pos)
Delta_score = objf(Delta_pos)
# 记录搜索种群的评价值
Convergence_curve = np.zeros(Max_iter)
# 开始迭代
print('GWO is optimizing '{}''.format(objf.__name__))
s = ['' for _ in range(SearchAgents_no)]
for l in range(0, Max_iter):
for i in range(0, SearchAgents_no):
# 评价搜索种群
fitness = objf(Positions[i])
# 更新灰狼
if fitness > Alpha_score:
Alpha_score = fitness; Alpha_pos = Positions[i]
if (fitness > Beta_score and fitness < Alpha_score):
Beta_score = fitness; Beta_pos = Positions[i]
if (fitness > Delta_score and fitness < Beta_score):
Delta_score = fitness; Delta_pos = Positions[i]
a = 2 - l * (2 / Max_iter); # 按迭代次数递减的步长
# 更新搜索种群
for i in range(0, SearchAgents_no):
for j in range(0, dim):
r1 = np.random.random(); r2 = np.random.random()
A1 = 2 * a * r1 - a; A2 = 2 * r2 - 1
C1 = 2 * r1; C2 = 2 * r2
D_alpha = abs(C1 * Alpha_pos[0, j] - Positions[i, j])
X1 = Alpha_pos[0, j] - A1 * D_alpha
D_beta = abs(C2 * Beta_pos[0, j] - Positions[i, j])
X2 = Beta_pos[0, j] - A2 * D_beta
D_delta = abs(C1 * Delta_pos[0, j] - Positions[i, j])
X3 = Delta_pos[0, j] - A1 * D_delta
Positions[i, j] = (X1 + X2 + X3) / 3
# 确保新位置在边界内
Positions[i, :] = np.maximum(Positions[i, :], lb)
Positions[i, :] = np.minimum(Positions[i, :], ub)
Convergence_curve[l] = Alpha_score
if (l % 1 == 0):
print(['At iteration ' + str(l) + ' the best fitness is ' + str(Alpha_score)])
s = 'Iteration ' + str(l + 1) + ': best position is:' + str(Alpha_pos) + ', best score is:' + str(Alpha_score)
#print(s)
return Alpha_pos, Alpha_score, Convergence_curve
原文地址: https://www.cveoy.top/t/topic/lgT6 著作权归作者所有。请勿转载和采集!