改进的多目标粒子群算法代码
时间: 2023-10-13 16:25:53 浏览: 126
以下是改进的多目标粒子群算法代码,希望能帮到你:
```python
import numpy as np
class MOPSO:
def __init__(self, objective_func, n_particles, n_iterations, w=0.4, c1=1.5, c2=1.5, max_velocity=0.5):
self.objective_func = objective_func
self.n_particles = n_particles
self.n_iterations = n_iterations
self.w = w
self.c1 = c1
self.c2 = c2
self.max_velocity = max_velocity
self.particles = []
self.global_best_position = None
self.global_best_fitness = None
self.fitness_history = []
# Initialize particles' positions and velocities
for i in range(self.n_particles):
particle = Particle()
self.particles.append(particle)
def optimize(self):
for i in range(self.n_iterations):
for particle in self.particles:
# Calculate fitness
fitness = self.objective_func(particle.position)
# Update personal best
if particle.best_fitness is None or fitness < particle.best_fitness:
particle.best_position = particle.position
particle.best_fitness = fitness
# Update global best
if self.global_best_fitness is None or fitness < self.global_best_fitness:
self.global_best_position = particle.position
self.global_best_fitness = fitness
for particle in self.particles:
# Calculate velocity
r1 = np.random.rand(len(particle.velocity))
r2 = np.random.rand(len(particle.velocity))
cognitive_velocity = self.c1 * r1 * (particle.best_position - particle.position)
social_velocity = self.c2 * r2 * (self.global_best_position - particle.position)
new_velocity = self.w * particle.velocity + cognitive_velocity + social_velocity
# Limit velocity
new_velocity[new_velocity > self.max_velocity] = self.max_velocity
new_velocity[new_velocity < -self.max_velocity] = -self.max_velocity
particle.velocity = new_velocity
particle.position += particle.velocity
self.fitness_history.append(self.global_best_fitness)
class Particle:
def __init__(self):
self.position = np.random.rand(2) * 10 - 5
self.velocity = np.random.rand(2) * 2 - 1
self.best_position = self.position
self.best_fitness = None
def objective_func(x):
y1 = x[0]**2 + x[1]**2
y2 = (x[0]-1)**2 + x[1]**2
return np.array([y1, y2])
mopso = MOPSO(objective_func, n_particles=20, n_iterations=100)
mopso.optimize()
import matplotlib.pyplot as plt
plt.plot(mopso.fitness_history)
plt.xlabel('Iteration')
plt.ylabel('Global Best Fitness')
plt.show()
```
在这个代码中,我们实现了一个多目标粒子群算法,并使用两个函数来评估每个粒子的适应度。我们还添加了一些新的参数,例如最大速度和历史适应度记录。这些改进可以使算法更加鲁棒和可靠。
阅读全文