Python优化算法05——蚁群算法和免疫优化算法

 参考文档链接:scikit-opt


本章继续Python的优化算法系列。

优化算法,尤其是启发式的仿生智能算法在最近很火,它适用于解决管理学,运筹学,统计学里面的一些优化问题。比如线性规划,整数规划,动态规划,非线性约束规划,甚至是超参数搜索等等方向的问题。

但是一般的优化算法还是matlab里面用的多,Python相关代码较少。博主在参考了很多文章的代码和模块之后,决定学习 scikit-opt   这个模块。这个优化算法模块对新手很友好,代码简洁,上手简单。而且代码和官方文档是中国人写的,还有很多案例,学起来就没什么压力...

缺点是包装的算法种类目前还不算多,只有七种:(差分进化算法、遗传算法、粒子群算法、模拟退火算法、蚁群算法、鱼群算法、免疫优化算法)      /(其实已经够用了)

本次带来的是 蚁群算法和免疫优化算法的使用演示。数学原理就不多说了。由于这个包里面好像目前只有解决商旅问题的版本。使用本次使用这两个算法解决商旅问题。


首先安装模块,在cmd里面或者anaconda prompt里面输入:

pip install scikit-opt

这个包很小,很快就能装好。


商旅问题定义

商旅问题(TSP)就是路径规划的问题,比如有很多城市,你都要跑一遍,那么先去哪个城市再去哪个城市可以让你的总路程最小。

实际问题需要一个城市坐标数据,比如你的出发点位置为(0,0),第一个城市离位置为(x1,y1),第二个为(x2,y2).........这里没有实际数据,就直接随机生成了。

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
points_coordinate 

 

 这里定义的是50个城市,每个城市的坐标都在是上图随机生成的矩阵。

然后我们把它变成类似相关系数里面的矩阵

distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')
distance_matrix.shape

 这个矩阵就能得出每个城市之间的距离,算上自己和自己的距离(0),总共有2500个数。

定义问题

def cal_total_distance(routine):
    num_points, = routine.shape
    return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])

然后进行求解:


蚁群算法求解商旅问题

from sko.ACA import ACA_TSP

aca = ACA_TSP(func=cal_total_distance, n_dim=num_points,
              size_pop=50, max_iter=200,
              distance_matrix=distance_matrix)

best_points, best_distance= aca.run()
best_distance

最短总距离

画图查看路径

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

 


 免疫优化算法求解商旅问题

from sko.IA import IA_TSP

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

 

画图查看路径

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

 结果也还不错。


参数详解

输入参数:

蚁群算法

 免疫优化算法

 

输出参数

蚁群算法

  免疫优化算法

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阡之尘埃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值