Python 有啥启发式算法的包吗( 二 )

这个库的灵活之处在于,可以方便地添加自定义算子
例如,如果你想到一种选择算子(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)) self.Chrom = self.Chrom # next generation return self.Chrom把你的 UDF 自定义算子注册到遗传算法对象上:from sko.GA import GA, GA_TSPfrom sko.GA import ranking_linear, ranking_raw, crossover_2point, selection_roulette_2, mutationdemo_func = lambda x: x ** 2 + (x - 0.05) ** 2 + x ** 2ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=, ub=)#ga.register(operator_name=\u0026#39;ranking\u0026#39;, operator=ranking_linear). \\ register(operator_name=\u0026#39;crossover\u0026#39;, operator=crossover_2point). \\ register(operator_name=\u0026#39;mutation\u0026#39;, operator=mutation). \\ register(operator_name=\u0026#39;selection\u0026#39;, operator=selection_tournament, tourn_size=3)像往常一样运行遗传算法:best_x, best_y = ga.run()print(\u0026#39;best_x:\u0026#39;, best_x, \u0026#39;\\u0026#39;, \u0026#39;best_y:\u0026#39;, best_y)恭喜你,成功了。
现在 udf 支持遗传算法的这几个算子: crossover, mutation, selection, ranking提供了十来个算子 参考这里3. 粒子群算法定义目标函数def demo_func(x): x1, x2, x3 = x return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2优化求解from sko.PSO import PSOpso = PSO(func=demo_func, dim=3)fitness = pso.run()print(\u0026#39;best_x is \u0026#39;,pso.gbest_x)print(\u0026#39;best_y is \u0026#39;,pso.gbest_y)pso.plot_history()
4.1 模拟退火算法用于多元函数优化from sko.SA import SAdef demo_func(x): x1, x2, x3 = x return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2sa = SA(func=demo_func, x0=)x_star, y_star = sa.run()print(x_star, y_star)import matplotlib.pyplot as pltimport pandas as pdplt.plot(pd.DataFrame(sa.f_list).cummin(axis=0))plt.show()
4.2 模拟退火算法解决TSP问题TSP问题(旅行商问题)
作为demo,生成模拟数据(代码与遗传算法解决TSP问题一样,这里省略)
调用模拟退火算法from sko.SA import SA_TSPsa_tsp = SA_TSP(func=demo_func, x0=range(num_points))best_points, best_distance = sa_tsp.run()
推荐阅读
- 有啥方法,网站,项目可以自己练习计算广告学
- 怎样成为一名合格的Python程序员?
- python 爬虫,咋获得输入验证码之后的搜索结果
- 100W——150W有啥好的车
- python的html5lib这个库咋使用啊我在网上也没有找到相关文档
- 最近有啥样的交友软件比较好玩呢
- 最近有啥好期待的网游玩
- 电子信息工程考研有啥偏软件类的专业可以报考
- 淘宝上有啥体验不错的假货,赝品或者山寨货?
- 零基础入门学习啥语言好
