狼群算法python代码
时间: 2023-09-24 15:09:56 浏览: 222
以下是狼群算法的 Python 代码实现:
```python
import random
import math
# 目标函数
def objective_function(x):
return sum([i ** 2 for i in x])
# 初始化狼群
def initialize(num_dimensions, num_wolves):
wolves = []
for i in range(num_wolves):
wolf = [random.uniform(-100, 100) for _ in range(num_dimensions)]
wolves.append(wolf)
return wolves
# 计算适应度
def calculate_fitness(position):
return objective_function(position)
# 找到最优狼
def get_alpha(wolves):
alpha_fitness = float("inf")
for wolf in wolves:
fitness = calculate_fitness(wolf)
if fitness < alpha_fitness:
alpha_fitness = fitness
alpha = wolf
return alpha
# 找到次优狼
def get_beta(wolves, alpha):
beta_fitness = float("inf")
for wolf in wolves:
fitness = calculate_fitness(wolf)
if fitness < beta_fitness and wolf != alpha:
beta_fitness = fitness
beta = wolf
return beta
# 找到最劣狼
def get_delta(wolves, alpha, beta):
delta_fitness = float("inf")
for wolf in wolves:
fitness = calculate_fitness(wolf)
if fitness < delta_fitness and wolf != alpha and wolf != beta:
delta_fitness = fitness
delta = wolf
return delta
# 更新狼的位置
def update_position(wolf, alpha, beta, delta, a, c):
for i in range(len(wolf)):
x = wolf[i]
r1 = random.random()
r2 = random.random()
A = 2 * a * r1 - a
C = 2 * c * r2 - c
D_alpha = abs(C * alpha[i] - x)
D_beta = abs(C * beta[i] - x)
D_delta = abs(C * delta[i] - x)
X1 = alpha[i] - A * D_alpha
X2 = beta[i] - A * D_beta
X3 = delta[i] - A * D_delta
wolf[i] = (X1 + X2 + X3) / 3
return wolf
# 狼群算法
def wolf_pack_algorithm(num_dimensions, num_wolves, num_iterations, a=1.5, c=1):
wolves = initialize(num_dimensions, num_wolves)
alpha = get_alpha(wolves)
beta = get_beta(wolves, alpha)
delta = get_delta(wolves, alpha, beta)
for j in range(num_iterations):
for i in range(num_wolves):
wolf = wolves[i]
wolf = update_position(wolf, alpha, beta, delta, a, c)
wolves[i] = wolf
alpha = get_alpha(wolves)
beta = get_beta(wolves, alpha)
delta = get_delta(wolves, alpha, beta)
return alpha
```
使用示例:
```python
num_dimensions = 2
num_wolves = 10
num_iterations = 100
best_solution = wolf_pack_algorithm(num_dimensions, num_wolves, num_iterations)
print("Best solution:", best_solution)
print("Objective function value:", objective_function(best_solution))
```
注意事项:
- 参数 `num_dimensions` 表示目标函数的自变量个数,这里默认为 2。
- 参数 `num_wolves` 表示狼群的大小,这里默认为 10。
- 参数 `num_iterations` 表示迭代次数,这里默认为 100。
- 参数 `a` 和 `c` 是算法中的两个常数,它们的默认值分别为 1.5 和 1。如果需要调整算法的收敛速度和精度,可以尝试修改这两个参数。
阅读全文