蜣螂优化算法python代码
时间: 2024-10-07 09:00:17 浏览: 139
蜣螂优化算法是一种启发式优化算法,模拟了蜣螂在觅食时的行为,通过不断地搜索来寻找最优解。以下是蜣螂优化算法的Python代码实现。
```
import numpy as np
import random
# 定义目标函数,这里以Rosenbrock函数为例
def rosenbrock(x):
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
# 蜣螂优化算法的实现
def cockroach_swarm_optimization(dim, fobj, bounds, max_iter, population_size, alpha=0.5, beta=1):
# 初始化种群
population = np.random.uniform(bounds, bounds, (population_size, dim))
fitness = np.array([fobj(ind) for ind in population])
best_index = np.argmin(fitness)
global_best_fitness = fitness[best_index]
global_best_solution = population[best_index].copy()
for i in range(max_iter):
# 计算吸引力和斥力
attract_repel_force = np.zeros((population_size, dim))
for j in range(population_size):
attract_force = np.zeros(dim)
repel_force = np.zeros(dim)
for k in range(population_size):
if j == k:
continue
distance = np.linalg.norm(population[j] - population[k])
direction = (population[k] - population[j]) / (distance + 1e-8)
if fitness[j] < fitness[k]:
attract_force += direction * distance
else:
repel_force -= direction / (distance ** 2 + 1e-8)
attract_repel_force[j] = alpha * attract_force + beta * repel_force
# 更新位置和适应度
for j in range(population_size):
population[j] += attract_repel_force[j]
# 边界处理
population[j] = np.clip(population[j], bounds, bounds)
fitness[j] = fobj(population[j])
if fitness[j] < global_best_fitness:
global_best_fitness = fitness[j]
global_best_solution = population[j].copy()
print('Iteration {}: Best Fitness Value = {}'.format(i+1, global_best_fitness))
return global_best_solution, global_best_fitness
# 示例用法
bounds = (-5, 5)
best_solution, best_fitness = cockroach_swarm_optimization(dim=10, fobj=rosenbrock, bounds=bounds,
max_iter=50, population_size=30)
print('Best Solution:', best_solution)
print('Best Fitness:', best_fitness)
```
阅读全文