求帝王蝶优化算法(MBOA)Python代码及结果报错解决指导
帝王蝶优化算法(Monarch Butterfly Optimization, MBOA)Python实现
以下是帝王蝶优化算法的Python实现,以经典Sphere函数作为测试目标函数,你可根据需求替换为实际优化问题的目标函数:
import numpy as np def sphere_function(x): """测试用Sphere目标函数,求最小值""" return np.sum(x ** 2) def monarch_butterfly_optimization(obj_func, dim, bounds, max_iter, npop=50, p=0.7): """ 帝王蝶优化算法实现 参数: obj_func: 目标函数,输入个体向量,输出适应度值 dim: 变量维度 bounds: 变量取值范围,格式为[(min1, max1), (min2, max2), ..., (dim, maxdim)] max_iter: 最大迭代次数 npop: 种群规模,默认50 p: 迁徙比例,默认0.7(p*Npop个个体参与迁徙操作) 返回: best_fitness: 最优适应度值 best_position: 最优位置向量 """ # 初始化种群 lower_bound = np.array([b[0] for b in bounds]) upper_bound = np.array([b[1] for b in bounds]) population = np.random.uniform(low=lower_bound, high=upper_bound, size=(npop, dim)) # 计算初始适应度 fitness = np.array([obj_func(ind) for ind in population]) best_idx = np.argmin(fitness) best_fitness = fitness[best_idx] best_position = population[best_idx].copy() for iter_num in range(max_iter): # 迁徙操作(Migration operator) num_migrate = int(np.round(p * npop)) migrate_indices = np.random.choice(npop, num_migrate, replace=False) for idx in migrate_indices: source_idx = np.random.choice([i for i in range(npop) if i != idx]) population[idx] = population[source_idx] + np.random.uniform(-1, 1, dim) * (best_position - population[source_idx]) population[idx] = np.clip(population[idx], lower_bound, upper_bound) # 调整操作(Adjustment operator) adjust_indices = np.array([i for i in range(npop) if i not in migrate_indices]) for idx in adjust_indices: r1, r2 = np.random.choice([i for i in range(npop) if i != idx], 2, replace=False) population[idx] = population[idx] + np.random.uniform(-1, 1, dim) * (population[r1] - population[r2]) population[idx] = np.clip(population[idx], lower_bound, upper_bound) # 更新最优解 fitness = np.array([obj_func(ind) for ind in population]) current_best_idx = np.argmin(fitness) current_best_fitness = fitness[current_best_idx] if current_best_fitness < best_fitness: best_fitness = current_best_fitness best_position = population[current_best_idx].copy() return best_fitness, best_position # 测试示例 if __name__ == "__main__": dim = 30 bounds = [(-100, 100)] * dim max_iter = 100 best_fit, best_pos = monarch_butterfly_optimization(sphere_function, dim, bounds, max_iter) print(f"最优适应度值: {best_fit:.6f}") print(f"最优位置向量: {best_pos}")
关键检查点
若你自己的代码结果错误,可对比上述实现排查:
- 迁徙、调整阶段的核心公式是否正确
- 个体更新后的边界处理是否到位
- 适应度计算是否匹配你的优化目标(求最小/最大值)
- 种群迭代过程中的索引操作是否无逻辑错误
内容的提问来源于stack exchange,提问作者ezabil
相关产品推荐
相关产品推荐

