├── Ant_Colony_Optimization
├── ACO_MatLab
│ ├── AC解决函数最优解
│ │ ├── F.m
│ │ └── SolveMax.m
│ ├── AC解决机器人路径规划
│ │ ├── DrawRoute.m
│ │ ├── G2D.m
│ │ ├── Magine.gif
│ │ ├── main.m
│ │ └── test.gif
│ └── AOC解决TSP问题
│ │ ├── DrawRoute.m
│ │ ├── TSP.gif
│ │ ├── mian.m
│ │ └── res.png
└── README.md
├── Genetic_Algorithm
├── GA_Java
│ ├── Chromosome.java
│ ├── GeneticAlgorithm.java
│ └── GeneticAlgorithmTest.java
├── GA_MatLab
│ ├── GA遗传算法工具箱
│ │ ├── Test.m
│ │ └── ga44.m
│ ├── GA遗传算法解决TSP问题
│ │ ├── cross.m
│ │ ├── exchange.m
│ │ ├── fit.m
│ │ ├── main.m
│ │ ├── mutation.m
│ │ ├── myLength.m
│ │ ├── plot_route.m
│ │ └── reverse.m
│ └── GA遗传算法解决非线性最优解
│ │ ├── README.md
│ │ ├── best.m
│ │ ├── binary2decimal.m
│ │ ├── cal_objvalue.m
│ │ ├── crossover.m
│ │ ├── initpop.m
│ │ ├── main.m
│ │ ├── mutation.m
│ │ └── selection.m
├── GA_Python
│ ├── GA_Test.py
│ └── Population.py
└── README.md
├── Immunity_Algorithm
├── IMA
│ ├── bamboo.bmp
│ ├── bird.bmp
│ ├── cross.m
│ ├── drawResult.m
│ ├── fit.m
│ ├── fitnessty.m
│ ├── isRgb.m
│ ├── main.asv
│ ├── main.m
│ ├── mutation.m
│ ├── select.m
│ ├── similarChromosome.m
│ └── similarPopulation.m
├── IMA解决TSP问题
│ ├── CharRecompose.m
│ ├── DisplaceInit.m
│ ├── DisplaceStr.m
│ ├── DrawRoute.m
│ ├── DrawRouteGif.m
│ ├── Mutation.m
│ ├── SelectAntigen.m
│ ├── main.m
│ └── test.gif
├── IMA解决非线性问题求解
│ ├── DecodeFun.m
│ ├── Hypermutation.m
│ ├── InitializeFun.m
│ ├── ReproduceFun.m
│ └── main.m
└── README.md
├── Particle_Swarm_Optimization
├── PSO-Toolbox
│ ├── main.m
│ └── pso_func.m
└── PSO-basic
│ ├── DrawGriewank.m
│ ├── DrawRastrigin.m
│ ├── Griewank.m
│ ├── PSO.m
│ ├── Rastrigin.m
│ ├── fitness.m
│ └── main.m
├── README.md
└── Smart-Algorithm.iml
/Ant_Colony_Optimization/ACO_MatLab/AC解决函数最优解/F.m:
--------------------------------------------------------------------------------
1 | function z = F(x, y)
2 | z = -(x.^4 + 3 * y.^4 - 0.2 * cos(3 * pi * x) - 0.4 * cos(4 * pi * y) + 0.6);
3 |
4 |
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决函数最优解/SolveMax.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AC解决函数最优解/SolveMax.m
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/DrawRoute.m:
--------------------------------------------------------------------------------
1 | function DrawRoute(X, Y)
2 | for i = 2: length(X)
3 | plot([X(i - 1), X(i)], [Y(i - 1), Y(i)], 'b-')
4 | hold on
5 | pause(0.1)
6 | frame = getframe(gcf);
7 | imind = frame2im(frame);
8 | [imind, cm] = rgb2ind(imind, 256);
9 | if i == 2
10 | imwrite(imind, cm, 'test.gif', 'gif', 'Loopcount', inf, 'DelayTime', 1e-4);
11 | else
12 | imwrite(imind, cm, 'test.gif', 'gif', 'WriteMode', 'append', 'DelayTime', 1e-4);
13 | end
14 |
15 | end
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/G2D.m:
--------------------------------------------------------------------------------
1 | function D=G2D(G)
2 | l=size(G,1);
3 | D=zeros(l*l,l*l);
4 | for i=1:l
5 | for j=1:l
6 | if G(i,j)==0
7 | for m=1:l
8 | for n=1:l
9 | if G(m,n)==0
10 | im=abs(i-m);jn=abs(j-n);
11 | if im+jn==1||(im==1&&jn==1)
12 | D((i-1)*l+j,(m-1)*l+n)=(im+jn)^0.5;
13 | end
14 | end
15 | end
16 | end
17 | end
18 | end
19 | end
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/Magine.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/Magine.gif
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/main.m
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/test.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AC解决机器人路径规划/test.gif
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/DrawRoute.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/DrawRoute.m
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/TSP.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/TSP.gif
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/mian.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/mian.m
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/res.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Ant_Colony_Optimization/ACO_MatLab/AOC解决TSP问题/res.png
--------------------------------------------------------------------------------
/Ant_Colony_Optimization/README.md:
--------------------------------------------------------------------------------
1 |
AntColonyOptimization蚁群算法
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ------
10 |
11 | > 前言:本文主要围绕解决TSP旅行商问题展开,对于机器人的路线规划以及非线性方程求解的问题等解决方案大家可以直接参考[github源码地址](https://github.com/LiYangSir/SmartAlgorithm),
12 | > 对于一些其他优化算法例如遗传算法解决一些现实问题都有实现!! **欢迎小伙伴的star哦~~ 🤭**
13 |
14 | 先看一下效果图:
15 |
16 | **蚁群算法解决TSP问题:**
17 |
18 |

19 |
20 |
21 | **蚁群算法解决机器人路径规划问题:**
22 |
23 |

24 |
25 |
26 | ## 1、什么是蚁群算法
27 |
28 | ### 1.1、蚁群算法的来源
29 | 同遗传算法相似,都来自于大自然的启迪。蚁群算法就来自于蚂蚁寻找食物过程中发现路径的行为。
30 | 蚂蚁并没有视觉却可以寻找到食物,这得益于蚂蚁分泌的信息素,蚂蚁之间**相互独立**,彼此之间通过**信息素**进行交流,从而实现群体行为。
31 |
32 | ### 1.2、蚁群算法的基本原理
33 |
34 | 基本原理的过程就是蚂蚁觅食的过程。首先,蚂蚁在觅食的过程中会在路径上留下信息素的物质,并在寻找食物的过程中感知这种物质的强度,并指导自己的行为方向,他们总会朝着浓度高的方向前进。因此可以看得出来,蚂蚁觅食的过程是一个**正反馈**的过程,该路段经过的蚂蚁越多,信息素留下的就越多,浓度越高,更多的蚂蚁都会选择这个路段。
35 |
36 | ## 2、蚁群算法的实现原理
37 |
38 | ### 2.1、蚁群算法实现的重要规则(==细品==)
39 | **1. 避障规则**
40 | 如果蚂蚁要移动的方向有障碍物挡住,他会随机的选择另外一个方向,如果有信息素指引的话,会按照信息素的指引前进。
41 | **2. 散播信息素规则**
42 | 每只蚂蚁在刚找到食物的时候散发出来的信息素最多,并随着走选的距离,散播的信息越少。
43 | **3. 范围**
44 | 蚂蚁观察的范围有限,只能在局部的范围内进行选择。例如蚂蚁观察的范围为3\*3,那么它能够移动的范围也就是在这个3\*3区域内。
45 | **4. 移动规则**
46 | 前面也说过,蚂蚁的前进方向的选择依赖于信息素的浓度,回朝向信息素高的方向移动。当周围没有信息素或者信息素相同的时候,那么蚂蚁就会按照原来的方向继续前进,并且在前进方向上受到一个随机的扰动,为了避免再原地转圈,他会记住之前经过的点,下一次遇到的时候就会避开这个已经经过的点。
47 | **5. 觅食规则**
48 | 如果蚂蚁在感知范围内找到食物则直接过去,加速模型的收敛,否则朝着信息素高的方向前进,并且每只蚂蚁都有小概率的犯错误,从而不是信息素最多的点移动,打破局部最优解的情况。
49 | **6. 环境**
50 | 每只蚂蚁之间相互独立,他们依赖环境中的信息素进行交流。每只蚂蚁都仅仅能感知到环境内的信息。并且随机信息素会随着时间逐渐减少。如果这条路上经过的蚂蚁越来越少,那么信息素也会越来越少。
51 |
52 | ### 2.2、蚁群算法解决TSP问题的过程
53 |
54 | 旅行商问题(Traveling saleman problem, TSP)是物流配送的典型问题,他的求解有十分重要的理论和现实意义。
55 |
56 | 旅行商问题传统的解决方法都是遗传算法,但是遗传算法的收敛速度慢,具有一定的缺陷。
57 |
58 | 在求解TSP蚁群算法中,每只蚂蚁相互独立,用于构造不同的路线,蚂蚁之间通过信息素进行交流,合作求解。
59 |
60 | **基本过程如下:**
61 |
62 | 1. 初始化,设置迭代次数;
63 | 2. 将 ants 只蚂蚁放置到 cities 个城市上;
64 | 3. ants只蚂蚁按照概率函数选择下一个城市,并完成所有城市的周游;
65 | 4. 记录本次迭代的最优路线;
66 | 5. 全局更新信息素。
67 | 6. 终止。本例终止条件是迭代次数,也可以设置运行时间或最短路径的下限。
68 | 7. 输出结果
69 |
70 | 应用全局更新信息素来改变路径上信息素的值。当ants蚂蚁生成了ants个解,其中最短路径的是本代最优解,将属于这条路线上的所有关联的路线进行信息素更新。
71 |
72 | 之所以使用全局信息素,是为了让最优路径上有格外的信息素支持,这样后面的蚂蚁会优先选择这条路线。并且伴随着信息素的挥发,全局最短路径关联路线信息素得到进一步增强。
73 |
74 | ## 3、蚁群算法TSP程序实现
75 |
76 | ### 3.1、程序中矩阵大小以及含义
77 | **程序中矩阵说明**(首字母大写):
78 | |矩阵|大小|含义|
79 | |:---:|:---:|---|
80 | |Distance|(城市数量,城市数量)|表征各个城市之间的**距离**信息|
81 | |Eta|(城市数量,城市数量)|表征各个城市之间的**启发因子**|
82 | |Tau|(城市数量,城市数量)|表征各个城市之间**信息素**的值|
83 | |Route|(蚂蚁个数,城市数量)|每只蚂蚁周游城市的记录矩阵|
84 | |R_best|(迭代次数,城市数量)|每次迭代的最优路线|
85 | |L_best|(迭代次数,1)|每次迭代的最短距离|
86 | |L_ave|(迭代次数,1)|每次迭代的平均距离|
87 |
88 | ### 3.2、整体架构
89 |
90 | ```matlab
91 | '3.3、初始化变量参数'
92 | '3.4、初始化矩阵参数'
93 |
94 | while '迭代次数'
95 | '3.5、安排蚂蚁初始位置'
96 | '3.6、蚂蚁周游'
97 | '3.7、记录最优路线以及最短距离'
98 | '3.8、更新信息素'
99 | end
100 | '3.9、结果输出'
101 | ```
102 |
103 | ### 3.3、初始化变量参数
104 | 初始化主要对程序当中重要参数进行声明。
105 | **程序实现:**
106 | ```matlab
107 | % 随机产生40个城市的坐标
108 | position = 50 * randn(40, 2);
109 | epochs = 50; % 迭代次数
110 | % 蚂蚁个数最好大于等于城市个数,保证每个城市都有一个蚂蚁
111 | ants = 40;
112 | alpha = 1.4; % 表征信息素重要程度参数
113 | beta = 2.2; % 表征启发因子重要程度参数
114 | rho = 0.15; % 信息素挥发参数
115 | Q = 10^6; % 信息素增强系数
116 | cities = size(position, 1); % 城市个数
117 | ```
118 |
119 | ### 3.4、初始化矩阵参数
120 | 主要实现了重要矩阵声明以及初始化。
121 | **程序实现:**
122 | ```matlab
123 | % 城市之间的距离矩阵
124 | Distance = ones(cities, cities);
125 | for i = 1: cities
126 | for j = 1: cities
127 | if i ~= j
128 | % 坐标点欧氏距离
129 | Distance(i, j) = ((position(i, 1) - position(j, 1))^2 + (position(i, 2) - position(j, 2))^2)^0.5;
130 | else
131 | % 因为后面要取倒数,所以取一个浮点数精度大小
132 | Distance(i, j) = eps;
133 | end
134 | Distance(j, i) = Distance(i, j);
135 | end
136 | end
137 | % 启发因子矩阵
138 | Eta = 1./Distance;
139 | % 信息素初始值每个路线均相同为 1
140 | Tau = ones(cities, cities);
141 | % 每只蚂蚁的路线图
142 | Route = zeros(ants, cities);
143 | epoch = 1;
144 | % 记录每回合最优城市
145 | R_best = zeros(epochs, cities);
146 | % 记录每回合最短距离
147 | L_best = inf .* ones(epochs, 1);
148 | % 记录每回合平均距离
149 | L_ave = zeros(epochs, 1);
150 | ```
151 |
152 | ### 3.5、安排蚂蚁初始位置
153 | 主要是将所有的蚂蚁安置在所有的城市当中,蚂蚁个数 >= 城市个数。并且保证均匀分布。
154 | ```matlab
155 | % 初始随机位置
156 | RandPos = [];
157 | for i = 1: ceil(ants / cities)
158 | RandPos = [RandPos, randperm(cities)];
159 | end
160 | % 初始位置转置就对应了Route矩阵中每只蚂蚁的初始位置
161 | Route(:, 1) = (RandPos(1, 1:ants))';
162 | ```
163 | ### 3.6、蚂蚁周游
164 | 由于蚂蚁的初始位置已经确定,所有主要就是周游剩余的所有城市,循环(cities-1)次。里面的循环就是将所有的蚂蚁进行周游一次。
165 |
166 | 对于每只蚂蚁的周游主要是对剩余的城市进行周游,不能重复拜访同一个城市。NoVisited矩阵存储着该蚂蚁未访问的城市。然后在所有没有访问过城市中选择一个。选择的方式也是类似于轮盘赌法。概率函数表征信息素和启发因子,两者有着不同的重要程度。
167 | $$
168 | P = [\tau_{ij}(t)]^\alpha · [\eta_{ij}]^\beta
169 | $$
170 | 其中$\tau_{ij}(t)$为路线上$(i, j)$上的信息素浓度;$\eta_{ij}$为路线上$(i, j)$上的启发式信息;
171 | **程序实现:**
172 | ```matlab
173 | for j = 2: cities
174 | for i = 1: ants
175 | Visited = Route(i, 1:j-1);
176 | NoVisited = zeros(1, (cities - j + 1));
177 | P = NoVisited;
178 | num = 1;
179 | for k = 1: cities
180 | if length(find(Visited == k)) == 0
181 | NoVisited(num) = k;
182 | num = num + 1;
183 | end
184 | end
185 | for k = 1: length(NoVisited)
186 | P(k) = (Tau(Visited(end), NoVisited(k))^alpha) * (Eta(Visited(end), NoVisited(k))^beta);
187 | end
188 | P = P / sum(P);
189 | Pcum = cumsum(P);
190 | select = find(Pcum >= rand);
191 | to_visit = NoVisited(select(1));
192 | Route(i, j) = to_visit;
193 | end
194 | end
195 | ```
196 | ### 3.7、记录最优路线以及最短距离
197 | 计算每个回合每只蚂蚁走过的距离。并记录该回合最短路径,最短距离和平均距离。
198 | ```matlab
199 | Distance_epoch = zeros(ants, 1);
200 | for i = 1: ants
201 | R = Route(i, :);
202 | for j = 1: cities - 1
203 | Distance_epoch(i) = Distance_epoch(i) + Distance(R(j), R(j + 1));
204 | end
205 | Distance_epoch(i) = Distance_epoch(i) + Distance(R(1), R(cities));
206 | end
207 | L_best(epoch) = min(Distance_epoch);
208 | pos = find(Distance_epoch == L_best(epoch));
209 | R_best(epoch, :) = Route(pos(1), :);
210 | L_ave(epoch) = mean(Distance_epoch);
211 | epoch = epoch + 1;
212 | ```
213 |
214 | ### 3.8、更新信息素
215 | 更新信息素主要保证获得最优距离的那条路线的信息素得到最大的增强。
216 | ```matlab
217 | Delta_Tau = zeros(cities, cities);
218 | for i = 1: ants
219 | for j = 1: (cities - 1)
220 | Delta_Tau(Route(i, j), Route(i, j + 1)) = Delta_Tau(Route(i, j), Route(i, j + 1)) + Q / Distance_epoch(i);
221 | end
222 | Delta_Tau(Route(i, 1), Route(i, cities)) = Delta_Tau(Route(i, 1), Route(i, cities)) + Q / Distance_epoch(i);
223 | end
224 | Tau = (1 - rho) .* Tau + Delta_Tau;
225 | Route = zeros(ants, cities);
226 | ```
227 | ### 3.9、结果输出
228 | 迭代完成后,在R_best矩阵中得到最短路径的最小路线,最后输出最优的结果。
229 | **结果输出实现:**
230 | ```matlab
231 | Pos = find(L_best == min(L_best));
232 | Short_Route = R_best(Pos(1), :);
233 | Short_Length = L_best(Pos(1), :);
234 | figure
235 | subplot(121);
236 | DrawRoute(position, Short_Route);
237 | subplot(122);
238 | plot(L_best);
239 | hold on
240 | plot(L_ave, 'r');
241 | title('平均距离和最短距离');
242 | ```
243 | **画图函数实现:**
244 | ```matlab
245 | function DrawRoute(C, R)
246 | N = length(R);
247 | scatter(C(:, 1), C(:, 2));
248 | hold on
249 | plot([C(R(1), 1), C(R(N), 1)], [C(R(1), 2), C(R(N), 2)], 'g');
250 | hold on
251 | for ii = 2: N
252 | plot([C(R(ii - 1), 1), C(R(ii), 1)], [C(R(ii - 1), 2), C(R(ii), 2)], 'g');
253 | hold on
254 | end
255 | title('旅行商规划');
256 | ```
257 | ## 4、结果
258 |
259 |

260 |
261 |
262 | > 为了说明方便将代码直接拆开展示,如果想要全部的代码欢迎大家直接到 [Github源码](https://github.com/LiYangSir/SmartAlgorithm/tree/master/Ant_Colony_Optimization/ACO_MatLab)
263 |
264 | ## 最后
265 |
266 | 更多精彩内容,大家可以转到我的主页:[曲怪曲怪的主页](http://quguai.cn/)
267 |
268 | **源码地址**:[github地址](https://github.com/LiYangSir/SmartAlgorithm)
269 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_Java/Chromosome.java:
--------------------------------------------------------------------------------
1 | import javax.print.DocFlavor;
2 | import java.util.ArrayList;
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | public class Chromosome {
7 | private boolean[] gene;
8 | private double score;
9 |
10 | public Chromosome() {
11 | }
12 |
13 | public Chromosome(int size) {
14 | if (size <= 0)
15 | return;
16 | gene = new boolean[size];
17 | for (int i = 0; i < size; i++)
18 | gene[i] = Math.random() >= 0.5;
19 | }
20 |
21 | public static Chromosome clone(Chromosome chromosome) {
22 | if (chromosome == null || chromosome.gene == null)
23 | return null;
24 | Chromosome copy = new Chromosome();
25 | copy.gene = new boolean[chromosome.gene.length];
26 | copy.score = chromosome.score;
27 | System.arraycopy(chromosome.gene, 0, copy.gene, 0, chromosome.gene.length);
28 | return copy;
29 | }
30 |
31 | /**
32 | * 交叉操作
33 | * @param p1:交叉对象1
34 | * @param p2:交叉对象2
35 | * @return 交叉后的对象
36 | */
37 | public static List genetic(Chromosome p1, Chromosome p2, double crossRate) {
38 | if (p1 == null ||p2 == null)
39 | return null;
40 | if (p1.gene == null || p2.gene == null) {
41 | return null;
42 | }
43 | if (p1.gene.length != p2.gene.length) {
44 | return null;
45 | }
46 |
47 | Chromosome c1 = clone(p1);
48 | Chromosome c2 = clone(p2);
49 | if (Math.random() < crossRate) {
50 | int size = c1.gene.length;
51 | int roundA = (int)(Math.random() * size);
52 | int roundB = (int)(Math.random() * size);
53 |
54 | int max = Math.max(roundA, roundB);
55 | int min = Math.min(roundA, roundB);
56 |
57 | for (int i = min; i <= max; i++) {
58 | boolean temp = c1.gene[i];
59 | c1.gene[i] = c2.gene[i];
60 | c2.gene[i] = temp;
61 | }
62 | }
63 | List chromosomes = new ArrayList<>();
64 | chromosomes.add(c1);
65 | chromosomes.add(c2);
66 | return chromosomes;
67 | }
68 |
69 | public void mutation(int num) {
70 | if (num == 0)
71 | return;
72 | int size = gene.length;
73 | for (int i = 0; i < num; i++) {
74 | int at = (int)(Math.random() * size) % size;
75 | gene[at] = !gene[at];
76 | }
77 |
78 | }
79 |
80 | public int binary2dec() {
81 | if (gene == null)
82 | return 0;
83 | int num = 0;
84 | for (boolean b : gene) {
85 | num <<= 1;
86 | if (b)
87 | num++;
88 | }
89 | return num;
90 | }
91 |
92 | public boolean[] getGene() {
93 | return gene;
94 | }
95 |
96 | public void setGene(boolean[] gene) {
97 | this.gene = gene;
98 | }
99 |
100 | public double getScore() {
101 | return score;
102 | }
103 |
104 | public void setScore(double score) {
105 | this.score = score;
106 | }
107 |
108 | @Override
109 | public String toString() {
110 | return "Chromosome{" +
111 | "gene=" + Arrays.toString(gene) +
112 | ", score=" + score +
113 | '}';
114 | }
115 |
116 | public static void main(String[] args) {
117 | Chromosome chromosome = new Chromosome();
118 | chromosome.gene = new boolean[]{false, true, false, false};
119 | System.out.println(chromosome.binary2dec());
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_Java/GeneticAlgorithm.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | public abstract class GeneticAlgorithm {
5 | private List population = new ArrayList<>();
6 | private int popSize = 100;//种群数量
7 | private int geneSize;//基因最大长度
8 | private int maxIterNum = 500;//最大迭代次数
9 | private double crossRate = 0.6;
10 | private double mutationRate = 0.01;//基因变异的概率
11 | private int maxMutationNum = 3;//最大变异次数
12 |
13 | private int generation = 1;//当前遗传到第几代
14 |
15 | private double bestScore;//最好得分 局部
16 | private double worstScore;//最坏得分 局部
17 | private double totalScore;//总得分 局部
18 | private double averageScore;//平均得分
19 |
20 | private double x; //记录历史种群中最好的X值
21 | private double y; //记录历史种群中最好的Y值
22 | private int geneI;//x y所在代数
23 |
24 | public GeneticAlgorithm(int geneSize) {
25 | this.geneSize = geneSize;
26 | }
27 |
28 | public void calculate(){
29 | generation = 1;
30 | init();
31 | while (generation < maxIterNum) { //迭代maxIterNum
32 | evolve(); // (选择 -> 交叉)+ -> 变异 -> 计算得分
33 | print(); // 打印
34 | generation++; // 代数
35 | }
36 | }
37 |
38 | private void evolve() {
39 | List childPopulation = new ArrayList<>();
40 | while (childPopulation.size() < popSize) {
41 | Chromosome p1 = getParentChromosome();
42 | Chromosome p2 = getParentChromosome();
43 | List chromosomes = Chromosome.genetic(p1, p2, crossRate);
44 | if (chromosomes != null)
45 | childPopulation.addAll(chromosomes);
46 | }
47 | List t = population;
48 | population = childPopulation;
49 | t.clear();
50 | t = null;
51 | mutation();
52 | calculateScore();
53 | }
54 |
55 | private void init(){
56 | population = new ArrayList<>();
57 | for (int i = 0; i < popSize; i++) {
58 | Chromosome chromosome = new Chromosome(geneSize);
59 | population.add(chromosome);
60 | }
61 | calculateScore();
62 | }
63 |
64 | /**
65 | * 选择过程:轮盘赌法
66 | * @return
67 | */
68 | private Chromosome getParentChromosome() {
69 | double slide = Math.random() * totalScore;
70 | double sum = 0;
71 | for (Chromosome chromosome : population) {
72 | sum += chromosome.getScore();
73 | if (slide < sum && chromosome.getScore() >= averageScore)
74 | return chromosome;
75 | }
76 | return null;
77 | }
78 |
79 | private void calculateScore() {
80 | setChromosomeScore(population.get(0));
81 | bestScore = population.get(0).getScore();
82 | worstScore = population.get(0).getScore();
83 | totalScore = 0;
84 | for (Chromosome chromosome : population) {
85 | setChromosomeScore(chromosome);
86 | if (chromosome.getScore() > bestScore) {
87 | bestScore = chromosome.getScore();
88 | if (y < bestScore) {
89 | x = changeX(chromosome);
90 | y = bestScore;
91 | geneI = geneSize;
92 | }
93 | }
94 | if (chromosome.getScore() < worstScore)
95 | worstScore = chromosome.getScore();
96 | totalScore += chromosome.getScore();
97 | }
98 | averageScore = totalScore / popSize;
99 | averageScore = Math.min(averageScore, bestScore);
100 | }
101 |
102 | private void mutation() {
103 | for (Chromosome chromosome : population) {
104 | if (Math.random() < mutationRate)
105 | chromosome.mutation((int) (Math.random() * maxMutationNum)); //变异次数
106 |
107 | }
108 | }
109 |
110 | private void setChromosomeScore(Chromosome chromosome) {
111 | if (chromosome == null) {
112 | return;
113 | }
114 | double x = changeX(chromosome);
115 | double y = calculateY(x);
116 | chromosome.setScore(y);
117 | }
118 |
119 | private void print() {
120 | System.out.println("--------------------------------");
121 | System.out.println("the generation is:" + generation);
122 | System.out.println("the best y is:" + bestScore);
123 | System.out.println("the worst fitness is:" + worstScore);
124 | System.out.println("the average fitness is:" + averageScore);
125 | System.out.println("the total fitness is:" + totalScore);
126 | System.out.println("geneI:" + geneI + "\tx:" + x + "\ty:" + y);
127 | }
128 |
129 | public abstract double calculateY(double x);
130 |
131 | public abstract double changeX(Chromosome chromosome);
132 |
133 | public List getPopulation() {
134 | return population;
135 | }
136 |
137 | public void setPopulation(List population) {
138 | this.population = population;
139 | }
140 |
141 | public int getPopSize() {
142 | return popSize;
143 | }
144 |
145 | public void setPopSize(int popSize) {
146 | this.popSize = popSize;
147 | }
148 |
149 | public int getGeneSize() {
150 | return geneSize;
151 | }
152 |
153 | public void setGeneSize(int geneSize) {
154 | this.geneSize = geneSize;
155 | }
156 |
157 | public int getMaxIterNum() {
158 | return maxIterNum;
159 | }
160 |
161 | public void setMaxIterNum(int maxIterNum) {
162 | this.maxIterNum = maxIterNum;
163 | }
164 |
165 | public double getMutationRate() {
166 | return mutationRate;
167 | }
168 |
169 | public void setMutationRate(double mutationRate) {
170 | this.mutationRate = mutationRate;
171 | }
172 |
173 | public int getMaxMutationNum() {
174 | return maxMutationNum;
175 | }
176 |
177 | public void setMaxMutationNum(int maxMutationNum) {
178 | this.maxMutationNum = maxMutationNum;
179 | }
180 |
181 | public int getGeneration() {
182 | return generation;
183 | }
184 |
185 | public void setGeneration(int generation) {
186 | this.generation = generation;
187 | }
188 |
189 | public double getBestScore() {
190 | return bestScore;
191 | }
192 |
193 | public void setBestScore(double bestScore) {
194 | this.bestScore = bestScore;
195 | }
196 |
197 | public double getWorstScore() {
198 | return worstScore;
199 | }
200 |
201 | public void setWorstScore(double worstScore) {
202 | this.worstScore = worstScore;
203 | }
204 |
205 | public double getTotalScore() {
206 | return totalScore;
207 | }
208 |
209 | public void setTotalScore(double totalScore) {
210 | this.totalScore = totalScore;
211 | }
212 |
213 | public double getAverageScore() {
214 | return averageScore;
215 | }
216 |
217 | public void setAverageScore(double averageScore) {
218 | this.averageScore = averageScore;
219 | }
220 |
221 | public double getX() {
222 | return x;
223 | }
224 |
225 | public void setX(double x) {
226 | this.x = x;
227 | }
228 |
229 | public double getY() {
230 | return y;
231 | }
232 |
233 | public void setY(double y) {
234 | this.y = y;
235 | }
236 |
237 | public int getGeneI() {
238 | return geneI;
239 | }
240 |
241 | public void setGeneI(int geneI) {
242 | this.geneI = geneI;
243 | }
244 | }
245 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_Java/GeneticAlgorithmTest.java:
--------------------------------------------------------------------------------
1 | public class GeneticAlgorithmTest extends GeneticAlgorithm {
2 |
3 | private static final int NUM = 1 << 24;
4 |
5 | public GeneticAlgorithmTest() {
6 | super(24);
7 | }
8 |
9 | /**
10 | * 函数值
11 | * @param x
12 | * @return
13 | */
14 | @Override
15 | public double calculateY(double x) { // "10*sin(5*x)+7*abs(x-5)+10"
16 | return 10.0 * Math.sin(5.0 * x) + 7.0 * Math.abs(x - 5) + 10;
17 | }
18 |
19 | /**
20 | * 根据基因序列转换成x轴得值
21 | * @param chromosome 基因序列
22 | * @return x轴的值
23 | */
24 | @Override
25 | public double changeX(Chromosome chromosome) {
26 | return ((1.0 * chromosome.binary2dec() / NUM) * 10);
27 | }
28 |
29 | public static void main(String[] args) {
30 | GeneticAlgorithmTest test = new GeneticAlgorithmTest();
31 | test.calculate();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法工具箱/Test.m:
--------------------------------------------------------------------------------
1 | clear
2 | clc
3 | A = [1 1; -1 2; 2 1];
4 | b = [2; 2; 3];
5 | lb = zeros(2, 1);
6 | [x, fval, exitflag] = ga(@lincontest6, 2, A, b, [], [], lb);
7 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法工具箱/ga44.m:
--------------------------------------------------------------------------------
1 | function y = ga44(x)
2 | y = 1 - 0.1 * (sin(x(1)^2 + x(2)) - 0.1) / (x(1)^2 + x(2)^2);
3 | end
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/cross.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/cross.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/exchange.m:
--------------------------------------------------------------------------------
1 | function [x, y] = exchange(x, y)
2 | temp = x;
3 | x = y;
4 | y = temp;
5 | end
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/fit.m:
--------------------------------------------------------------------------------
1 | function fitness = fit(len, m, maxlen, minlen)
2 | fitness = len;
3 | for i = 1:length(len)
4 | fitness(i, 1) = (1 - (len(i)-minlen)/(maxlen-minlen+0.0001)).^m;
5 | end
6 | end
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/main.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/mutation.m:
--------------------------------------------------------------------------------
1 | function chromosome = mutation(chromosome)
2 | nnper = randperm(size(chromosome, 2));
3 | index1 = nnper(1);
4 | index2 = nnper(2);
5 | temp = chromosome(index1);
6 | chromosome(index1) = chromosome(index2);
7 | chromosome(index2) = temp;
8 | end
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/myLength.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/myLength.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/plot_route.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/plot_route.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决TSP问题/reverse.m:
--------------------------------------------------------------------------------
1 | function chromosome = reverse(chromosome, distance)
2 | [row, col] = size(chromosome);
3 | ObjV = myLength(distance, chromosome);
4 | chromosome1 = chromosome;
5 | for i = 1: row
6 | r1 = randsrc(1, 1, [1:col]);
7 | r2 = randsrc(1, 1, [1:col]);
8 | mininverse = min([r1, r2]);
9 | maxinverse = max([r1, r2]);
10 | chromosome1(1, mininverse:maxinverse) = chromosome1(i, maxinverse:-1:mininverse);
11 | end
12 | ObjV1 = myLength(distance, chromosome1);
13 | if ObjV1 < ObjV
14 | chromosome = chromosome1;
15 | end
16 | end
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/README.md:
--------------------------------------------------------------------------------
1 | 优化算法之遗传算法
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | -----
10 |
11 | [TOC]
12 |
13 | ## 1、什么是遗传算法
14 |
15 | 我们了解过深度学习的都知道,我们在进行网络优化的过程都是通过反向传播求导进行参数的不断优化,而这种类型的优化参数采用前向传播的方式继续优化网络,不断找出最优解,或者最优的参数。很多的优化算法都来自于大自然的启发,来一种算法叫做蚁群算法,灵感就是来自于蚂蚁,所以观察大自然有时也是灵感的来源。
16 |
17 | 遗传算法,也叫Genetic Algorithm,简称 GA 算法他既然叫遗传算法,那么遗传之中必然有基因,那么基因染色体(Chromosome)就是它的需要调节的参数。我们在生物中了解到,大自然的法则是“物竞天择,适者生存”,我觉得遗传算法更适用于“**优胜劣汰**”。
18 | + 优:最优解,
19 | + 劣:非最优解。
20 |
21 | ## 2、遗传算法名词解释
22 |
23 | 下面主要通过疑问提问题的方式进行解释遗传算法当中的适应度函数、选择、交叉、变异这几个名词。
24 |
25 | **1. 都知道优胜劣汰,那怎么实现优胜劣汰呢?**
26 | 很重要的一个环节就是**选择**,也称之为“大自然的选择”,大自然怎么选择呢,大自然会抛弃掉一些适应能力差的,在程序当中就是离最优解较远的解,会被抛弃掉。
27 |
28 | **2. 如何实现大自然的选择呢?**
29 | 这里我们会引入轮盘赌法,进行大自然的选择。选择一些离最优解较近的个体。还有一些其他的经典的选择办法,例如锦标赛法进行选择。
30 |
31 | **3. 只靠选择就可以实现吗?那样会不会陷入局部最优解?**
32 | 如果只靠选择进行调优,那么最终的结果会受到初始种群的影响,只是在初始种群的群体中进行选择,得出的最优解也是在初始群体中的最优解。所以就需要引入大自然当中的“啪啪啪”,也叫**交叉**。正所谓“龙生龙,凤生风,老鼠生下来就会打洞”,所以说两个优秀的基因进行交叉可以将两者优秀的基因遗传给一代,也增加了群体的基因多样性,但这种不一定就是最好的,也可能发生“夭折”。
33 |
34 | **4. 大自然的选择好像不仅如此,还有变异吧?**
35 | 为了更好的模拟大自然的选择规律,来需要进入**变异**,变异发生的概率很低,但也是增加群体多样性的条件,和交叉相同,变异求解出来的不一定是最好的解,也会出现“夭折”。
36 |
37 | **5. 上面只是大自然的规则,那么大自然的环境又是什么呢?**
38 | 优秀的基因并不是独立的,就像北极熊不会存活在热带雨林一样。只有适合环境的基因才是优秀的,所以说基因具有相对性,环境是挑选基因的先决条件,这里的环境就是**适应度函数**。个体用过适应度函数后得到的结果越大,表明更加适合这里的环境,那么保留下来的概率越大。反之则越小。
39 |
40 | ## 3、遗传算法的程序实现
41 |
42 | 正所谓 “不结合代码的解释都是** ” 。下面结合代码来梳理遗传算法的实现。
43 |
44 |

45 |
46 |
47 | 涉及到还是适应度函数、选择、交叉、变异这几个模块。下面就这几个模块展开说明。具体的流程图解释如下:
48 | 1. 需要先对初始种群进行一次**适应度函数**进行计算,这样方便我们对个体进行选择,适应度值越大的越容易被保留;
49 | 2. 对群体进行**选择**,选择出适应度值较大的一部分优势群体;
50 | 3. 对优势种群进行 “**交配**”,更容易产生优秀的个体;
51 | 4. 模拟大自然**变异**操作,对染色体个体进行变异操作;
52 |
53 | 下面以计算函数最大值
54 | $$
55 | f(x)=10\times sin(5\times x)+7\times \left|x-5\right|+10; x\in[0, 10]
56 | $$
57 | ### 3.1、种群初始化
58 | 种群的初始化相对简单,只需要随机生成一个二维矩阵,矩阵的**size=(种群大小,染色体编码长度)**。染色体编码采用二进制编码的方式。染色体编码并不是直接采用将[0, 10]直接转换为二进制,原因如下:
59 |
60 | + 并非均匀分布,10的二进制表示为1010,会导致出现空余位置,例如11、12等没有意义的数字出现
61 | + 精度低,如果直接编码最小增量单位变成了 1 ,没有了浮点数的表示,最优解很多情况都会出现在浮点数的表示范围。n:代表染色体编码的长度
62 |
63 | $$
64 | x = \dfrac{染色体编码对应的十进制值}{2^n - 1}
65 | $$
66 | 此时x的范围为[0, 1],我们可以根据待测得x轴的范围进行偏移计算。例如:x得范围为[2, 10],则设计:
67 |
68 | $$
69 | x = \dfrac{染色体编码对应的十进制值}{2^n - 1} \times 8 + 2
70 | $$
71 | 种群初始化基本结构如下,实数范围还需要进一步计算得到真正得x轴的浮点值。
72 |
73 |

74 |
75 | ```matlab
76 | % popsize: 种群个数
77 | % chromlength: 染色体长度
78 | function pop=initpop(popsize,chromlength)
79 | % round:产生的随机数进行四舍五入操作就是0或者1
80 | pop = round(rand(popsize,chromlength));
81 | ```
82 |
83 | ### 3.2、适应度函数设计
84 | 适应度函数得出的值越大表明个体越优秀,所以一般情况下,在求解函数最大值的时候,适应度函数就是求解函数本身,求解最小值的时候适应度函数就是函数的倒数。在本例中求取最大值,所以适应度函数就是函数本身。
85 | ```matlab
86 | function [objvalue] = cal_objvalue(pop)
87 | x = binary2decimal(pop);
88 | objvalue=10*sin(5*x)+7*abs(x-5)+10;
89 |
90 | % 二进制转10进制并转换到对应的x轴浮点值
91 | function pop2 = binary2decimal(pop)
92 | [px,py]=size(pop);
93 | for i = 1:py
94 | pop1(:,i) = 2.^(py-i).*pop(:,i);
95 | end
96 | temp = sum(pop1,2);
97 | pop2 = temp*10/1023; % 限制到[0, 10]
98 | ```
99 |
100 | ### 3.3、选择
101 | 我们在前面已经说明了选择的原因(挑选优秀个体),挑选的算法有很多,我们这里选择“轮盘赌法”。轮盘赌法就是类似于我们玩的转盘,圆心角度越大的我们越容易选中。
102 | **注:** 选择后后的个体数目和原种群个数相同。
103 |
104 |
105 |

106 |
107 |
108 | 大自然就像那个指针,适应度值越大,表明这个体约适应这个环境,那么被选择的概率越大,与此同时,适应度值小的个体并不代表不会被选中,只是选中的概率小,一方面也保证了正负样本的一个均衡。
109 | ```matlab
110 | % pop: 遗传算法的种群
111 | % fitvalue: 种群的适应度值
112 | % newpop: 返回筛选过后的新的种群
113 | function [newpop] = selection(pop,fitvalue)
114 | [px,py] = size(pop);
115 | totalfit = sum(fitvalue);
116 | % 将适应度值转换为概率,适应度值越大表明概率越大
117 | p_fitvalue = fitvalue/totalfit;
118 | % 沿梯度进行求和运算 [0.1, 0.3, 0.6] ->[0.1, 0.4, 1]
119 | p_fitvalue = cumsum(p_fitvalue);
120 | % ms相当于指针,得出落在哪一个区域,就表明这个基因被选中
121 | ms = sort(rand(px,1)); % 先进行排序,减小时间复杂度
122 | fitin = 1; % 适应度矩阵的索引
123 | newin = 1; % 新种群索引
124 | while newin<=px
125 | if(ms(newin))
138 |
139 |
140 |
141 | **随机距离交叉(本例实现):**
142 |
143 |

144 |
145 |
146 | **程序实现:**
147 | ```matlab
148 | % pop:总种群
149 | % pc:交叉概率
150 | function [newpop] = crossover(pop,pc)
151 | [px,py] = size(pop);
152 | newpop = ones(size(pop));
153 | % 每两个进行一次交叉
154 | for i = 1:2:px-1
155 | if(rand
169 |
170 |
171 |
172 | **程序实现:**
173 | ```matlab
174 | % pop: 总种群
175 | % pm: 变异概率
176 | function [newpop] = mutation(pop,pm)
177 | [px,py] = size(pop);
178 | newpop = ones(size(pop));
179 | for i = 1:px
180 | if(rand
198 |
199 |
200 |
201 | **程序实现:**
202 | ```matlab
203 | clear;
204 | clc;
205 | % 总种群数量
206 | popsize=100;
207 | % 染色体长度
208 | chromlength=10;
209 | % 交叉概率
210 | pc = 0.6;
211 | % 变异概率
212 | pm = 0.001;
213 | %初始化种群
214 | pop = initpop(popsize,chromlength); % 100 * 10
215 |
216 | for i = 1:100
217 | objvalue = cal_objvalue(pop);
218 | fitvalue = objvalue;
219 | newpop = selection(pop,fitvalue);
220 | newpop = crossover(newpop,pc);
221 | newpop = mutation(newpop,pm);
222 | pop = newpop;
223 | [bestindividual,bestfit] = best(pop,fitvalue);
224 | x2 = binary2decimal(bestindividual); % 最优解 x 值
225 | x1 = binary2decimal(newpop);
226 | y1 = cal_objvalue(newpop);
227 | if mod(i,20) == 0
228 | figure;
229 | fplot(@(x)10*sin(5*x)+7*abs(x-5)+10,[0 10]);
230 | hold on;
231 | plot(x1,y1,'*');
232 | title(['迭代次数:%d' num2str(i)]);
233 | end
234 | end
235 | fprintf('The best X is --->>%5.2f\n',x2);
236 | fprintf('The best Y is --->>%5.2f\n',bestfit);
237 | ```
238 |
239 | ## 4、运行结果展示
240 |
241 |

242 |
243 |
244 | ## 总结
245 |
246 | 遗传算法同样会陷入局部最优解的情况,例如下面的情况:
247 |
248 |

249 |
250 |
251 | 解决局部最优解的方法有很多,小伙伴可以自行百度,我这里提供一种方法叫做非线性寻优,利用matlab自带函数fmincon进行非线性寻优。
252 |
253 | ----
254 |
255 | ## 最后
256 |
257 | 更多精彩内容,大家可以转到我的主页:[曲怪曲怪的主页](http://quguai.cn/)
258 | **源码地址**:[github地址]()
259 |
260 |
261 |
262 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/best.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/best.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/binary2decimal.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/binary2decimal.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/cal_objvalue.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/cal_objvalue.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/crossover.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/crossover.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/initpop.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/initpop.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/main.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/mutation.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/mutation.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/selection.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Genetic_Algorithm/GA_MatLab/GA遗传算法解决非线性最优解/selection.m
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_Python/GA_Test.py:
--------------------------------------------------------------------------------
1 | from GA遗传算法.Population import Population
2 | import numpy as np
3 |
4 | cross_rate = 0.6
5 | mutation_rate = 0.001
6 | pop_size = 100
7 | chromosome_size = 10
8 | population = Population(100, 10)
9 |
10 | for i in range(100):
11 | population.cal_obj_value()
12 | population.select_chromosome()
13 | population.cross_chromosome(cross_rate)
14 | population.mutation_chromosome(mutation_rate)
15 | best_individual, best_fit = population.best()
16 | best_individual = np.expand_dims(best_individual, 0)
17 | x = population.binary2decimal(best_individual)
18 | print("X:", x, "\t Y: ", best_fit)
19 |
--------------------------------------------------------------------------------
/Genetic_Algorithm/GA_Python/Population.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | class Population:
5 |
6 | def __init__(self, pop_size, chromosome_size):
7 | self.pop_size = pop_size
8 | self.chromosome_size = chromosome_size
9 | self.population = np.round(np.random.rand(pop_size, chromosome_size)).astype(np.int)
10 | self.fit_value = np.zeros((pop_size, 1))
11 |
12 | def select_chromosome(self):
13 | total_fitness_value = self.fit_value.sum()
14 | p_fit_value = self.fit_value/total_fitness_value
15 | p_fit_value = np.cumsum(p_fit_value)
16 | point = np.sort(np.random.rand(self.pop_size, 1), 0)
17 | fit_in = 0
18 | new_in = 0
19 | new_population = np.zeros_like(self.population)
20 | while new_in < self.pop_size:
21 | if point[new_in] < p_fit_value[fit_in]:
22 | new_population[new_in, :] = self.population[fit_in, :]
23 | new_in += 1
24 | else:
25 | fit_in += 1
26 | self.population = new_population
27 |
28 | def cross_chromosome(self, cross_rate):
29 | x = self.pop_size
30 | y = self.chromosome_size
31 | new_population = np.zeros_like(self.population)
32 | for i in range(0, x-1, 2):
33 | if np.random.rand(1) < cross_rate:
34 | insert_point = int(np.round(np.random.rand(1) * y).item())
35 | new_population[i, :] = np.concatenate([self.population[i, 0:insert_point], self.population[i+1, insert_point:y]], 0)
36 | new_population[i+1, :] = np.concatenate([self.population[i+1, 0:insert_point], self.population[i, insert_point:y]], 0)
37 | else:
38 | new_population[i, :] = self.population[i, :]
39 | new_population[i + 1, :] = self.population[i + 1, :]
40 | self.population = new_population
41 |
42 | def best(self):
43 | best_individual = self.population[0, :]
44 | best_fit = self.fit_value[0]
45 | for i in range(1, self.pop_size):
46 | if self.fit_value[i] > best_fit:
47 | best_individual = self.population[i, :]
48 | best_fit = self.fit_value[i]
49 | return best_individual, best_fit
50 |
51 | def mutation_chromosome(self, mutation_rate):
52 | x = self.pop_size
53 | for i in range(x):
54 | if np.random.rand(1) < mutation_rate:
55 | m_point = int(np.round(np.random.rand(1) * self.chromosome_size).item())
56 | if self.population[i, m_point] == 1:
57 | self.population[i, m_point] = 0
58 | else:
59 | self.population[i, m_point] = 1
60 |
61 | def binary2decimal(self, population):
62 | pop1 = np.zeros_like(population)
63 | y = self.chromosome_size
64 | for i in range(y):
65 | pop1[:, i] = 2 ** (y - i - 1) * population[:, i]
66 | pop = np.sum(pop1, 1)
67 | pop2 = pop * 10/(1 << y)
68 | return pop2
69 |
70 | def cal_obj_value(self):
71 | x = self.binary2decimal(self.population)
72 | self.fit_value = 10 * np.sin(5 * x) + 7 * np.abs(x - 5) + 10
73 |
74 |
75 | if __name__ == "__main__":
76 | pop = Population(10, 3)
77 | a = np.random.rand(1, 1)
78 | b = np.random.rand(1, 2)
79 | c = np.concatenate([a, b], 1)
80 | print(c)
81 | point = np.random.rand(10, 1)
82 | point = np.sort(point, 0)
83 | print(point)
--------------------------------------------------------------------------------
/Genetic_Algorithm/README.md:
--------------------------------------------------------------------------------
1 | 智能算法之Genetic Algorithm遗传算法
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | -----
11 | > 前言:本文主要围绕 Matlab 的实现展开,Java版本以及Python版本参考文章最后的源码地址,MatLab和python实现大致相同,Java较为不同。
12 |
13 |
14 | ## 1、什么是遗传算法
15 |
16 | 我们了解过深度学习的都知道,我们在进行网络优化的过程都是通过反向传播求导进行参数的不断优化,而这种类型的优化参数采用前向传播的方式继续优化网络,不断找出最优解,或者最优的参数。很多的优化算法都来自于大自然的启发,来一种算法叫做蚁群算法,灵感就是来自于蚂蚁,所以观察大自然有时也是灵感的来源。
17 |
18 | 遗传算法,也叫Genetic Algorithm,简称 GA 算法他既然叫遗传算法,那么遗传之中必然有基因,那么基因染色体(Chromosome)就是它的需要调节的参数。我们在生物中了解到,大自然的法则是“物竞天择,适者生存”,我觉得遗传算法更适用于“**优胜劣汰**”。
19 | + 优:最优解,
20 | + 劣:非最优解。
21 |
22 | ## 2、遗传算法名词解释
23 |
24 | 下面主要通过疑问提问题的方式进行解释遗传算法当中的适应度函数、选择、交叉、变异这几个名词。
25 |
26 | **1. 都知道优胜劣汰,那怎么实现优胜劣汰呢?**
27 | 很重要的一个环节就是**选择**,也称之为“大自然的选择”,大自然怎么选择呢,大自然会抛弃掉一些适应能力差的,在程序当中就是离最优解较远的解,会被抛弃掉。
28 |
29 | **2. 如何实现大自然的选择呢?**
30 | 这里我们会引入轮盘赌法,进行大自然的选择。选择一些离最优解较近的个体。还有一些其他的经典的选择办法,例如锦标赛法进行选择。
31 |
32 | **3. 只靠选择就可以实现吗?那样会不会陷入局部最优解?**
33 | 如果只靠选择进行调优,那么最终的结果会受到初始种群的影响,只是在初始种群的群体中进行选择,得出的最优解也是在初始群体中的最优解。所以就需要引入大自然当中的“啪啪啪”,也叫**交叉**。正所谓“龙生龙,凤生风,老鼠生下来就会打洞”,所以说两个优秀的基因进行交叉可以将两者优秀的基因遗传给一代,也增加了群体的基因多样性,但这种不一定就是最好的,也可能发生“夭折”。
34 |
35 | **4. 大自然的选择好像不仅如此,还有变异吧?**
36 | 为了更好的模拟大自然的选择规律,来需要进入**变异**,变异发生的概率很低,但也是增加群体多样性的条件,和交叉相同,变异求解出来的不一定是最好的解,也会出现“夭折”。
37 |
38 | **5. 上面只是大自然的规则,那么大自然的环境又是什么呢?**
39 | 优秀的基因并不是独立的,就像北极熊不会存活在热带雨林一样。只有适合环境的基因才是优秀的,所以说基因具有相对性,环境是挑选基因的先决条件,这里的环境就是**适应度函数**。个体用过适应度函数后得到的结果越大,表明更加适合这里的环境,那么保留下来的概率越大。反之则越小。
40 |
41 | ## 3、遗传算法的程序实现
42 |
43 | 正所谓 “不结合代码的解释都是** ” 。下面结合代码来梳理遗传算法的实现。
44 |
45 |

46 |
47 |
48 | 涉及到还是适应度函数、选择、交叉、变异这几个模块。下面就这几个模块展开说明。具体的流程图解释如下:
49 | 1. 需要先对初始种群进行一次**适应度函数**进行计算,这样方便我们对个体进行选择,适应度值越大的越容易被保留;
50 | 2. 对群体进行**选择**,选择出适应度值较大的一部分优势群体;
51 | 3. 对优势种群进行 “**交配**”,更容易产生优秀的个体;
52 | 4. 模拟大自然**变异**操作,对染色体个体进行变异操作;
53 |
54 | 下面以计算函数最大值
55 | $$
56 | f(x)=10\times sin(5\times x)+7\times \left|x-5\right|+10; x\in[0, 10]
57 | $$
58 | ### 3.1、种群初始化
59 | 种群的初始化相对简单,只需要随机生成一个二维矩阵,矩阵的**size=(种群大小,染色体编码长度)**。染色体编码采用二进制编码的方式。染色体编码并不是直接采用将[0, 10]直接转换为二进制,原因如下:
60 |
61 | + 并非均匀分布,10的二进制表示为1010,会导致出现空余位置,例如11、12等没有意义的数字出现
62 | + 精度低,如果直接编码最小增量单位变成了 1 ,没有了浮点数的表示,最优解很多情况都会出现在浮点数的表示范围。n:代表染色体编码的长度
63 |
64 | $$
65 | x = \dfrac{染色体编码对应的十进制值}{2^n - 1}
66 | $$
67 | 此时x的范围为[0, 1],我们可以根据待测得x轴的范围进行偏移计算。例如:x得范围为[2, 10],则设计:
68 |
69 | $$
70 | x = \dfrac{染色体编码对应的十进制值}{2^n - 1} \times 8 + 2
71 | $$
72 | 种群初始化基本结构如下,实数范围还需要进一步计算得到真正得x轴的浮点值。
73 |
74 |

75 |
76 | ```matlab
77 | % popsize: 种群个数
78 | % chromlength: 染色体长度
79 | function pop=initpop(popsize,chromlength)
80 | % round:产生的随机数进行四舍五入操作就是0或者1
81 | pop = round(rand(popsize,chromlength));
82 | ```
83 |
84 | ### 3.2、适应度函数设计
85 | 适应度函数得出的值越大表明个体越优秀,所以一般情况下,在求解函数最大值的时候,适应度函数就是求解函数本身,求解最小值的时候适应度函数就是函数的倒数。在本例中求取最大值,所以适应度函数就是函数本身。
86 | ```matlab
87 | function [objvalue] = cal_objvalue(pop)
88 | x = binary2decimal(pop);
89 | objvalue=10*sin(5*x)+7*abs(x-5)+10;
90 |
91 | % 二进制转10进制并转换到对应的x轴浮点值
92 | function pop2 = binary2decimal(pop)
93 | [px,py]=size(pop);
94 | for i = 1:py
95 | pop1(:,i) = 2.^(py-i).*pop(:,i);
96 | end
97 | temp = sum(pop1,2);
98 | pop2 = temp*10/1023; % 限制到[0, 10]
99 | ```
100 |
101 | ### 3.3、选择
102 | 我们在前面已经说明了选择的原因(挑选优秀个体),挑选的算法有很多,我们这里选择“轮盘赌法”。轮盘赌法就是类似于我们玩的转盘,圆心角度越大的我们越容易选中。
103 | **注:** 选择后后的个体数目和原种群个数相同。
104 |
105 |
106 |

107 |
108 |
109 | 大自然就像那个指针,适应度值越大,表明这个体约适应这个环境,那么被选择的概率越大,与此同时,适应度值小的个体并不代表不会被选中,只是选中的概率小,一方面也保证了正负样本的一个均衡。
110 | ```matlab
111 | % pop: 遗传算法的种群
112 | % fitvalue: 种群的适应度值
113 | % newpop: 返回筛选过后的新的种群
114 | function [newpop] = selection(pop,fitvalue)
115 | [px,py] = size(pop);
116 | totalfit = sum(fitvalue);
117 | % 将适应度值转换为概率,适应度值越大表明概率越大
118 | p_fitvalue = fitvalue/totalfit;
119 | % 沿梯度进行求和运算 [0.1, 0.3, 0.6] ->[0.1, 0.4, 1]
120 | p_fitvalue = cumsum(p_fitvalue);
121 | % ms相当于指针,得出落在哪一个区域,就表明这个基因被选中
122 | ms = sort(rand(px,1)); % 先进行排序,减小时间复杂度
123 | fitin = 1; % 适应度矩阵的索引
124 | newin = 1; % 新种群索引
125 | while newin<=px
126 | if(ms(newin))
139 |
140 |
141 |
142 | **随机距离交叉(本例实现):**
143 |
144 |

145 |
146 |
147 | **程序实现:**
148 | ```matlab
149 | % pop:总种群
150 | % pc:交叉概率
151 | function [newpop] = crossover(pop,pc)
152 | [px,py] = size(pop);
153 | newpop = ones(size(pop));
154 | % 每两个进行一次交叉
155 | for i = 1:2:px-1
156 | if(rand
170 |
171 |
172 |
173 | **程序实现:**
174 | ```matlab
175 | % pop: 总种群
176 | % pm: 变异概率
177 | function [newpop] = mutation(pop,pm)
178 | [px,py] = size(pop);
179 | newpop = ones(size(pop));
180 | for i = 1:px
181 | if(rand
199 |
200 |
201 |
202 | **程序实现:**
203 | ```matlab
204 | clear;
205 | clc;
206 | % 总种群数量
207 | popsize=100;
208 | % 染色体长度
209 | chromlength=10;
210 | % 交叉概率
211 | pc = 0.6;
212 | % 变异概率
213 | pm = 0.001;
214 | %初始化种群
215 | pop = initpop(popsize,chromlength); % 100 * 10
216 |
217 | for i = 1:100
218 | objvalue = cal_objvalue(pop);
219 | fitvalue = objvalue;
220 | newpop = selection(pop,fitvalue);
221 | newpop = crossover(newpop,pc);
222 | newpop = mutation(newpop,pm);
223 | pop = newpop;
224 | [bestindividual,bestfit] = best(pop,fitvalue);
225 | x2 = binary2decimal(bestindividual); % 最优解 x 值
226 | x1 = binary2decimal(newpop);
227 | y1 = cal_objvalue(newpop);
228 | if mod(i,20) == 0
229 | figure;
230 | fplot(@(x)10*sin(5*x)+7*abs(x-5)+10,[0 10]);
231 | hold on;
232 | plot(x1,y1,'*');
233 | title(['迭代次数:%d' num2str(i)]);
234 | end
235 | end
236 | fprintf('The best X is --->>%5.2f\n',x2);
237 | fprintf('The best Y is --->>%5.2f\n',bestfit);
238 | ```
239 |
240 | ## 4、运行结果展示
241 |
242 |

243 |
244 |
245 | ## 总结
246 |
247 | 遗传算法同样会陷入局部最优解的情况,例如下面的情况:
248 |
249 |

250 |
251 |
252 | 解决局部最优解的方法有很多,小伙伴可以自行百度,我这里提供一种方法叫做非线性寻优,利用matlab自带函数fmincon进行非线性寻优。
253 |
254 | ----
255 |
256 | ## 最后
257 |
258 | 更多精彩内容,大家可以转到我的主页:[曲怪曲怪的主页](http://quguai.cn/)
259 | **源码地址**:[github地址](https://github.com/LiYangSir/SmartAlgorithm)
260 |
261 |
262 |
263 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/bamboo.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA/bamboo.bmp
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/bird.bmp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA/bird.bmp
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/cross.m:
--------------------------------------------------------------------------------
1 | function pop = cross(pop, cross_rate, pop_size, chromosome_size)
2 | j = 1;
3 | for i = 1: pop_size
4 | p = rand;
5 | if p <= cross_rate
6 | parent(j, :) = pop(i, :);
7 | a(1, j) = i;
8 | j = j + 1;
9 | end
10 | end
11 | j = j - 1;
12 | if rem(j, 2) ~= 0
13 | j = j - 1;
14 | end
15 | for i = 1: 2: j
16 | p = round(randn(1, chromosome_size));
17 | for k = 1: chromosome_size
18 | if p(1, k) == 1
19 | pop(a(1, i), k) = parent(i + 1, k);
20 | pop(a(1, i + 1), k) = parent(i, k);
21 | end
22 | end
23 | end
24 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/drawResult.m:
--------------------------------------------------------------------------------
1 | function drawResult(Image, threshold)
2 | [m, n] = size(Image);
3 | for i = 1: m
4 | for j = 1: n
5 | if Image(i, j) > threshold
6 | Image(i, j) = 255;
7 | else
8 | Image(i, j) = 0;
9 | end
10 | end
11 | end
12 | imshow(Image);
13 | end
14 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/fit.m:
--------------------------------------------------------------------------------
1 | function f = fit(similar_chromosome, fitness)
2 | t = 0.8;
3 | [m, m] = size(similar_chromosome);
4 | k = -0.8;
5 | for i = 1:m
6 | n = 0;
7 | for j = 1: m
8 | if similar_chromosome(i, j) > t
9 | n = n + 1;
10 | end
11 | end
12 | C(1, i) = n / m;
13 | end
14 | f = fitness .* exp(k * C);
15 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/fitnessty.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA/fitnessty.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/isRgb.m:
--------------------------------------------------------------------------------
1 | function y = isRgb(x)
2 | y = size(x, 3) == 3;
3 | if y
4 | if isa(x, 'logical')
5 | y = false;
6 | elseif isa(x, 'double')
7 | y = (min(x) >= 0 && max(x) <= 1);
8 | end
9 | end
10 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/main.asv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA/main.asv
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA/main.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/mutation.m:
--------------------------------------------------------------------------------
1 | function pop = mutation(pop, mutation_rate, chromosome_size, pop_size)
2 | for i = 1: pop_size
3 | s = rand(1, chromosome_size);
4 | for j = 1: chromosome_size
5 | if s(1, j) < mutation_rate
6 | if pop(i, j) == 1
7 | pop(i, j) = 0;
8 | else
9 | pop(i, j) = 1;
10 | end
11 | end
12 | end
13 | end
14 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/select.m:
--------------------------------------------------------------------------------
1 | function pop = select(pop, fitness)
2 | [px, ~] = size(pop);
3 | pfit = zeros(1, px);
4 | for i = 1: px
5 | pfit(i) = fitness(i)./ sum(fitness);
6 | end
7 | pfit = cumsum(pfit);
8 | if pfit(end) < 1
9 | pfit(end) = 1;
10 | end
11 |
12 | for i = 1: 10
13 | for j = 1: px
14 | if rand <= pfit(j)
15 | pop(i, :) = pop(j, :);
16 | break;
17 | end
18 | end
19 | end
20 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/similarChromosome.m:
--------------------------------------------------------------------------------
1 | function similar_chromosome = similarChromosome(pop)
2 | [m, n] = size(pop);
3 | similar_chromosome = zeros(m, m);
4 | for i = 1:m
5 | for j = 1:m
6 | if i == j
7 | similar_chromosome(i, j) = 1;
8 | else
9 | H(i, j) = 0;
10 | for k = 1:n
11 | if pop(i, k) ~= pop(j, k)
12 | H(i, j) = H(i, j) + 1;
13 | end
14 | end
15 | H(i, j) = H(i, j) / n;
16 | similar_chromosome(i, j) = 1 / (1 + H(i, j));
17 | end
18 | end
19 | end
20 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA/similarPopulation.m:
--------------------------------------------------------------------------------
1 | function similar_population = similarPopulation(pop)
2 | [m, n] = size(pop);
3 | h = 0;
4 | for i = 1:n
5 | s = sum(pop(:, i));
6 | if s == 0 || s == m
7 | h = h;
8 | else
9 | h = h - s / m * log2(s / m) - (m - s) / m * log2((m - s) / m);
10 | end
11 | end
12 | similar_population = 1 / (1 + h);
13 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/CharRecompose.m:
--------------------------------------------------------------------------------
1 | function result = CharRecompose(A)
2 | global D;
3 | index = A(1,2:end);
4 | tmp = A(1,1);
5 | result = [tmp];
6 | [m,n] = size(index);
7 | while n>=2
8 | len = D(tmp,index(1));
9 | tmpID = 1;
10 | for s = 2:n
11 | if len > D(tmp,index(s))
12 | tmpID = s;
13 | len = D(tmp,index(s));
14 | end
15 | end
16 | tmp = index(tmpID);
17 | result = [result,tmp];
18 | index(:,tmpID) = [];
19 | [m,n] = size(index);
20 | end
21 | result = [result,index(1)];
22 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/DisplaceInit.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决TSP问题/DisplaceInit.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/DisplaceStr.m:
--------------------------------------------------------------------------------
1 | function result = DisplaceStr(inMatrix, startCol, endCol)
2 | [m,n] = size(inMatrix);
3 | if n <= 1
4 | result = inMatrix;
5 | return;
6 | end
7 | switch nargin
8 | case 1
9 | startCol = 1;
10 | endCol = n;
11 | case 2
12 | endCol = n;
13 | end
14 | mMatrix1 = inMatrix(:,(startCol + 1):endCol);
15 | result = [mMatrix1, inMatrix(:, startCol)];
16 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/DrawRoute.m:
--------------------------------------------------------------------------------
1 | function DrawRoute(position, Route)
2 | N = length(Route);
3 | scatter(position(:, 1), position(:, 2));
4 | hold on;
5 | plot([position(Route(1), 1), position(Route(N), 1)], [position(Route(1), 2), position(Route(N), 2)])
6 | for i = 1: N - 1
7 | plot([position(Route(i), 1), position(Route(i + 1), 1)], [position(Route(i), 2), position(Route(i + 1), 2)], 'g')
8 | hold on;
9 | end
10 | end
11 |
12 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/DrawRouteGif.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决TSP问题/DrawRouteGif.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/Mutation.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决TSP问题/Mutation.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/SelectAntigen.m:
--------------------------------------------------------------------------------
1 | function result = SelectAntigen(A,B)
2 | global D;
3 | [m,n] = size(A);
4 | [p,q] = size(B);
5 | index = [A;B];
6 | rr = zeros((m+p),2);
7 | rr(:,2) = [1:(m+p)]';
8 | for s = 1:(m+p)
9 | for t = 1:(n-1)
10 | rr(s,1) = rr(s,1)+D(index(s,t),index(s,t+1));
11 | end
12 | rr(s,1) = rr(s,1) + D(index(s,n),index(s,1));
13 | end
14 | rr = sortrows(rr,1);
15 | ss = [];
16 | tmplen = 0;
17 | for s = 1:(m+p)
18 | if tmplen ~= rr(s,1)
19 | tmplen = rr(s,1);
20 | ss = [ss;index(rr(s,2),:)];
21 | end
22 | end
23 | global TmpResult;
24 | TmpResult = [TmpResult;rr(1,1)];
25 | global TmpResult1;
26 | TmpResult1 = [TmpResult1;rr(end,1)];
27 | result = ss(1:m,:);
28 |
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决TSP问题/main.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决TSP问题/test.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决TSP问题/test.gif
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决非线性问题求解/DecodeFun.m:
--------------------------------------------------------------------------------
1 | function Decimal = DecodeFun(pop, xmin, xmax)
2 | pop = fliplr(pop);
3 | pop_size = size(pop);
4 | M = ones(pop_size(1), 1) * (0: 1: 21);
5 | Decimal = sum((pop .* 2.^M)');
6 | Decimal = xmin + (xmax - xmin) * Decimal ./ (2^22 - 1);
7 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决非线性问题求解/Hypermutation.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决非线性问题求解/Hypermutation.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决非线性问题求解/InitializeFun.m:
--------------------------------------------------------------------------------
1 | function pop = InitializeFun(pop_size, chromosome_size)
2 | pop = round(rand(pop_size, chromosome_size));
3 | end
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决非线性问题求解/ReproduceFun.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决非线性问题求解/ReproduceFun.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/IMA解决非线性问题求解/main.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Immunity_Algorithm/IMA解决非线性问题求解/main.m
--------------------------------------------------------------------------------
/Immunity_Algorithm/README.md:
--------------------------------------------------------------------------------
1 | Immunity Algorithm免疫算法
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ------
11 | > 前言:本文主要围绕解决TSP旅行商问题展开,对于机器人的路线规划以及非线性方程求解的问题等解决方案大家可以直接参考[github源码地址](https://github.com/LiYangSir/SmartAlgorithm),
12 | > 对于一些其他智能算法例如遗传算法解决一些现实问题都有实现!! **欢迎小伙伴的star哦~~ 🤭**
13 |
14 |
15 | **效果图:**
16 |
17 |

18 |
19 |
20 | ## 1、什么是免疫算法
21 |
22 | 将免疫概念及其理论应用于遗传算法,在保留原算法优良特性的前提下,力图有选择、有目的地利用待求问题中的一些特征信息或知识来抑制其优化过程中出现的退化现象,这种算法称为免疫算法(Immune Algorithm) IA。人工免疫算法是一种具有生成+检测 (generate and test)的迭代过程的群智能搜索算法。从理论上分析,迭代过程中,在保留上一代最佳个体的前提下,免疫算法是全局收敛的。摘自百度百科
23 |
24 | 也就是说,免疫算法的思想来自于生物体的免疫机制,构造具有动态性和自适应性的信息防御机制,用来抵抗外部无用的有害信息的侵入(*退化解*),从而保证信息的有效性和无害性(*最优解*)。
25 | **注**:退化解的来自于变异等操作过后的适应度值低于父类的解。
26 |
27 | ### 1.1 生物免疫系统
28 |
29 | 在生物课上学过,免疫系统的构成元素主要是淋巴细胞,淋巴细胞包括B细胞和T细胞。
30 | + T细胞主要在收到抗原刺激后可以分化成淋巴母细胞,产生多种淋巴因子,引起细胞免疫反应。
31 | + B细胞又称为抗体形成细胞,可以产生抗体,抗体会同抗原产生一系列的反应,最后通过吞噬细胞的作用来消灭抗原。并且抗体具有专一性,而且免疫系统具备识别能力和记忆能力,可以对旧抗原做出更快的反应。
32 |
33 |

34 |
35 |
36 | **免疫系统和一般免疫算法的比较:**
37 | |免疫系统|免疫算法|
38 | |:---:|:---:|
39 | |抗原|待解决的问题,例如方程最优解、TSP等等|
40 | |抗体|最优解|
41 | |抗原识别|问题识别|
42 | |从记忆细胞产生抗体|找到以往的成功例子|
43 | |淋巴细胞的分化|最优解的保持|
44 | |细胞抑制|剩余候选解的消除|
45 | |抗体增强|利用遗传算子产生新的抗体|
46 |
47 | ### 1.2 免疫算法的基本原理
48 |
49 | 免疫遗传算法解决了遗传算法早熟收敛的问题,有可能陷入局部最优解的情况,并且遗传算法具有一定的盲目性,尤其是在交叉和变异的过程中。容易产生相较于父类更加差的解,也就是退化现象的出现。如果在遗传算法中引入免疫的方法和概念,对遗传算法全局搜索进行干预,就避免了很多重复的工作。
50 |
51 | 免疫算法在面对求解问题的时候,相当于面对各种抗原,可以提前注射疫苗,来一只退化的现象,从而保持优胜略汰的特点,使算法一直优化下去。
52 |
53 | 一般的免疫算法分为下面 3 种情况。
54 | 1. 模仿免疫系统抗体与抗原的识别,结合抗体的产生过程而抽象出来的免疫算法。
55 | 2. 基于免疫系统中的其他特殊机制抽象出来的算法,例如克隆选择算法。
56 | 3. 和其他智能算法等其他的算法进行融合,例如免疫遗传算法。
57 |
58 | ### 1.3 免疫算法的基本步骤和流程
59 |
60 |
61 |

62 |
63 |
64 | ## 2、免疫遗传算法
65 | 免疫遗传算法和遗传算法的结构一致,最大的不同之处在于在免疫遗传算法中引入了浓度调节机制。在进行选择操作的时候,遗传算法制只利用了适应度指标对个体进行评价;在免疫遗传算法当中,免疫遗传算法中的选择策略变为:适应度越高,浓度越小,个体复制的概率越大,反之越小。
66 |
67 | 免疫遗传算法的基本思想就是在传统的算法基础上加入一个免疫算子,加入免疫算子的目的就是为了防止种群的退化。免疫算子有接种疫苗和免疫选择两个步骤组成。免疫遗传算法可以有效地调节选择压力。因此免疫算法可以保持种群多样性的能力。
68 |
69 | **免疫遗传算法的步骤和流程:**
70 |
71 |
72 |

73 |
74 |
75 | ## 3、免疫算法在TSP问题中的应用
76 | TSP问题是所有智能算法都要解决的问题,TSP问题就是旅行商问题,旅行商要遍历所有的城市,并且城市仅能通过一次,并且保证所经过的城市的路径最小。
77 | ### 3.1、免疫算法的结构
78 | 对于个体的编码仍然采用和遗传算法中相同的实数编码结构。由于本例中要求路径最低,适应度函数就取为路径的倒数。
79 |
80 | 采用单点交叉,交叉的位置随机,类似与遗传算法。每次遗传操作后,随机抽取一些个体进行注射抗体,进行免疫检测,即对接种了个体进行检测,如果适应度提高,则继续,否则就代表着在进行交叉和变异的过程中出现了退化现象,这时个体就会被父类代替,就是下面的表达式:
81 | ```c
82 | 父类适应度 < 子类适应度 ? 子类 : 父类
83 | ```
84 |
85 | ### 3.2、求解 TSP 问题流程图
86 |
87 |
88 |

89 |
90 |
91 | ### 3.3、免疫遗传算法-TSP MatLab 实现
92 |
93 | 主要是对参数进行初始化,包括对一些概率参数、初始种群矩阵,城市初始位置、城市之间的距离矩阵等等。
94 | **参数初始化:**
95 | ```matlab
96 | N = 20;
97 | %城市的个数
98 | M = N - 1;
99 | %种群的个数
100 | pos = 50 * randn(N,2);
101 | %%生成城市的坐标
102 | global D;
103 | %城市距离数据
104 | D = zeros(N,N);
105 | for i = 1 : N
106 | for j = i + 1 : N
107 | dis = (pos(i, 1)-pos(j, 1)).^2+(pos(i, 2)-pos(j, 2)).^2;
108 | D(i, j) = dis^(0.5);
109 | D(j, i) = D(i, j);
110 | end
111 | end
112 |
113 | %中间结果保存
114 | global TmpResult;
115 | TmpResult = [];
116 | global TmpResult1;
117 | TmpResult1 = [];
118 |
119 | [M, N] = size(D); % 种群规模
120 | pCharChange = 1; % 个体换位概率
121 | pStrChange = 0.4; % 个体移位概率
122 | pStrReverse = 0.4; % 个体逆转概率
123 | pCharReCompose = 0.4; % 个体重组概率
124 | MaxIterateNum = 100; % 迭代次数
125 |
126 | mPopulation = zeros(N-1,N);
127 | mRandM = randperm(N-1); % 最优路径
128 | mRandM = mRandM + 1;
129 | for rol = 1:N-1
130 | mPopulation(rol,:) = randperm(N);%产生初始抗体
131 | end
132 | ```
133 |
134 | **迭代过程:**
135 | ```matlab
136 | count = 0;
137 | figure(2);
138 | while count < MaxIterateNum
139 | % 产生新抗体
140 | B = Mutation(mPopulation, [pCharChange pStrChange pStrReverse pCharReCompose]);
141 | % 计算新产生的抗体对应的适应度,并选择最优抗体
142 | mPopulation = SelectAntigen(mPopulation,B);
143 | % 保存每一代最优的个体
144 | best_pop(count + 1, :) = mPopulation(1, :);
145 | count = count + 1;
146 | end
147 | ```
148 |
149 | 变异过程,变异的过程主要保存移位、换位、逆转以及重组操作,这几个操作之间相互独立,最后拼接在一起后返回。
150 | **变异操作:**
151 | ```matlab
152 | function result = Mutation(A, P)
153 | [m,n] = size(A);
154 | % 换位
155 | n1 = round(P(1)*m); % 变异的个体数
156 | m1 = randperm(m); % 混淆个体顺序
157 | cm1 = randperm(n-1)+1; % 个体变异的位置
158 | B1 = zeros(n1,n); % 保存变异后的个体
159 | c1 = cm1(n-1);
160 | c2 = cm1(n-2);
161 | for s = 1:n1
162 | B1(s,:) = A(m1(s),:);
163 | tmp = B1(s,c1);
164 | B1(s,c1) = B1(s,c2);
165 | B1(s,c2) = tmp;
166 | end
167 |
168 | % 移位
169 | n2 = round(P(2)*m);
170 | m2 = randperm(m);
171 | cm2 = randperm(n-1)+1;
172 | B2 = zeros(n2,n);
173 | c1 = min([cm2(n-1),cm2(n-2)]);
174 | c2 = max([cm2(n-1),cm2(n-2)]);
175 | for s = 1:n2
176 | B2(s,:) = A(m2(s),:);
177 | B2(s,c1:c2) = DisplaceStr(B2(s,:),c1,c2);
178 | end
179 |
180 | % 逆转
181 | n3 = round(P(3)*m);
182 | m3 = randperm(m);
183 | cm3 = randperm(n-1)+1;
184 | B3 = zeros(n3,n);
185 | c1 = min([cm3(n-1),cm3(n-2)]);
186 | c2 = max([cm3(n-1),cm3(n-2)]);
187 | for s = 1:n3
188 | B3(s,:) = A(m3(s),:);
189 | tmp1 = [[c2:-1:c1]',B3(s,c1:c2)'];
190 | tmp1 = sortrows(tmp1,1);
191 | B3(s,c1:c2) = tmp1(:,2)';
192 | end
193 |
194 | % 重组
195 | n4 = round(P(4)*m);
196 | m4 = randperm(m);
197 | cm4 = randperm(n-1)+1;
198 | B4 = zeros(n4,n);
199 | c1 = min([cm4(n-1),cm4(n-2)]);
200 | c2 = max([cm4(n-1),cm4(n-2)]);
201 | for s = 1:n4
202 | B4(s,:) = A(m4(s),:);
203 | B4(s,c1:c2) = CharRecompose(B4(s,c1:c2));
204 | end
205 |
206 | % 变异后个体拼接
207 | result = [B1;B2;B3;B4];
208 | ```
209 | 上面的涉及几个函数分别是DisplaceStr()以及CharRecompose()
210 | ```matlab
211 | function result = DisplaceStr(inMatrix, startCol, endCol)
212 | [m,n] = size(inMatrix);
213 | if n <= 1
214 | result = inMatrix;
215 | return;
216 | end
217 | switch nargin
218 | case 1
219 | startCol = 1;
220 | endCol = n;
221 | case 2
222 | endCol = n;
223 | end
224 | mMatrix1 = inMatrix(:,(startCol + 1):endCol);
225 | result = [mMatrix1, inMatrix(:, startCol)];
226 |
227 | function result = CharRecompose(A)
228 | global D;
229 | index = A(1,2:end);
230 | tmp = A(1,1);
231 | result = [tmp];
232 | [m,n] = size(index);
233 | while n>=2
234 | len = D(tmp,index(1));
235 | tmpID = 1;
236 | for s = 2:n
237 | if len > D(tmp,index(s))
238 | tmpID = s;
239 | len = D(tmp,index(s));
240 | end
241 | end
242 | tmp = index(tmpID);
243 | result = [result,tmp];
244 | index(:,tmpID) = [];
245 | [m,n] = size(index);
246 | end
247 | result = [result,index(1)];
248 | ```
249 | 选择优秀的个体继续进行后续的操作,对于退化或者次优解进行去除。
250 | **选择抗体:**
251 | ```matlab
252 | function result = SelectAntigen(A,B)
253 | global D;
254 | [m,n] = size(A);
255 | [p,q] = size(B);
256 | index = [A;B];
257 | rr = zeros((m+p),2);
258 | rr(:,2) = [1:(m+p)]';
259 | for s = 1:(m+p)
260 | for t = 1:(n-1)
261 | rr(s,1) = rr(s,1)+D(index(s,t),index(s,t+1));
262 | end
263 | rr(s,1) = rr(s,1) + D(index(s,n),index(s,1));
264 | end
265 | rr = sortrows(rr,1);
266 | ss = [];
267 | tmplen = 0;
268 | for s = 1:(m+p)
269 | if tmplen ~= rr(s,1)
270 | tmplen = rr(s,1);
271 | ss = [ss;index(rr(s,2),:)];
272 | end
273 | end
274 | global TmpResult;
275 | TmpResult = [TmpResult;rr(1,1)];
276 | global TmpResult1;
277 | TmpResult1 = [TmpResult1;rr(end,1)];
278 | result = ss(1:m,:);
279 | ```
280 | ## 4、结果
281 |
282 |

283 |

284 |
285 |
286 | **注:** 为了说明方便将代码直接拆开展示如果需要源码可以直接最后的源码地址中找到。
287 |
288 | ## 最后
289 |
290 | 更多精彩内容,大家可以转到我的主页:[曲怪曲怪的主页](http://quguai.cn/)
291 |
292 | **源码地址**:[github地址](https://github.com/LiYangSir/SmartAlgorithm)
293 |
294 |
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-Toolbox/main.m:
--------------------------------------------------------------------------------
1 | clear
2 | clc
3 | x_range = [-40, 40];
4 | y_range = [-40, 40];
5 | range = [x_range; y_range];
6 | Max_V = 0.2 * (range(:, 2) - range(:, 1));
7 | n = 2;
8 | % pso_Trelea_vectorized('pso_func', n, Max_V, range)
9 | figure('color', 'k');
10 | subplot(121);
11 | axis off;
12 | axis([1, 10, 1, 10]);
13 | text(0, 1, 'asdasd', 'Color', 'b', 'FontSize', 15);
14 | text(0, 1.5, 'asdddddd', 'color', 'r');
15 | text(0, 2, 'asdddddd', 'color', 'r');
16 | text(0, 3, 'asdddddd', 'color', 'r');
17 | subplot(122);
18 | axis off;
19 | axis([1, 10, 1, 10]);
20 | text(0, 0, 'asdasd', 'color', 'b');
21 | text(0, 5, 'asdddddd', 'color', 'r');
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-Toolbox/pso_func.m:
--------------------------------------------------------------------------------
1 | function z = pso_func(in)
2 | n = size(in);
3 | x = in(:, 1);
4 | y = in(:, 2);
5 | nx = n(1);
6 | for i = 1: nx
7 | temp = 0.4 * (x(i) - 2)^2 + 0.3 * (y(i) - 4) ^2 - 0.7;
8 | z(i, :) = temp;
9 | end
10 | end
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/DrawGriewank.m:
--------------------------------------------------------------------------------
1 | function DrawGriewank()
2 | x = -8: 0.1: 8;
3 | y = x;
4 | [X, Y] = meshgrid(x, y);
5 | [row, col] = size(X);
6 | for l = 1: col
7 | for h = 1: row
8 | z(h, l) = Griewank([X(h, l), Y(h, l)]);
9 | end
10 | end
11 | surf(X, Y, z);
12 | shading interp
13 | end
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/DrawRastrigin.m:
--------------------------------------------------------------------------------
1 | function DrawRastrigin()
2 | x = -4: 0.05: 4;
3 | y = x;
4 | [X, Y] = meshgrid(x, y);
5 | [row, col] = size(X);
6 | for l = 1: col
7 | for h = 1: row
8 | z(h, l) = Rastrigin([X(h, l), Y(h, l)]);
9 | end
10 | end
11 | surf(X, Y, z);
12 | shading interp
13 | end
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/Griewank.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Particle_Swarm_Optimization/PSO-basic/Griewank.m
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/PSO.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Particle_Swarm_Optimization/PSO-basic/PSO.m
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/Rastrigin.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiYangSir/Smart-Algorithm/b0653c32aa1ed4ce0d97c8c138f93c9fde75ae6d/Particle_Swarm_Optimization/PSO-basic/Rastrigin.m
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/fitness.m:
--------------------------------------------------------------------------------
1 | function F = fitness(x)
2 | F = 0;
3 | for i = 1: 30
4 | F = F + x(i)^2 + x(i) - 6;
5 | end
6 | end
--------------------------------------------------------------------------------
/Particle_Swarm_Optimization/PSO-basic/main.m:
--------------------------------------------------------------------------------
1 | clear
2 | clc
3 | % [xm1, fv1] = PSO(@fitness, 50, 1.5, 2.5, 0.5, 100, 30);
4 | % [xm2, fv2] = PSO(@fitness, 50, 1.5, 2.5, 0.5, 1000, 30);
5 | % [xm3, fv3] = PSO(@fitness, 50, 1.5, 2.5, 0.5, 10000, 30);
6 |
7 | % [xm1, fv1] = PSO(@fitness, 50, 1.5, 2.5, 0.5, 100, 30);
8 | % [xm2, fv2] = PSO(@fitness, 100, 1.5, 2.5, 0.5, 100, 30);
9 | % [xm3, fv3] = PSO(@fitness, 200, 1.5, 2.5, 0.5, 100, 30);
10 |
11 | [xm1, fv1] = PSO(@fitness, 50, 1.5, 1.5, 0.5, 100, 30);
12 | [xm2, fv2] = PSO(@fitness, 100, 1.5, 1.5, 0.5, 100, 30);
13 | [xm3, fv3] = PSO(@fitness, 500, 1.5, 1.5, 0.5, 100, 30);
14 |
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Smart Algorithm
2 |
3 | >智能算法是路线规划、深度学习等等一系列领域所使用的优化算法,是算法进阶之路的必备之路。
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | ------
13 |
14 | ### 简介
15 |
16 | 主要针对目前主流的算法进行实现,例如遗传算法、粒子群算法、模拟退火算法、免疫算法、蚁群算法等等一系列的算法。
17 |
18 | > [个人主页](http://quguai.cn) | [CSDN](https://me.csdn.net/qq_41503660) | 微信公众号: TeaUrn
19 |
20 | ### 开始使用
21 |
22 | 智能算法-遗传算法、蚁群算法、粒子群算法实现。实现版本Java,Python,MatLab多版本实现。具体详细说明点击下面连接针对每个算法有着详细的说明。
23 |
24 | [蚁群算法:Ant_Colony_Optimization](/Ant_Colony_Optimization)
25 |
26 | [遗传算法:Genetic_Algorithm](/Genetic_Algorithm)
27 |
28 | [免疫算法:Immunity_Algorithm](/Immunity_Algorithm)
29 |
30 | [粒子群:Particle Swarm Optimization](/Particle_Swarm_Optimization)
31 |
32 |
33 | ### 联系方式:
34 | 微信公众号:**TeaUrn**
35 | 或者扫描下方二维码进行关注。里面有惊喜等你哦~~
36 |
37 |
38 |
39 | ### 捐赠
40 | 如果您觉得文章对您有所帮助,可以请作者喝☕。
41 |
42 | |支付宝/微信/QQ|
43 | |-------------|
44 | ||
--------------------------------------------------------------------------------
/Smart-Algorithm.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------