简介: # [scikit-opt](https://github.com/guofei9987/scikit-opt) [![PyPI](https://img.shields.io/pypi/v/scikit-opt)](https://pypi.org/project/scikit-opt/) [![release](https://img.shields.io/github/v/relea

scikit-opt








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



安装

pip install scikit-opt

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

特性

特性1:UDF(用户自定义算子)

举例来说,你想出一种新的“选择算子”,如下
-> Demo code: examples/demo_ga_udf.py#s1

# step1: define your own operator:
def selection_tournament(algorithm, tourn_size):FitV = algorithm.FitVsel_index = []for i in range(algorithm.size_pop):aspirants_index = np.random.choice(range(algorithm.size_pop), size=tourn_size)sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))algorithm.Chrom = algorithm.Chrom[sel_index, :]  # next generationreturn algorithm.Chrom

导入包,并且创建遗传算法实例 
-> Demo code: examples/demo_ga_udf.py#s2

import numpy as np
from sko.GA import GA, GA_TSPdemo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2
ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2],precision=[1e-7, 1e-7, 1])

把你的算子注册到你创建好的遗传算法实例上 
-> Demo code: examples/demo_ga_udf.py#s3

ga.register(operator_name='selection', operator=selection_tournament, tourn_size=3)

scikit-opt 也提供了十几个算子供你调用 
-> Demo code: examples/demo_ga_udf.py#s4

from sko.operators import ranking, selection, crossover, mutationga.register(operator_name='ranking', operator=ranking.ranking). \register(operator_name='crossover', operator=crossover.crossover_2point). \register(operator_name='mutation', operator=mutation.mutation)

做遗传算法运算
-> Demo code: examples/demo_ga_udf.py#s5

best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

现在 udf 支持遗传算法的这几个算子: crossovermutationselectionranking

Scikit-opt 也提供了十来个算子,参考这里

提供一个面向对象风格的自定义算子的方法,供进阶用户使用:

-> Demo code: examples/demo_ga_udf.py#s6

class MyGA(GA):def selection(self, tourn_size=3):FitV = self.FitVsel_index = []for i in range(self.size_pop):aspirants_index = np.random.choice(range(self.size_pop), size=tourn_size)sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))self.Chrom = self.Chrom[sel_index, :]  # next generationreturn self.Chromranking = ranking.rankingdemo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2
my_ga = MyGA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2],precision=[1e-7, 1e-7, 1])
best_x, best_y = my_ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

特性2: GPU 加速

GPU加速功能还比较简单,将会在 1.0.0 版本大大完善。 
有个 demo 已经可以在现版本运行了: https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_gpu.py

特性3:断点继续运行

例如,先跑10代,然后在此基础上再跑20代,可以这么写:

from sko.GA import GAfunc = lambda x: x[0] ** 2
ga = GA(func=func, n_dim=1)
ga.run(10)
ga.run(20)

快速开始

1. 差分进化算法

Step1:定义你的问题,这个demo定义了有约束优化问题 
-> Demo code: examples/demo_de.py#s1

'''
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
]

Step2: 做差分进化算法 
-> Demo code: examples/demo_de.py#s2

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)

2. 遗传算法

第一步:定义你的问题 
-> Demo code: examples/demo_ga.py#s1

import numpy as npdef schaffer(p):'''This function has plenty of local minimum, with strong shocksglobal minimum at (0,0) with value 0'''x1, x2 = px = np.square(x1) + np.square(x2)return 0.5 + (np.sin(x) - 0.5) / np.square(1 + 0.001 * x)

第二步:运行遗传算法 
-> Demo code: examples/demo_ga.py#s2

from sko.GA import GAga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, 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)

第三步:用 matplotlib 画出结果 
-> Demo code: examples/demo_ga.py#s3

import pandas as pd
import matplotlib.pyplot as pltY_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()

2.2 遗传算法用于旅行商问题

GA_TSP 针对TSP问题重载了 交叉(crossover)变异(mutation) 两个算子

第一步,定义问题。 
这里作为demo,随机生成距离矩阵. 实战中从真实数据源中读取。

-> Demo code: examples/demo_ga_tsp.py#s1

import numpy as np
from scipy import spatial
import matplotlib.pyplot as pltnum_points = 50points_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):'''The objective function. input routine, return total distance.cal_total_distance(np.arange(num_points))'''num_points, = routine.shapereturn sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

第二步,调用遗传算法进行求解 
-> Demo code: examples/demo_ga_tsp.py#s2


from sko.GA import GA_TSPga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1)
best_points, best_distance = ga_tsp.run()

第三步,画出结果: 
-> Demo code: examples/demo_ga_tsp.py#s3

fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
ax[1].plot(ga_tsp.generation_best_Y)
plt.show()

3. 粒子群算法

(PSO, Particle swarm optimization)

3.1 带约束的粒子群算法

第一步,定义问题 
-> Demo code: examples/demo_pso.py#s1

def demo_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2

第二步,做粒子群算法 
-> Demo code: examples/demo_pso.py#s2

from sko.PSO import PSOpso = PSO(func=demo_func, 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)

第三步,画出结果 
-> Demo code: examples/demo_pso.py#s3

import matplotlib.pyplot as pltplt.plot(pso.gbest_y_hist)
plt.show()


see examples/demo_pso.py

3.2 不带约束的粒子群算法

-> Demo code: examples/demo_pso.py#s4

pso = PSO(func=demo_func, dim=3)
fitness = pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

4. 模拟退火算法

(SA, Simulated Annealing)

4.1 模拟退火算法用于多元函数优化

第一步:定义问题 
-> Demo code: examples/demo_sa.py#s1

demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2

第二步,运行模拟退火算法 
-> Demo code: examples/demo_sa.py#s2

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)

第三步,画出结果
-> Demo code: examples/demo_sa.py#s3

import matplotlib.pyplot as plt
import pandas as pdplt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))
plt.show()

另外,scikit-opt 还提供了三种模拟退火流派: Fast, Boltzmann, Cauchy. 更多参见 more sa

4.2 模拟退火算法解决TSP问题(旅行商问题)

第一步,定义问题。(我猜你已经无聊了,所以不黏贴这一步了)

第二步,调用模拟退火算法 
-> Demo code: examples/demo_sa_tsp.py#s2

from sko.SA import SA_TSPsa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=100, T_min=1, L=10 * num_points)best_points, best_distance = sa_tsp.run()
print(best_points, best_distance, cal_total_distance(best_points))

第三步,画出结果
-> Demo code: examples/demo_sa_tsp.py#s3

from matplotlib.ticker import FormatStrFormatterfig, ax = plt.subplots(1, 2)best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(sa_tsp.best_y_history)
ax[0].set_xlabel("Iteration")
ax[0].set_ylabel("Distance")
ax[1].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1],marker='o', markerfacecolor='b', color='c', linestyle='-')
ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f'))
ax[1].set_xlabel("Longitude")
ax[1].set_ylabel("Latitude")
plt.show()

咱还有个动画 

参考代码 examples/demo_sa_tsp.py

5. 蚁群算法

蚁群算法(ACA, Ant Colony Algorithm)解决TSP问题

-> Demo code: examples/demo_aca_tsp.py#s2

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()

6. 免疫优化算法

(immune algorithm, IA)
-> Demo code: examples/demo_ia.py#s2


from sko.IA import IA_TSPia_tsp = IA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=500, max_iter=800, prob_mut=0.2,T=0.7, alpha=0.95)
best_points, best_distance = ia_tsp.run()
print('best routine:', best_points, 'best_distance:', best_distance)

7. 人工鱼群算法

人工鱼群算法(artificial fish swarm algorithm, AFSA)

-> Demo code: examples/demo_afsa.py#s1

def func(x):x1, x2 = xreturn 1 / x1 ** 2 + x1 ** 2 + 1 / x2 ** 2 + x2 ** 2from sko.AFSA import AFSAafsa = AFSA(func, n_dim=2, size_pop=50, max_iter=300,max_try_num=100, step=0.5, visual=0.3,q=0.98, delta=0.5)
best_x, best_y = afsa.run()
print(best_x, best_y)

原文链接
本文为阿里云原创内容,未经允许不得转载。

一个易用、易部署的Python遗传算法库相关推荐

  1. python 算法库_一个易用又功能强大的 Python遗传算法库

    github地址guofei9987/scikit-opt​github.com 安装 $pip install scikit-opt 定义你的目标函数 def demo_func(x): x1, x ...

  2. Python遗传算法库和进化算法框架(二)Geatpy库函数和数据结构

    (转载自https://blog.csdn.net/qq_33353186/article/details/82020507) 上一篇讲了Geatpy的快速入门:https://blog.csdn.n ...

  3. WormHole是一个简单、易用的api管理平台,支持dubbo服务调用

    WormHole服务网关管理平台 相关快速链接 管理台操作说明 C端对接网关及签名说明 回调接口使用说明 多环境配置使用说明 网关错误码说明 WormHole更新说明 配置好即可运行 GitHub地址 ...

  4. [Android开源]一个非常简单易用用来花式展示二维码样式生成的库QRCodeStyle

    类库说明 一个非常简单易用用来花式展示二维码样式生成的库 自由组合二维码样式 使用范例 设置带圆边圈的logo Bitmap logo = BitmapFactory.decodeResource(g ...

  5. 易语言 python库_精易Python支持库 (1.1#1205版)发布啦!

    精易Python支持库 (1.1#1205版) 本支持库提供了 6 种库定义数据类型,提供了 87 种命令. 支持库说明 该支持库为易语言调用并执行Python代码.文件提供了支持. 使用本支持库,可 ...

  6. 量子计算机与易经,易经卦象的演化过程,就是一个量子计算机模型?

    易经卦象的演化过程,就是一个量子计算机模型 易经 量子计算机模型,看来要更加接近易学模型,甚至易学卦象就是量子计算机的一个运作机制, 当事情还没有发生的时候,输入一个初始值,通过模型推演,就可以得出结 ...

  7. 易语言python_易语言python支持库

    易语言python支持库 支持库名:易语言python支持库 1.0 版 相关文件: C:\Program Files (x86)\e\lib\pythonae.fne 数字签名:{C2547100- ...

  8. ZanUI-WeApp -- 一个颜值高、好用、易扩展的微信小程序 UI 库

    ZanUI-WeApp -- 一个颜值高.好用.易扩展的微信小程序 UI 库:https://cnodejs.org/topic/589d625a5c8036f7019e7a4a 微信小程序之官方UI ...

  9. 安装python扩展库时只能使用pip_安装 Python 扩展库时只能使用 pip 工具在线安装,如果安装不成功就没有别的办法了。_学小易找答案...

    [单选题]关于Python中的复数,下列说法错误的是_________________. [填空题]在Python程序中,导入sys模块后,可以通过列表________________访问命令行参数. ...

最新文章

  1. MIT-THU未来城市创新网络即将和你见面!
  2. 英特尔诺基亚将联手开发智能手机
  3. 进击的UI---------------------UIStepper(加减)
  4. 贪心算法———房间搬桌子
  5. 【读书笔记】Android的Ashmem机制学习
  6. 电脑主机,晚上就煎肉,把隔壁宿舍都馋哭了!
  7. AngularJs学习笔记--Modules
  8. hdu3339 In Action(Dijkstra+01背包)
  9. 排序二叉树 SortBinaryTree
  10. POI大量数据读取内存溢出分析及解决方案
  11. Batteries for Mac(电池电量管理软件)
  12. 关于数据中心的设计方案,数据中心网络规划设计
  13. 农村三资管理平台app_鑫农三资app下载-鑫农三资app下载安卓版 v1.0.2_手机乐园
  14. 暗原色先验单一输入图像去雾
  15. Protues8.6仿真STM32出现错误-VDDA和VSSA的问题解决办法
  16. 金融安全资讯精选 2017年第二期:金融网络安全和反欺诈方法论_金融新兴技术成熟度几何?...
  17. golang中定时器ticker
  18. Android UI控件和布局
  19. 人机交互 交互形式和交互设备
  20. node安装详细步骤

热门文章

  1. mongodb mysql配置_Nosql_MongoDB数据库配置以及基本指令
  2. python输入的字符串转换为对应的数字类型_Python合集之Python运算符(四)
  3. python坐标定位_如何利用Python识别并定位图片中某一个色块的坐标?
  4. fetch 不是xhr_春招|前端2019应届春招:不是被大厂选,而是选大厂(字节跳动,美团,网易)...
  5. linux set权限,Linux 特殊权限set_uid(示例代码)
  6. mysql 存储引擎版本_mysql不同版本和存储引擎选型的验证
  7. 分别对时分秒加减的java_Java中关于获取时间(日期)的总结大全
  8. mysql php 乱码问题_解决php与mysql中文乱码问题
  9. php获得指定目录文件,PHP遍历指定文件夹获取路径及大小(包含子文件夹)
  10. 问了自己8个问题后,我选择了考博...