基于scikit-optimize库中的GA遗传算法的Python代码示例:
时间: 2024-03-28 15:15:13 浏览: 21
很高兴能为您提供帮助,以下是一个基于scikit-optimize库中的GA遗传算法的Python代码示例:
```
from skopt import gp_minimize
from skopt.space import Real
from skopt.utils import use_named_args
from skopt.plots import plot_convergence
import numpy as np
import matplotlib.pyplot as plt
# define function to minimize
def f(x):
return (x[0]**2 + x[1]**2) / 25.0 - np.cos(x[0]) * np.cos(x[1]/np.sqrt(2))
# define search space
space = [Real(-10, 10, name='x'), Real(-10, 10, name='y')]
# define optimization function
@use_named_args(space)
def objective(**params):
return f([params['x'], params['y']])
# run optimization
res_gp = gp_minimize(objective, space, n_calls=100, n_random_starts=5, random_state=42)
# print results
print("Best score=%.4f" % res_gp.fun)
print("Best parameters: x=%.4f, y=%.4f" % (res_gp.x[0], res_gp.x[1]))
# plot convergence
plot_convergence(res_gp)
plt.show()
```
这段代码使用了GA遗传算法来优化一个二元函数,搜索空间为x和y,取值范围为-10到10之间,输出结果为最优解下的目标函数值和最优解点的坐标。同时,还画出了迭代过程中目标函数值与迭代轮数之间的关系图。