粒子群最佳化演算法python
粒子群最佳化(Particle Swarm Optimization,PSO)是一種基於群體智慧型的最佳化算法,用於尋找最佳化問題的全局最優解。以下是一個簡單的粒子群最佳化算法的Python實現示例:
import numpy as np
class Particle:
def __init__(self, dim, minx, maxx):
self.position = np.random.uniform(low=minx, high=maxx, size=dim)
self.velocity = np.random.uniform(low=-0.1, high=0.1, size=dim)
self.best_position = self.position.copy()
self.best_score = np.inf
def update_velocity(self, global_best, w=0.5, c1=1, c2=2):
r1 = np.random.rand(self.position.shape[0])
r2 = np.random.rand(self.position.shape[0])
updated_velocity = w * self.velocity + c1 * r1 * (global_best - self.position) + c2 * r2 * (self.best_position - self.position)
return updated_velocity
def update_position(self, global_best):
self.position = self.position + self.update_velocity(global_best)
return self.position
class PSO:
def __init__(self, dim, n_particles, minx, maxx, n_iterations):
self.dim = dim
self.n_particles = n_particles
self.minx = minx
self.maxx = maxx
self.n_iterations = n_iterations
self.particles = [Particle(dim, minx, maxx) for _ in range(n_particles)]
self.global_best = np.random.uniform(low=minx, high=maxx, size=dim)
self.initialize_global_best()
def initialize_global_best(self):
for particle in self.particles:
particle.best_score = float('inf')
for i in range(self.dim):
if particle.position[i] < particle.best_score:
particle.best_score = particle.position[i]
particle.best_position = particle.position.copy()
self.global_best = np.array([np.mean(p.best_position) for p in self.particles])
def optimize(self):
for i in range(self.n_iterations):
for particle in self.particles:
particle.update_position(self.global_best)
new_score = particle.get_fitness()
if new_score < particle.best_score:
particle.best_score = new_score
particle.update_velocity(self.global_best)
particle.update_position(particle.best_position)
self._update_global_best()
return self._get_global_best()
def _update_global_best(self):
for particle in self.particles:
if particle.best_score < float('inf'):
new_global_best = np.array([np.mean([particle.position, particle.best_position])])
if new_global_best < self._get_global_best():
self._global_best = new_global_best
else:
for p in self.particles:
p._global_best = p._best_position[np._where(_ <= self._global_best)[0]] # Here I used `np._where` instead of `numpy`'s `where` because I think it is clearer in this context that we are getting a tuple of indices to sort and get the last element from each of these tuples in a single loop
```這個實現包含了基本的粒子群最佳化算法的主要部分,包括粒子類(`Particle`)和最佳化類(`PSO`)。`Particle`類表示一個最佳化問題的解,包含粒子位置、速度、最佳位置和最佳得分等屬性。`PSO`類包含粒子列表、全局最佳位置和初始最佳位置等屬性,並提供了一些用於更新粒子和全局最佳位置的方法。在最佳化過程中,每個粒子會根據其自身的最佳位置和全局最佳位置來更新其位置和速度。在每一輪疊代結束後,全局最佳位置會被更新為當前所有