scikit-opt——Python中的群体智能优化算法库

安装

pip install scikit-opt

对于当前的开发者版本:

git clone [email protected]:guofei9987/scikit-opt.git
cd scikit-opt
pip install .

Genetic Algorithm

第一步:定义你的问题

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.sin(x) - 0.5) / np.square(1 + 0.001 * x)

第二步:运行遗传算法

from sko.GA import GA
#2个变量,每代取50个,800次迭代,上下界及精度
ga = 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)

第三步:画出结果

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

精度改成1就能视为整数规划。

Genetic Algorithm for TSP(Travelling Salesman Problem)

只需要导入GA_TSP,它重载了crossover, mutation来解决TSP.

第一步:定义你的问题。准备你的点的坐标和距离矩阵。

这里使用随机数据作为Demo.

import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt

num_points = 50

points_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.shape
    return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

第二步:运行GA算法

from sko.GA import GA_TSP

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

第三步:画出结果

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

参考链接:scikit-opt官方文档-遗传算法部分

原文地址:https://www.cnblogs.com/lfri/p/12241206.html

时间: 2024-07-31 12:25:53

scikit-opt——Python中的群体智能优化算法库的相关文章

Python中的二叉树查找算法模块

问题 思路说明 二叉树查找算法,在开发实践中,会经常用到.按照惯例,对于这么一个常用的东西,Python一定会提供轮子的.是的,python就是这样,一定会让开发者省心,降低开发者的工作压力. python中的二叉树模块内容: BinaryTree:非平衡二叉树 AVLTree:平衡的AVL树 RBTree:平衡的红黑树 以上是用python写的,相面的模块是用c写的,并且可以做为Cython的包. FastBinaryTree FastAVLTree FastRBTree 特别需要说明的是:树

Python中的Apriori关联算法-市场购物篮分析

数据科学Apriori算法是一种数据挖掘技术,用于挖掘频繁项集和相关的关联规则.本模块重点介绍什么是关联规则挖掘和Apriori算法,以及Apriori算法的用法.此外,在小型企业场景中,我们将借助Python编程语言构建一个Apriori模型. 什么是关联规则挖掘? 如前所述,Apriori算法用于关联规则挖掘.现在,什么是关联规则挖掘?关联规则挖掘是一种用于识别一组项目之间的频繁模式和关联的技术. 例如,了解客户的购买习惯.通过查找顾客放置在其“购物篮”中的不同商品之间的关联和关联,可以得出

linux 下的动态库制作 以及在python 中如何调用 c 函数库

动态库: 动态库又称动态链接库英文为DLL,是Dynamic Link Library 的缩写形式,DLL是一个包含可由多个程序同时使用的代码和数据的库,DLL不是可执行文件.动态链接提供了一种方法,使进程可以调用不属于其可执行代码的函数.函数的可执行代码位于一个 DLL 中,该 DLL 包含一个或多个已被编译.链接并与使用它们的进程分开存储的函数.DLL 还有助于共享数据和资源.多个应用程序可同时访问内存中单个DLL 副本的内容.DLL 是一个包含可由多个程序同时使用的代码和数据的库.Wind

python中的轻量级定时任务调度库:schedule

提到定时任务调度的时候,相信很多人会想到芹菜celery,要么就写个脚本塞到crontab中.不过,一个小的定时脚本,要用celery的话太“重”了.所以,我找到了一个轻量级的定时任务调度的库:schedule. 库的安装还是最简单的pip install schedule,使用起来也是很容易理解的.我们从最简单的栗子看起: import schedule import time def job(): print("I'm working...") schedule.every(10)

Python实现的粒子群优化算法

01.from numpy import array 02.from random import random 03.from math import sin, sqrt 04. 05.iter_max = 10000 06.pop_size = 100 07.dimensions = 2 08.c1 = 2 09.c2 = 2 10.err_crit = 0.00001 11. 12.class Particle: 13. pass 14. 15.def f6(param): 16. '''S

python中常用的函数与库一

1, collections.deque 在python里如果我们用列表作为队列使用也是可以的,只是当从队尾删除或者增加元素的时候是很快的,但是从队首删除或者增加元素则要慢得多,这是因为在队首进行操作其他的元素都要逐一改变. collections.deque就是为队列设计的,它能迅速得删除或者增加元素,无论是队首还是队尾 >>> from collections import deque >>> queue = deque(["Eric", &qu

在 python 中查看已安装三方库的版本号

对于已安装的三方库,有的时候需要查看一下版本号,本文记录如下内容: python的版本号 三方库的版本号 下图中的操作是在PyCharm中进行的操作,在其它的控制台中同理 1.python的版本号: python 2.三方库的版本号分为两种查找方式,一种是查找所有的安装列表,另一种是查找指定库的版本 2.1.查找所有:pip list 2.2.查找指定库的版本:pip show pandas 原文地址:https://www.cnblogs.com/rui-yang/p/11798337.htm

Python中处理HTTP协议的库:urllib2

使用Python访问网页主要有三种方式: urllib, urllib2, httplib urllib比较简单,功能相对也比较弱,httplib简单强大,但不支持session 1. 最简单的页面访问(获取服务器端的Response包) res=urllib2.urlopen(url) print res.read() 2. 加上要GET或POST的数据 data={"name":"hank", "passwd":"hjz"

python 中问题,包括某些库的问题

*)matplotlib animate中变量作用域的问题 错误提示: UnboundLocalError: local variable 'i' referenced before assignment 代码: i=0 def animate(frameno): x = mu + sigma * np.random.randn(N) n, _ = np.histogram(x, bins, normed=True) time_text.set_text(time_template%framen