使用Python实现遗传算法

来源:互联网 发布:尼康失真控制数据 编辑:程序博客网 时间:2024/05/16 08:26

我们使用scikit-opt工具箱来实现遗传算法:https://github.com/guofei9987/scikit-opt

下载后,我们只需要其中的ga.py文件

首先,定义一个目标函数

def demo_func2(p):    x, y, z = p    return -(x ** 2 + y ** 2 + z ** 2)

我们想用遗传算法找出目标函数的最大值,这样做:

func是你的目标函数
lb是每个变量搜索的最小界
ub是每个变量搜索区域的最大界

general_best,func_general_best,FitV_history=ga.ga(func=demo_func2,  lb=[-1, -10, -5], ub=[2, 10, 2])print('best_x:',general_best)print('best_y:',func_general_best)ga.plot_FitV(FitV_history)

Figure_1-1

原创粉丝点击