如何使用sko PSO 包进行粒子群算法优化(python,PSO )

如何使用sko PSO 包进行粒子群算法优化(python,PSO )

问题描述:

我想使用这个包进行单目标优化:

https://github.com/guofei9987/scikit-opt

目标函数为 y=((10-4x)/(4x+3))*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 is  [10.] best_y is [-6.97674419]

事实上这是个错误的答案, 因为通过函数图像我们可以看到正确的答案位于0.5和1之间。

想求教各位大佬想要获得 正确的 答案y应该怎么写

这个是求最小值,所以程序结果没问题。你说的0.5-1 之间,应该是求最大值把。如果你要最大值,可以加个负号。

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()

这是结果: