概率思想加相互通信比较加一小步一小步迭代
粒子群算法最终实现代码
import numpy as np
import matplotlib.pyplot as plt
# 定义目标函数
def objective_function(x):
return x[0]**2 + x[1]**2 # 简单的二次函数
# 粒子类
class Particle:
def __init__(self, dimensions):
self.position = np.random.rand(dimensions) * 20 - 10
self.velocity = np.random.rand(dimensions) - 0.5
self.best_position = self.position.copy()
self.best_value = objective_function(self.position)
def update_velocity(self, global_best_position, inertia_weight, cognitive_weight, social_weight):
cognitive_component = cognitive_weight * np.random.rand() * (self.best_position - self.position)
social_component = social_weight * np.random.rand() * (global_best_position - self.position)
self.velocity = inertia_weight * self.velocity + cognitive_component + social_component
def update_position(self, bounds):
self.position += self.velocity
self.position = np.clip(self.position, bounds[0], bounds[1])
current_value = objective_function(self.position)
if current_value < self.best_value:
self.best_value = current_value
self.best_position = self.position.copy()
# PSO算法
def pso(objective_function, dimensions, num_particles, bounds, num_iterations):
inertia_weight = 0.7
cognitive_weight = 1.5
social_weight = 1.5
particles = [Particle(dimensions) for _ in range(num_particles)]
global_best_position = particles[0].position
global_best_value = objective_function(global_best_position)
fig, ax = plt.subplots()
for iteration in range(num_iterations):
for particle in particles:
particle.update_velocity(global_best_position, inertia_weight, cognitive_weight, social_weight)
particle.update_position(bounds)
if particle.best_value < global_best_value:
global_best_value = particle.best_value
global_best_position = particle.best_position
ax.clear()
ax.set_xlim(bounds)
ax.set_ylim(bounds)
ax.set_title(f"Iteration {iteration + 1}/{num_iterations}")
ax.set_xlabel("x0")
ax.set_ylabel("x1")
positions = np.array([particle.position for particle in particles])
ax.scatter(positions[:, 0], positions[:, 1], color='blue')
ax.scatter(global_best_position[0], global_best_position[1], color='red', marker='*', s=100)
plt.pause(0.1)
plt.show()
return global_best_position, global_best_value
# 参数设置
dimensions = 2
num_particles = 100
bounds = (-10, 10)
num_iterations = 36
best_position, best_value = pso(objective_function, dimensions, num_particles, bounds, num_iterations)
print(f"Best Position: {best_position}")
print(f"Best Value: {best_value}")