用遗传算法求函数最大值(python)
step1.可视化函数(pyecharts)
step2.求函数的最大值(遗传算法)
1: 可视化函数
没有安装pyecharts的先打开命令行输入下列命令:
pip install pyecharts
把官方文档https://pyecharts.org里的demo拿来修改一下即可:
实际上需要我们编写的只有create_data()这个函数!
代码如下:
import numpy as np
import pyecharts.options as opts
from pyecharts.charts import Surface3D
# -----------------绘制图像---------------------
# 获取绘制图像的数据
def create_data():
data = []
for i in np.arange(-10, 10, 0.1):
for j in np.arange(-10, 10, 0.1):
x = i
y = j
z = 0.5 - (np.sin(np.sqrt(x**2+y**2))**2 - 0.5) / (1 + 0.001*(x**2 + y**2)**2)
data.append([x, y, z])
# 没有下行的代码会无法显示
data = [[item[1], item[0], item[2]] for item in data]
return data
# 使用pyecharts绘制图像
def draw():
(
# Surface3D(init_opts=opts.InitOpts(width="1600px", height="800px"))
Surface3D()
.add(
series_name="f(x,y)",
shading="color",
data=list(create_data()),
xaxis3d_opts=opts.Axis3DOpts(type_="value"),
yaxis3d_opts=opts.Axis3DOpts(type_="value"),
grid3d_opts=opts.Grid3DOpts(width=100, height=40, depth=100),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="z=f(x,y)"),
visualmap_opts=opts.VisualMapOpts(
dimension=2,
max_=1,
min_=-1,
range_color=[