麻雀搜索算法python代码
时间: 2023-11-08 07:03:36 浏览: 183
以下是麻雀搜索算法的Python代码:
```python
import math
def sparrow_search(fitness_func, dim, lb, ub, max_iter, num_sparrows, pa, delta_max):
# 初始化麻雀群体
sparrow_pos = [lb + (ub - lb) * np.random.random(dim) for i in range(num_sparrows)]
sparrow_fitness = [fitness_func(sparrow_pos[i]) for i in range(num_sparrows)]
sparrow_v = np.zeros((num_sparrows, dim))
# 记录最优位置和适应度
best_sparrow_pos = sparrow_pos[np.argmin(sparrow_fitness)]
best_sparrow_fitness = min(sparrow_fitness)
# 迭代寻优
for iter in range(max_iter):
# 更新每个麻雀的速度和位置
for i in range(num_sparrows):
# 计算每个麻雀对最优解的影响力
attract_to_best = pa * np.random.random() * (best_sparrow_pos - sparrow_pos[i])
# 计算每个麻雀之间的相互作用力
interact = np.zeros(dim)
for j in range(num_sparrows):
if i != j:
diff = sparrow_pos[j] - sparrow_pos[i]
dist = np.linalg.norm(diff)
interact += (sparrow_pos[j] - sparrow_pos[i]) * math.exp(-dist) / dist
# 计算每个麻雀的随机扰动项
rand_vec = delta_max * (2 * np.random.random(dim) - 1)
# 更新速度和位置
sparrow_v[i] = sparrow_v[i] + attract_to_best + interact + rand_vec
sparrow_pos[i] = sparrow_pos[i] + sparrow_v[i]
# 限制麻雀位置不超过边界
sparrow_pos[i] = np.clip(sparrow_pos[i], lb, ub)
# 更新最优解
fitness_i = fitness_func(sparrow_pos[i])
if fitness_i < best_sparrow_fitness:
best_sparrow_fitness = fitness_i
best_sparrow_pos = sparrow_pos[i]
return (best_sparrow_pos, best_sparrow_fitness)
```
其中,fitness_func 是适应度函数,dim 是问题维数,lb 和 ub 是问题的边界,max_iter 是最大迭代次数,num_sparrows 是麻雀数量,pa 是吸引因子,delta_max 是扰动范围。
阅读全文