粒子群算法拟合曲线python代码
时间: 2023-08-31 10:12:52 浏览: 121
好的,关于粒子群算法拟合曲线的Python代码,我可以提供以下示例代码:
```
import numpy as np
import matplotlib.pyplot as plt
# 定义适应度函数
def fitness(x):
return np.sin(x) / x
# 计算粒子群的适应度值
def pso(positions):
# 初始化粒子位置和速度
w = 0.7 # 惯性因子
c1 = 1.5 # 学习因子
c2 = 1.5
n_particles = positions.shape[0]
position = np.copy(positions)
velocity = np.zeros_like(position)
pbest_position = np.copy(position)
pbest_fitness = np.zeros(n_particles)
for i in range(n_particles):
fitness_value = fitness(position[i])
pbest_fitness[i] = fitness_value
gbest_fitness = np.max(pbest_fitness)
gbest_position = np.copy(pbest_position[np.argmax(pbest_fitness), :])
error = 1e-6 # 终止条件
while gbest_fitness > error:
# 更新速度和位置
for i in range(n_particles):
r1 = np.random.rand(position.shape[1])
r2 = np.random.rand(position.shape[1])
velocity[i, :] = w * velocity[i, :] + \
c1 * r1 * (pbest_position[i, :] - position[i, :]) + \
c2 * r2 * (gbest_position - position[i, :])
position[i, :] = position[i, :] + velocity[i, :]
# 边界处理
position[i, position[i, :] < -10] = -10
position[i, position[i, :] > 10] = 10
# 更新粒子的历史最佳位置和适应度
fitness_value = fitness(position[i, :])
if fitness_value > pbest_fitness[i]:
pbest_fitness[i] = fitness_value
pbest_position[i, :] = position[i, :]
# 更新群体最佳位置
if np.max(pbest_fitness) > gbest_fitness:
gbest_fitness = np.max(pbest_fitness)
gbest_position = np.copy(pbest_position[np.argmax(pbest_fitness), :])
return gbest_fitness, gbest_position
particles = np.random.uniform(-10, 10, (100, 1))
fitness_value, position = pso(particles)
plt.plot(np.linspace(-10, 10, 100), fitness(np.linspace(-10, 10, 100)), label='sin(x) / x')
plt.plot(position, fitness(position), 'ro', label='PSO')
plt.legend()
plt.show()
```
以上代码是一个简单的粒子群算法拟合曲线的示例代码,代码中包含对适应度函数的定义、粒子群的初始化、速度和位置的更新、边界处理、以及群体最佳位置的更新等实现。需要注意的是,这里的适应度函数是 sin(x)/x,你可以根据具体需求修改适应度函数的定义。
阅读全文