蚁群算法代码

2021/8/3 17:07:46

本文主要是介绍蚁群算法代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在网上看了一些蚁群算法原理,其中最为广泛的应用还是那个旅行家问题(TSP)。诸如粒子群优化算法,蚁群算法都可以求一个目标函数的最小值问题的。

下面代码记录下跑的代码。蚁群算法中最为重要的就是目标函数和信息素矩阵的设计。其他的参数则为信息素重要程度,信息素挥发速度,适应度的重要程度。

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

'''
test Ant Aolony Algorithm
'''

num_points = 25

points_coordinate = np.random.rand(num_points, 2)  # generate coordinate of points


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

# routine 中应该为一个列表,其中存放的是遍历过程中的位置编号
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)])


# %% Do ACA
from sko.ACA import ACA_TSP

'''
    需要设置的参数包含以下部分:
    (1):    目标函数: 用于衡量之前走过的的路径的目标值(累计路程值), 需要有一个参数routine, 用于记录遍历的路径位置索引
    (2):    维度数目: 此数字将被用于程序进行构建遍历路径位置索引
    (3):    蚁群数目: size_pop
    (4):    最大迭代次数: 作为一项中值条件
    (5):    距离(隶属度/信息素)矩阵:  蚁群算法中一般称其为信息素矩阵,需要预先进行计算,旨在记录两个路径点之间的距离长度
    [注意]: 距离矩阵在输入之前需要进行计算
    缺点: 速度太慢
'''
aca = ACA_TSP(func=cal_total_distance, n_dim=num_points,
              size_pop=500, max_iter=200,
              distance_matrix=distance_matrix)

best_x, best_y = aca.run()


# %% Plot
fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_x, [best_x[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1])
plt.show()

 



这篇关于蚁群算法代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程