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

github地址guofei9987/scikit-opt​github.comv2-4f5cdb38bbfb23abe4ced8ba01dfeb44_ipico.jpg

安装

$pip install scikit-opt

定义你的目标函数

def demo_func(x):

x1, x2, x3 = x

return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2

用遗传算法求解

from ga import GA

ga = GA(func=demo_func, lb=[-1, -10, -5], ub=[2, 10, 2], max_iter=500)

best_x, best_y = ga.run()

还提供一个每代数据的接口,可以拿来画各个维度的图

import pandas as pd

import matplotlib.pyplot as plt

FitV_history = pd.DataFrame(ga.FitV_history)

fig, ax = plt.subplots(2, 1)

ax[0].plot(FitV_history.index, FitV_history.values, '.', color='red')

plt_max = FitV_history.max(axis=1)

ax[1].plot(plt_max.index, plt_max, label='max')

ax[1].plot(plt_max.index, plt_max.cummax())

plt.show()

2. 用遗传算法解决TSP问题(Travelling Salesman Problem)

加载距离矩阵的数据,这里用随机数生成数据

from GA import GA_TSP

import numpy as np

num_points = 8

points = range(num_points)

points_coordinate = np.random.rand(num_points, 2)

distance_matrix = np.zeros(shape=(num_points, num_points))

for i in range(num_points):

for j in range(num_points):

distance_matrix[i][j] = np.linalg.norm(points_coordinate[i] - points_coordinate[j], ord=2)

print('distance_matrix is: \n', distance_matrix)

def cal_total_distance(points):

num_points, = points.shape

total_distance = 0

for i in range(num_points - 1):

total_distance += distance_matrix[points[i], points[i + 1]]

total_distance += distance_matrix[points[i + 1], points[0]]

return total_distance

用遗传算法求解:

ga_tsp = GA_TSP(func=cal_total_distance, points=points, pop=50, max_iter=200, Pm=0.001)

best_points, best_distance = ga_tsp.fit()

画图:

fig, ax = plt.subplots(1, 1)

best_points_ = np.concatenate([best_points, [best_points[0]]])

best_points_coordinate = points_coordinate[best_points_, :]

ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1],'o-r')

plt.show

这个库的灵活之处在于,可以方便地添加自定义算子

例如,如果你想到一种选择算子(selection),你的算子是这样的:

def selection_tournament(self, tourn_size):

FitV = self.FitV

sel_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 generation

return self.Chrom

把你的 UDF 自定义算子注册到遗传算法对象上:

from sko.GA import GA, GA_TSP

from sko.GA import ranking_linear, ranking_raw, crossover_2point, selection_roulette_2, mutation

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

ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2])

#

ga.register(operator_name='ranking', operator=ranking_linear). \

register(operator_name='crossover', operator=crossover_2point). \

register(operator_name='mutation', operator=mutation). \

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

像往常一样运行遗传算法:

best_x, best_y = ga.run()

print('best_x:', best_x, '\n', 'best_y:', best_y)

恭喜你,成功了。现在 udf 支持遗传算法的这几个算子: crossover, mutation, selection, ranking

提供了十来个算子 参考这里

库的地址,欢迎starscikit-opt​github.com

另外,这个库还封装了粒子群算法(PSO)、蚁群算法(ACA)、模拟退火算法(SA)、免疫优化算法(IA)、人工鱼群算法(AFSA)中文文档​scikit-opt.github.ioDocument​scikit-opt.github.io

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用sko来实现Python中的遗传算法。在这个中,您可以使用GA类来创建遗传算法的实例,并设置相应的参数,如目标函数、变量维度、种群大小、迭代次数等。通过调用run()方法,您可以运行遗传算法并获取最佳解。 以下是一个使用sko实现遗传算法的示例代码: ``` import numpy as np from sko.GA import GA # 定义目标函数 demo_func = lambda x: x ** 2 + (x - 0.05) ** 2 + (x - 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]) # 运行遗传算法 best_x, best_y = ga.run() # 打印结果 print('best_x:', best_x, '\n', 'best_y:', best_y) ``` 上述代码中,我们首先定义了目标函数`demo_func`,然后使用GA类创建了一个遗传算法实例`ga`。接着通过调用run()方法,运行遗传算法,并获取最佳解`best_x`和最佳值`best_y`。最后,我们将结果打印出来。 请注意,上述代码仅作为示例,您可以根据自己的需求进行相应的修改和调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [一个易用、易部署的Python遗传算法](https://blog.csdn.net/yunqiinsight/article/details/108144993)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值