免疫算法简介及应用

简介

人工免疫算法(Immune Algorithm)是一种具有生成+检测 (generate and test)的迭代过程的群智能搜索算法。从理论上分析,迭代过程中,在保留上一代最佳个体的前提下,免疫算法是全局收敛的。

基本步骤

  1. 抗原识别。输入目标函数和各种约束作为免疫算法的抗原。
  2. 初始抗体生成。随机生成初始抗体种群。
  3. 亲和力计算。计算抗体的适应值。
  4. 免疫处理。免疫处理包括免疫选择、克隆、变异和抑制。
    1. 免疫选择:根据抗体的亲和力选出亲和度较高的抗体。
    2. 克隆:对选出的亲和力较高的抗体进行复制。
    3. 变异:对克隆得到的个体进行交叉、变异操作,使其亲和力发生改变。
    4. 抑制:对变异的抗体进行选择,保留亲和度较高的抗体。
  5. 群体刷新。将免疫选择的抗体和免疫抑制后的抗体组成一个集合,保留其中亲和度较高的抗体,使这些抗体进入新的种群。新的种群中不足的部分随机生成,以增加多样性。

流程图

应用

用IA解决TSP问题

import numpy as np
from scipy import spatial

# 全国31个省会(部分)城市的坐标
points_coordinate=[
[1304, 2312],
[3639, 1315],
[4177, 2244],
[3712, 1399],
[3488, 1535],
[3326, 1556],
[3238, 1229],
[4196, 1004],
[4312, 790],
[4386, 570],
[3007, 1970],
[2562, 1756],
[2788, 1491],
[2381, 1676],
[1332, 695],
[3715, 1678],
[3918, 2179],
[4061, 2370],
[3780, 2212],
[3676, 2578],
[4029, 2838],
[4263, 2931],
[3429, 1908],
[3507, 2367],
[3394, 2643],
[3439, 3201],
[2935, 3240],
[3140, 3550],
[2545, 2357],
[2778, 2826],
[2370, 2975],
]
points_coordinate = np.array(points_coordinate)
num_points = points_coordinate.shape[0]
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')


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


# run IA
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)


# step3: plot
import matplotlib.pyplot as plt

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

结果如下:

best routine: [19 20 21 17  2 16 18 22 15  3  7  8  9  1  4  5  6 12 11 13 14  0 30 26 27 25 29 28 10 23 24] 
best_distance: [15844.52047043]

参考链接:

1. 腾讯云社区-免疫算法简单介绍

2. CSDN三名狂客-免疫算法

3. 百度百科-免疫算法

4. scikit-opt官方文档-IA部分

猜你喜欢

转载自www.cnblogs.com/lfri/p/12242443.html