编写Python程序,用PSO算法求解Rastrigin函数,维数为30,目标最优值为100,初值范围为[-5.12,5.12],并且最后打印结果图像
时间: 2024-04-29 19:24:20 浏览: 149
以下是Python程序:
```python
import numpy as np
import matplotlib.pyplot as plt
def rastrigin(x):
n = len(x)
return 10 * n + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
class PSO():
def __init__(self, dim, particle_num, iter_num, target_value, lb, ub):
self.dim = dim
self.particle_num = particle_num
self.iter_num = iter_num
self.target_value = target_value
self.lb = lb
self.ub = ub
self.particles = np.random.uniform(lb, ub, (particle_num, dim))
self.velocities = np.zeros((particle_num, dim))
self.global_best_position = None
self.global_best_value = float('inf')
self.local_best_positions = self.particles.copy()
self.local_best_values = np.array([float('inf')] * particle_num)
def optimize(self):
for i in range(self.iter_num):
for j in range(self.particle_num):
# Update velocity
r1, r2 = np.random.uniform(size=(2, self.dim))
self.velocities[j] = self.velocities[j] + r1 * (self.local_best_positions[j] - self.particles[j]) + r2 * (self.global_best_position - self.particles[j])
# Clip velocity
self.velocities[j] = np.clip(self.velocities[j], self.lb - self.ub, self.ub - self.lb)
# Update position
self.particles[j] = self.particles[j] + self.velocities[j]
# Clip position
self.particles[j] = np.clip(self.particles[j], self.lb, self.ub)
# Evaluate fitness
fitness = rastrigin(self.particles[j])
# Update local best
if fitness < self.local_best_values[j]:
self.local_best_values[j] = fitness
self.local_best_positions[j] = self.particles[j].copy()
# Update global best
if fitness < self.global_best_value:
self.global_best_value = fitness
self.global_best_position = self.particles[j].copy()
# Check termination condition
if self.global_best_value < self.target_value:
break
print('Global best position:', self.global_best_position)
print('Global best value:', self.global_best_value)
# Plot result
x = np.arange(self.lb, self.ub, 0.1)
y = np.arange(self.lb, self.ub, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.zeros(X.shape)
for i in range(X.shape[0]):
for j in range(X.shape[1]):
Z[i, j] = rastrigin(np.array([X[i, j], Y[i, j]]))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.scatter(self.global_best_position[0], self.global_best_position[1], self.global_best_value, c='r', marker='o')
plt.show()
pso = PSO(dim=2, particle_num=100, iter_num=1000, target_value=100, lb=-5.12, ub=5.12)
pso.optimize()
```
程序中定义了一个PSO类,包含了PSO算法的所有步骤,包括初始化、更新速度和位置、求解适应度、更新全局最优解和局部最优解、以及终止条件的检查。程序的主要部分是optimize方法,它执行了一定的迭代次数,每次迭代更新所有粒子的速度和位置,并检查是否满足终止条件。最后,程序绘制了Rastrigin函数的图像,并在图像上标记出全局最优解的位置。
在这个程序中,粒子的维数为2,但可以轻松地修改为30。其他参数可以根据需要进行调整。运行程序后,可以看到输出的全局最优解的位置和值,以及绘制的图像,它显示了Rastrigin函数的形状和全局最优解的位置。
阅读全文