簡介
人工免疫算法(Immune Algorithm)是一種具有生成+檢測 (generate and test)的迭代過程的群智能搜索算法。從理論上分析,迭代過程中,在保留上一代最佳個體的前提下,免疫算法是全局收斂的。
基本步驟
- 抗原識別。輸入目標函數和各種約束作為免疫算法的抗原。
- 初始抗體生成。隨機生成初始抗體種群。
- 親和力計算。計算抗體的適應值。
- 免疫處理。免疫處理包括免疫選擇、克隆、變異和抑制。
- 免疫選擇:根據抗體的親和力選出親和度較高的抗體。
- 克隆:對選出的親和力較高的抗體進行復制。
- 變異:對克隆得到的個體進行交叉、變異操作,使其親和力發生改變。
- 抑制:對變異的抗體進行選擇,保留親和度較高的抗體。
- 群體刷新。將免疫選擇的抗體和免疫抑制后的抗體組成一個集合,保留其中親和度較高的抗體,使這些抗體進入新的種群。新的種群中不足的部分隨機生成,以增加多樣性。
流程圖
應用
用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]
參考鏈接:
3. 百度百科-免疫算法