日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

一个易用、易部署的Python遗传算法库

發布時間:2024/8/23 python 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一个易用、易部署的Python遗传算法库 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

簡介:?# [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?支持遺傳算法的這幾個算子:?crossover,?mutation,?selection,?ranking

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遗传算法库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 国产偷国产偷av亚洲清高 | 久久综合久久久久 | 黄色高清免费 | 91av在线免费视频 | 91av俱乐部 | 国产黄色片免费在线观看 | 怡红院综合网 | 国产又粗又猛又黄又爽视频 | 亚洲综合丁香 | 日韩三级黄色 | 久久大胆人体 | 日日摸夜夜添狠狠添欧美 | 欧美xo影院 | 国产精品无遮挡 | 国产精品高潮呻吟av | 91av在线视频观看 | 日韩在线观看免费网站 | www婷婷 | 日韩a视频| 四虎影视www在线播放 | 91涩漫成人官网入口 | 久久亚洲综合色 | 在线成人亚洲 | 欧美高清x| 日韩综合网 | 中文字幕精品久久久久人妻红杏1 | 狠狠干香蕉 | 成人h动漫精品一区二 | 久久久久久久久久国产精品 | 黑白配在线观看免费观看 | 亚洲爱 | 天天综合天天添夜夜添狠狠添 | 国产福利资源在线 | 丝袜熟女一区二区 | 加勒比综合网 | 国产操女人 | 欧美三级免费 | 波多野结衣在线播放视频 | 欧美一级艳片视频免费观看 | 在线观看免费人成视频 | 精品| 韩国三级在线 | 法国空姐在线观看免费 | 白浆在线| 国产91综合一区在线观看 | 黑白配在线观看免费观看 | 国产又粗又猛又黄又爽 | 精产国品一二三产品蜜桃 | 成人在线观看亚洲 | 涩五月婷婷 | av福利站| 欧美久久久久久久 | 国产草草草 | 国产免费二区 | 日韩av电影手机在线观看 | 日本中文字幕在线免费观看 | 超碰在线97观看 | 亚洲成a人片77777精品 | 亚洲色图3p | 国产在线精品二区 | 欧美性猛交 xxxx | 人人草人人射 | 亚洲大尺度在线观看 | 婷婷五月情 | 自拍偷拍精品视频 | 黄色网址中文字幕 | 日韩经典三级 | 久久免费偷拍视频 | 亚洲一区不卡在线 | 亚洲av人无码激艳猛片服务器 | 日韩91在线 | 91精品人妻一区二区三区 | www.激情五月| 做视频| 亚洲精品偷拍视频 | 在线观看国产日韩 | 日韩在线视频免费播放 | 日韩美女免费视频 | 一区二区av| av网站在线免费看 | 九九黄色大片 | 无码国模国产在线观看 | 大粗鳮巴久久久久久久久 | 中文字幕在线免费观看视频 | 日韩精品一区不卡 | 毛片网站入口 | 男生和女生操操 | 国产精彩视频一区二区 | a√在线视频| 一区二区免费在线视频 | 蜜色视频| 亚洲综合自拍偷拍 | 国产精品视频你懂的 | 国产精品99久久久久久宅男 | 中文字幕国产在线 | 国产一级免费在线观看 | 五十路在线 | 小辣椒导航 | 日本在线视频一区 |