用python 写出相关算法
时间: 2023-08-15 15:40:31 浏览: 79
python实现识别手写数字 python图像识别算法
以下是使用Python实现PSO算法的示例代码:
```python
import random
class Particle:
def __init__(self, dim, max_pos, min_pos):
self.position = [random.uniform(min_pos, max_pos) for _ in range(dim)]
self.velocity = [0 for _ in range(dim)]
self.best_position = self.position[:]
self.best_fitness = float('inf')
self.fitness = float('inf')
def update_fitness(self, fitness_func):
self.fitness = fitness_func(self.position)
if self.fitness < self.best_fitness:
self.best_fitness = self.fitness
self.best_position = self.position[:]
class PSO:
def __init__(self, dim, size, max_pos, min_pos, fitness_func, max_iter=100, c1=2, c2=2, w=0.7):
self.dim = dim
self.size = size
self.max_pos = max_pos
self.min_pos = min_pos
self.fitness_func = fitness_func
self.max_iter = max_iter
self.c1 = c1
self.c2 = c2
self.w = w
self.global_best_position = [random.uniform(min_pos, max_pos) for _ in range(dim)]
self.global_best_fitness = float('inf')
self.particles = [Particle(dim, max_pos, min_pos) for _ in range(size)]
def update_global_best(self):
for particle in self.particles:
if particle.best_fitness < self.global_best_fitness:
self.global_best_fitness = particle.best_fitness
self.global_best_position = particle.best_position[:]
def update_particles(self):
for particle in self.particles:
for i in range(self.dim):
r1 = random.random()
r2 = random.random()
new_velocity = (self.w * particle.velocity[i] +
self.c1 * r1 * (particle.best_position[i] - particle.position[i]) +
self.c2 * r2 * (self.global_best_position[i] - particle.position[i]))
particle.velocity[i] = new_velocity
new_position = particle.position[i] + new_velocity
if new_position > self.max_pos:
new_position = self.max_pos
elif new_position < self.min_pos:
new_position = self.min_pos
particle.position[i] = new_position
particle.update_fitness(self.fitness_func)
def run(self):
for i in range(self.max_iter):
self.update_particles()
self.update_global_best()
print('Iteration {}: Best fitness = {}'.format(i, self.global_best_fitness))
if __name__ == '__main__':
def sphere(x):
return sum([xi ** 2 for xi in x])
pso = PSO(dim=2, size=20, max_pos=100, min_pos=-100, fitness_func=sphere, max_iter=50)
pso.run()
```
以上代码是一个简单的PSO算法实现,适用于求解连续优化问题。其中,Particle类表示粒子,包含位置、速度、适应度值等属性,以及更新自身适应度值、最优位置和最优适应度值的方法。PSO类表示整个算法,包含粒子群、全局最优解、算法参数等属性,以及更新全局最优解和粒子位置、速度的方法。在主函数中,定义了一个简单的测试函数sphere,并使用PSO算法求解该函数的最小值。
阅读全文