安装
pip install scikit-opt
对于当前的开发者版本:
git clone git@github.com:guofei9987/scikit-opt.git
cd scikit-opt
pipinstall .
Genetic Algorithm
第一步:定义你的问题
importnumpy as npdefschaffer(p):'''This function has plenty of local minimum, with strong shocks
global minimum at (0,0) with value 0'''x1, x2=p
x= np.square(x1) +np.square(x2)return 0.5 + (np.sin(x) - 0.5) / np.square(1 + 0.001 * x)
第二步:运行遗传算法
from sko.GA importGA
#2个变量,每代取50个,800次迭代,上下界及精度
ga= GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, lb=[-1, -1], ub=[1, 1], precision=1e-7)
best_x, best_y=ga.run()print('best_x:', best_x, '\n', 'best_y:', best_y)
第三步:画出结果
importpandas as pdimportmatplotlib.py