首页 > 解决方案 > 如何使用 SKO.pso python 应用粒子群优化

问题描述

我在 Github 上找到了一个包,里面有各种关于进化的算法。链接如下: https ://github.com/guofei9987/scikit-opt

但是,我在使用该软件包时感到困惑。当我尝试作为示例进行操作时,将昏暗设置为 1,当上限为 10 时将下限设置为零,关注 x 的非负数,得到错误答案,这是我的代码:

def demo_func(x):
    # Sphere
    x1= x
    return ((10-4*x1)/(4*x1+3))*x1
from sko.PSO import PSO
pso = PSO(func=demo_func, n_dim=1, pop=40, max_iter=150, lb=[0], ub=[10], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

import matplotlib.pyplot as plt

plt.plot(pso.gbest_y_hist)
plt.show()

结果如下:结果

best_x 是 [10.] best_y 是 [-6.97674419]

然而,这是一个错误的答案。x 的正确答案在 0.5 到 1 之间。有人有建议吗?

标签: pythonparticle-swarm

解决方案


PSO 优化函数的最小值。添加负号以获得最大值。

def demo_func(x):
    x1,= x
    return -((10-4*x1)/(4*x1+3))*x1
from sko.PSO import PSO
pso = PSO(func=demo_func, n_dim=1, pop=40, max_iter=150, lb=[0], ub=[10], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

import matplotlib.pyplot as plt

plt.plot(pso.gbest_y_hist)
plt.show()

推荐阅读