粒子群最佳化 PSO
import random, math
def pso(objective, bounds, n_particles=30, iterations=100):
dim = len(bounds)
particles = [[random.uniform(b[0], b[1]) for b in bounds] for _ in range(n_particles)]
velocity = [[0]*dim for _ in range(n_particles)]
pbest = [p[:] for p in particles]
pbest_val = [objective(p) for p in particles]
gbest = min(pbest, key=lambda p: objective(p))
gbest_val = objective(gbest)
w, c1, c2 = 0.7, 1.5, 1.5
for _ in range(iterations):
for i in range(n_particles):
for d in range(dim):
r1, r2 = random.random(), random.random()
velocity[i][d] = (w * velocity[i][d]
+ c1 * r1 * (pbest[i][d] - particles[i][d])
+ c2 * r2 * (gbest[d] - particles[i][d]))
particles[i][d] += velocity[i][d]
particles[i][d] = max(bounds[d][0], min(bounds[d][1], particles[i][d]))
val = objective(particles[i])
if val < pbest_val[i]:
pbest[i] = particles[i][:]
pbest_val[i] = val
if val < gbest_val:
gbest = particles[i][:]
gbest_val = val
return gbest, gbest_val
def sphere(x):
return sum(v*v for v in x)
best, val = pso(sphere, [(-10,10)]*3)
print(f"PSO 找到: {best}, f(x)={val:.6f}")