来源:数字中国
本文约300字,建议阅读3分钟
附安装pip指令及示例代码。
This library encapsulates the Genetic Algorithm (GA), Particle Swarm Algorithm (PSO), Ant Colony Algorithm (ACA), Simulated Annealing Algorithm (SA), Immune Optimization Algorithm (IA), Artificial Fish Swarm Algorithm (AFSA).
Open source address:
https://github.com/guofei9987/scikit-opt
After installing Python, enter the following command on the command line to install:
pip install scikit-opt
Particle swarm algorithm as an example
First step, define the problem
-> Demo code: examples/demo_pso.py#s1
def demo_func(x):
x1, x2, x3 = x
return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
The second step is to do particle swarm algorithm
-> Demo code: examples/demo_pso.py#s2
from sko.PSO import PSO
pso = PSO(func=demo_func, n_dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
The third step, draw the result
-> Demo code: examples/demo_pso.py#s3
import matplotlib.pyplot as plt
plt.plot(pso.gbest_y_hist)
plt.show()
Editor: Huang Jiyan