人工鱼群算法的python代码
时间: 2024-09-25 17:00:22 浏览: 39
人工鱼群算法(Artificial Fish Swarm Optimization, AFSO)是一种模拟生物社会群体行为的优化算法,常用于解决复杂的全局优化问题。Python语言因其简洁性和丰富的库支持,非常适合实现此类算法。以下是一个简单的二维空间的人工鱼群搜索过程的Python代码示例:
```python
import numpy as np
class Particle:
def __init__(self, position, velocity, best_position):
self.position = position
self.velocity = velocity
self.best_position = best_position
class PSO:
def __init__(self, n_particles, search_space, max_iter, omega=0.7, c1=2, c2=2):
self.particles = [Particle(np.random.uniform(search_space[0], search_space[1]), np.zeros(2), np.inf*np.ones(2)) for _ in range(n_particles)]
self.search_space = search_space
self.max_iter = max_iter
self.c1, self.c2 = c1, c2
self.w = omega
def update(self):
r1, r2 = np.random.rand(), np.random.rand() # 随机数
for particle in self.particles:
vel_new = self.w * particle.velocity + self.c1 * r1 * (particle.best_position - particle.position) + self.c2 * r2 * (self.global_best_position - particle.position)
pos_new = particle.position + vel_new
if pos_new[0] < self.search_space[0] or pos_new[0] > self.search_space[1]:
vel_new[0] = -vel_new[0]
if pos_new[1] < self.search_space[0] or pos_new[1] > self.search_space[1]:
vel_new[1] = -vel_new[1]
particle.position, particle.velocity = pos_new, vel_new
if fitness(pos_new) < fitness(particle.best_position): # 更新个体最优解
particle.best_position = pos_new
if fitness(pos_new) < fitness(self.global_best_position): # 更新全局最优解
self.global_best_position = pos_new
def fitness(position):
# 这里应替换为你要优化的实际函数
return position[0]**2 + position[1]**2 # 示例:计算位置到原点的距离平方
# 主程序
pso = PSO(50, (0, 100), 100)
for i in range(pso.max_iter):
pso.update()
print(f"Iteration {i+1}: Best Position: {pso.global_best_position}")
阅读全文