鲸鱼算法python实例
时间: 2023-08-12 18:06:23 浏览: 126
当然,我可以为您提供一个简单的鲸鱼算法的 Python 示例。鲸鱼算法是一种启发式优化算法,受到鲸鱼迁徙行为的启发。以下是一个简单的实现示例:
```python
import random
import math
# 定义问题的目标函数,这里以 Rosenbrock 函数为例
def objective_function(x, y):
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
# 定义鲸鱼算法主函数
def whale_algorithm(iterations, population_size, search_space):
population = []
best_solution = None
best_fitness = float('inf')
# 初始化种群
for _ in range(population_size):
x = random.uniform(search_space[0], search_space[1])
y = random.uniform(search_space[0], search_space[1])
solution = [x, y]
fitness = objective_function(x, y)
population.append((solution, fitness))
# 更新最优解
if fitness < best_fitness:
best_solution = solution
best_fitness = fitness
# 开始迭代
for _ in range(iterations):
a = 2 - 2 * (_ / iterations) # 更新 a 值
for i in range(population_size):
x, y = population[i][0]
# 随机选择一条路径
r1 = random.random()
r2 = random.random()
A = 2 * a * r1 - a
C = 2 * r2
# 更新位置
D = abs(C * best_solution[0] - x)
new_x = best_solution[0] - A * D
r1 = random.random()
r2 = random.random()
A = 2 * a * r1 - a
C = 2 * r2
D = abs(C * best_solution[1] - y)
new_y = best_solution[1] - A * D
# 边界处理
new_x = max(search_space[0], min(new_x, search_space[1]))
new_y = max(search_space[0], min(new_y, search_space[1]))
# 计算适应度
new_fitness = objective_function(new_x, new_y)
# 更新最优解
if new_fitness < best_fitness:
best_solution = [new_x, new_y]
best_fitness = new_fitness
# 更新种群
population[i] = ([new_x, new_y], new_fitness)
return best_solution, best_fitness
# 测试鲸鱼算法
iterations = 100 # 迭代次数
population_size = 50 # 种群大小
search_space = (-5, 5) # 搜索空间范围
best_solution, best_fitness = whale_algorithm(iterations, population_size, search_space)
print("Best solution:", best_solution)
print("Best fitness:", best_fitness)
```
这个示例中,我们使用 Rosenbrock 函数作为目标函数。您可以按照自己的需求修改目标函数和搜索空间。祝您成功使用鲸鱼算法进行优化!
阅读全文