import numpy as np
class Fish:
def __init__(self, position, step_size):
self.position = position
self.step_size = step_size
# 适应度函数,这里假设需要最小化的目标函数是 f(x) = x^2
def fitness_function(x):
return x**2
def artificial_fish_swarm(n, max_iterations, visual_range, step_size, hunger_rate):
# 初始化鱼群
fish_list = []
for _ in range(n):
position = np.random.uniform(-10, 10) # 随机初始化位置
fish_list.append(Fish(position, step_size))
# 迭代搜索
for _ in range(max_iterations):
for fish in fish_list:
# 个体行为:移动到更优的位置
new_position = fish.position + np.random.uniform(-fish.step_size, fish.step_size)
new_position_fitness = fitness_function(new_position)
if new_position_fitness < fitness_function(fish.position):
fish.position = new_position
# 集体行为:寻找更优的位置
neighbors = [f for f in fish_list if abs(f.position - fish.position) <= visual_range]
if neighbors:
best_neighbor = min(neighbors, key=lambda f: fitness_function(f.position))
if fitness_function(best_neighbor.position) < fitness_function(fish.position):
new_position = fish.position + np.random.uniform(-fish.step_size, fish.step_size)
new_position_fitness = fitness_function(new_position)
if new_position_fitness < fitness_function(fish.position):
fish.position = new_position
# 饥饿行为:减小步长
fish.step_size *= (1 - hunger_rate)
# 返回最优解
best_fish = min(fish_list, key=lambda f: fitness_function(f.position))
return best_fish.position
# 测试
best_position = artificial_fish_swarm(n=50, max_iterations=100, visual_range=2, step_size=1, hunger_rate=0.2)
best_fitness = fitness_function(best_position)
print(f"Best position: {best_position}")
print(f"Best fitness: {best_fitness}")
本文仅为学习记录,如有错误欢迎指出。