目录
1 帮助文档
https://scikit-opt.github.io/scikit-opt/#/zh/README
2 安装SCIKIT-OPT
pip install scikit-opt
3 遗传算法算例
3.1 定义问题
#定义问题
import numpy as np
def schaffer(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.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)
3.2 运行遗传算法
from sko.GA import GA
ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, prob_mut=0.001, 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)
文工注:最优解为最小值,若要求最大值,需要在前面加负号
3.3 结果绘制
import pandas as pd
import matplotlib.pyplot as plt
Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
Y_history.min(axis=1).cummin().plot(kind='line')
plt.show()
3.4 算例2
from sko.GA import GA
demo_func = lambda x: (x[0] - 1) ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
ga = GA(func=demo_func, n_dim=3, max_iter=500, lb=[-1, -1, -1], ub=[5, 1, 1], precision=[2, 1, 1e-7])
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
4 参数说明
4.1 输入
入参 | 默认值 | 意义 |
func | - | 目标函数 |
n_dim | - | 目标函数的维度 |
size_pop | 50 | 种群规模 |
max_iter | 200 | 最大迭代次数 |
prob_mut | 0.001 | 变异概率 |
lb | -1 | 每个自变量的最小值 |
ub | 1 | 每个自变量的最大值 |
constraint_eq | 空元组 | 等式约束 |
constraint_ueq | 空元组 | 不等式约束 |
precision | 1e-7 | 精准度,int/float或者它们组成的列表 |
4.2 输出
4.2.1 GA
- ga.generation_best_Y 每一代的最优函数值
- ga.generation_best_X 每一代的最优函数值对应的输入值
- ga.all_history_FitV 每一代的每个个体的适应度
- ga.all_history_Y 每一代每个个体的函数值
- ga.best_y 最优函数值
- ga.best_x 最优函数值对应的输入值