scikit-opt的使用

一个封装了7种启发式算法的 Python 代码库
(差分进化算法、遗传算法、粒子群算法、模拟退火算法、蚁群算法、鱼群算法、免疫优化算法)

0.安装

pip install scikit-opt

或者直接把源代码中的 sko 文件夹下载下来放本地也调用可以


1.差分进化算法(DE)

(Differential Evolution Algorithm,DE)

参数说明

入参 默认值 意义
func - 目标函数
n_dim - 目标函数的维度
size_pop 50 种群规模
max_iter 200 最大迭代次数
prob_mut 0.001 变异概率
F 0.5 变异系数
lb -1 每个自变量的最小值
ub 1 每个自变量的最大值
constraint_eq 空元组 等式约束
constraint_ueq 空元组 不等式约束(<=0)
'''
min f(x1, x2, x3) = x1^2 + x2^2 + x3^2
s.t.x1*x2 >= 1x1*x2 <= 5x2 + x3 = 10 <= x1, x2, x3 <= 5
'''def obj_func(p):x1, x2, x3 = preturn x1 ** 2 + x2 ** 2 + x3 ** 2constraint_eq = [lambda x: 1 - x[1] - x[2]
]constraint_ueq = [lambda x: 1 - x[0] * x[1],lambda x: x[0] * x[1] - 5
]# %% Do DifferentialEvolution
from sko.DE import DEde = DE(func=obj_func, n_dim=3, size_pop=50, max_iter=800, lb=[0, 0, 0], ub=[5, 5, 5],constraint_eq=constraint_eq, constraint_ueq=constraint_ueq)best_x, best_y = de.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

结果

best_x: [1.02276678 0.9785311  0.02146889] best_y: [2.00403592]

2.粒子群算法(PSO)

def demo_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2# %% Do PSO
from sko.PSO import PSOpso = PSO(func=demo_func, n_dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)# %% Plot the result
import matplotlib.pyplot as pltplt.plot(pso.gbest_y_hist)
plt.show()
best_x is  [0.   0.05 0.5 ] best_y is [0.25]


3.模拟退火(SA)

demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2# %% Do SA
from sko.SA import SAsa = SA(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, L=300, max_stay_counter=150)
best_x, best_y = sa.run()
print('best_x:', best_x, 'best_y', best_y)# %% Plot the result
import matplotlib.pyplot as plt
import pandas as pdplt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))
plt.show()# %%
from sko.SA import SAFastsa_fast = SAFast(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150)
sa_fast.run()
print('Fast Simulated Annealing: best_x is ', sa_fast.best_x, 'best_y is ', sa_fast.best_y)# %%
from sko.SA import SAFastsa_fast = SAFast(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150,lb=[-1, 1, -1], ub=[2, 3, 4])
sa_fast.run()
print('Fast Simulated Annealing with bounds: best_x is ', sa_fast.best_x, 'best_y is ', sa_fast.best_y)# %%
from sko.SA import SABoltzmannsa_boltzmann = SABoltzmann(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150)
sa_boltzmann.run()
print('Boltzmann Simulated Annealing: best_x is ', sa_boltzmann.best_x, 'best_y is ', sa_fast.best_y)# %%
from sko.SA import SABoltzmannsa_boltzmann = SABoltzmann(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150,lb=-1, ub=[2, 3, 4])
sa_boltzmann.run()
print('Boltzmann Simulated Annealing with bounds: best_x is ', sa_boltzmann.best_x, 'best_y is ', sa_fast.best_y)# %%
from sko.SA import SACauchysa_cauchy = SACauchy(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150)
sa_cauchy.run()
print('Cauchy Simulated Annealing: best_x is ', sa_cauchy.best_x, 'best_y is ', sa_cauchy.best_y)# %%
from sko.SA import SACauchysa_cauchy = SACauchy(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, q=0.99, L=300, max_stay_counter=150,lb=[-1, 1, -1], ub=[2, 3, 4])
sa_cauchy.run()
print('Cauchy Simulated Annealing with bounds: best_x is ', sa_cauchy.best_x, 'best_y is ', sa_cauchy.best_y)

参数说明


4.蚁群算法(ACA)

import numpy as np
from scipy import spatial
import pandas as pd
import matplotlib.pyplot as pltnum_points = 25points_coordinate = np.random.rand(num_points, 2)  # generate coordinate of points
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')def cal_total_distance(routine):num_points, = routine.shapereturn sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])# %% Do ACA
from sko.ACA import ACA_TSPaca = ACA_TSP(func=cal_total_distance, n_dim=num_points,size_pop=50, max_iter=200,distance_matrix=distance_matrix)best_x, best_y = aca.run()# %% Plot
fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_x, [best_x[0]]])
print(best_x)  # 结果序列
print(best_points_)  # 添加起点形成环
best_points_coordinate = points_coordinate[best_points_, :]  # 找到点序列对应的坐标序列
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')  # 连接
pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1])
plt.show()


5.遗传算法(GA)

import numpy as npdef schaffer(p):'''This function has plenty of local minimum, with strong shocksglobal minimum at (0,0) with value 0https://en.wikipedia.org/wiki/Test_functions_for_optimization'''x1, x2 = ppart1 = np.square(x1) - np.square(x2)part2 = np.square(x1) + np.square(x2)return 0.5 + (np.square(np.sin(part1)) - 0.5) / np.square(1 + 0.001 * part2)# %%
from sko.GA import GAga = 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)
# %% Plot the result
import pandas as pd
import matplotlib.pyplot as pltY_history = pd.DataFrame(ga.all_history_Y)
print(Y_history)
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()

结果

best_x: [0.00294498 0.00016674] best_y: [8.77542544e-09]0             1   ...            48            49
0    2.432570e-01  8.702831e-02  ...  3.420108e-04  1.928273e-02
1    6.365298e-02  4.969987e-02  ...  1.994070e-02  3.016882e-02
2    8.110868e-04  5.950608e-04  ...  1.694919e-03  2.924401e-02
3    9.968317e-04  1.167487e-04  ...  1.288323e-03  2.983435e-04
4    2.318954e-03  2.191508e-04  ...  1.501895e-04  1.733578e-03
..            ...           ...  ...           ...           ...
795  9.406647e-09  8.849707e-09  ...  9.312904e-09  9.406647e-09
796  8.849707e-09  8.849707e-09  ...  8.830077e-09  8.849707e-09
797  8.849707e-09  8.849707e-09  ...  8.849707e-09  8.849707e-09
798  8.830077e-09  8.849707e-09  ...  8.849707e-09  8.849707e-09
799  8.830077e-09  8.849707e-09  ...  8.958900e-09  8.849707e-09[800 rows x 50 columns]

scikit-opt的使用相关推荐

  1. 【转载】Linux 软件安装到 /usr,/usr/local/ 还是 /opt 目录?

    Linux 的软件安装目录是也是有讲究的,理解这一点,在对系统管理是有益的 /usr:系统级的目录,可以理解为C:/Windows/ /usr/lib:理解为C:/Windows/System32. ...

  2. opt eclipse jre bin java_Linux下安装JDK和Eclipse的配置方法

    一.安装Java开发环境 1,jdk-6u33-linux-i586.bin,下载后原目录为:/home/Downloads/ 2.将下载的文件放置到你需要得地方,这里我放在 cp jdk-6u33- ...

  3. 教你在Python中用Scikit生成测试数据集(附代码、学习资料)

    原文标题:How to Generate Test Datasets in Python with Scikit-learn 作者:Jason Brownlee 翻译:笪洁琼 校对:顾佳妮 本文共17 ...

  4. MySQL库目录下db.opt文件的作用

    细心的朋友可能会发现有时候在某些库目录下有个 db.opt 文件,那这个文件是干什么用的呢?如果你用vi等编辑器打开看的话,内容很简单,是用来记录该库的默认字符集编码和字符集排序规则用的.也就是说如果 ...

  5. Scikit Learn: 在python中机器学习

    Warning 警告:有些没能理解的句子,我以自己的理解意译. 翻译自:Scikit Learn:Machine Learning in Python 作者: Fabian Pedregosa, Ga ...

  6. ImportError: /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type

    1. 问题描述 使用ananconda安装好opencv之后发现出现了这种问题: import cv2 ------------------------------------------------ ...

  7. Scikit中的特征选择,XGboost进行回归预测,模型优化的实战

    前天偶然在一个网站上看到一个数据分析的比赛(sofasofa),自己虽然学习一些关于机器学习的内容,但是并没有在比赛中实践过,于是我带着一种好奇心参加了这次比赛. 赛题:足球运动员身价估计 比赛概述 ...

  8. 如何检查电脑是否安装了python-python-如何检查安装了scikit的nltk版本?

    python-如何检查安装了scikit的nltk版本? 在外壳程序脚本中,我正在检查是否已安装此软件包,如果未安装,请先安装它. 因此,使用shell脚本: import nltk echo nlt ...

  9. python -scikit

    在用http://muricoca.github.io/crab/tutorial.html 里给的例子时,会发现不能运行,改库里的两个小地方就好了. 1. no module named learn ...

  10. mysql db.opt+ (frm,MYD,MYI)备份与还原数据库

    2019独角兽企业重金招聘Python工程师标准>>> mysql数据库的备份与还原主要有3中方式 方式一 备份:通过导出sql执行文件备份数据库 还原:通过导入sql执行文件到my ...

最新文章

  1. WPF入门:数据绑定
  2. brk(), sbrk() 用法详解【转】
  3. Qt工作笔记-以配置文件的方式动态获取Mysql数据库中的数据
  4. 基于Docker Compose搭建的Mysql8.0主从复制(1主3从,多主机)
  5. android finish后不能ondestroy_Android面试基础(一)
  6. Linux的辅助数据和传递文件描述符
  7. 谜题35:一分钟又一分钟
  8. Java经典设计模式 总览
  9. Java编程:弗洛伊德算法(无向图所有顶点最小路径)
  10. 最全的微信小程序源代码
  11. java 中文转gb2312_Java将GB2312编码转化为汉字
  12. 使用Python、pandas、pyecharts进行数据分析——实例讲解
  13. 各层电子数排布规则_电子排布式书写规则
  14. 汇总病毒样本的常用反调试技术、反分析技巧(持续更新)
  15. 电脑使用小常识(4):让win10强制更新棍淡
  16. DIV布局强制英文换行(div英文不怎么给力啊~ 只有用别的方法啦)
  17. Java基础(32)
  18. (小米系统系列四)小米/红米手机获取root根目录权限
  19. MySQL Workbench使用教程简介
  20. 第二节 python知识点梳理

热门文章

  1. Spring详解一号IOC京都大火篇
  2. 大数据python试卷_大数据分析的python基础-中国大学mooc-试题题目及答案
  3. 什么是实名域名?域名必须进行实名认证吗?
  4. 科属种XML文档三级树状图浏览的实现
  5. JavaScript学习笔记(条件判断)
  6. 《信号完整性分析》的读书笔记和总结
  7. 艺术设计用计算机主板,学艺术设计的用什么电脑比较好
  8. 计算机一个小键盘按不出来怎么办,我的电脑键盘上面1234按不出来怎么办
  9. xcode 设置编码区背景颜色为淡绿色
  10. Mac系统接移动硬盘进行读写软件Mounty