鲸鱼优化算法python
时间: 2023-09-16 09:14:51 浏览: 85
鲸鱼优化算法是一种启发式优化算法,它模拟了鲸鱼的迁徙行为来寻找最优解。以下是使用Python实现鲸鱼优化算法的示例代码:
```python
import random
import math
# 定义目标函数
def func(x):
return math.sin(10 * x) * x + math.cos(2 * x) * x
# 初始化种群
def init_population(pop_size, x_min, x_max):
population = []
for i in range(pop_size):
x = random.uniform(x_min, x_max)
population.append(x)
return population
# 计算适应度值
def fitness(x):
return func(x)
# 鲸鱼优化算法
def WOA(pop_size, max_iter, x_min, x_max):
# 初始化种群
population = init_population(pop_size, x_min, x_max)
# 迭代寻优
for t in range(max_iter):
a = 2 - 2 * t / max_iter # 更新参数a
# 遍历每个个体
for i in range(pop_size):
# 随机选择两个个体
r1 = random.randint(0, pop_size - 1)
r2 = random.randint(0, pop_size - 1)
# 计算距离
A = 2 * a * random.random() - a
C = 2 * random.random()
l = random.uniform(-1, 1)
p = random.random()
D = abs(C * population[r1] - population[r2])
X1 = population[r1] - A * D
if p < 0.5:
if abs(A) >= 1:
Xnew = X1 - l * D
else:
Xnew = population[i] - A * D
else:
X2 = population[i] - A * D
if fitness(X2) < fitness(population[i]):
Xnew = X2
else:
Xnew = X1 - l * D
# 边界处理
if Xnew < x_min:
Xnew = x_min
elif Xnew > x_max:
Xnew = x_max
# 更新个体
population[i] = Xnew
# 返回最优解
best_x = population[0]
best_fitness = fitness(population[0])
for i in range(1, pop_size):
if fitness(population[i]) < best_fitness:
best_x = population[i]
best_fitness = fitness(population[i])
return best_x, best_fitness
# 示例
x_min = -5
x_max = 5
pop_size = 30
max_iter = 100
best_x, best_fitness = WOA(pop_size, max_iter, x_min, x_max)
print("Best solution: x = %.4f, f(x) = %.4f" % (best_x, best_fitness))
```
在示例中,我们定义了目标函数`func()`,并使用`init_population()`初始化种群。然后,我们使用`WOA()`函数实现鲸鱼优化算法,并返回最优解。最后,我们输出最优解的结果。可以根据实际需求调整参数值。
阅读全文