遗传算法-入门(Java demo)

转载from:http://www.acmerblog.com/genetic-algorithm-for-beginners-java-demo-5755.html

本文用简单的demo介绍遗传算法,适合初学者入门。实际案例参考:旅行商(TSP)问题-遗传算法

遗传算法介绍

遗传算法 ( GA , Genetic Algorithm ) ,也称进化算法 。遗传算法是计算机科学人工智能领域中用于解决最优化的一种搜索启发式算法,是进化算法的一种。这种启发式通常用来生成有用的解决方案来优化和搜索问题。进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择以及杂交等。遗传算法通常实现方式为一种计算机模拟。对于一个最优化问题,一定数量的候选解(称为个体)的抽象表示(称为染色体)的种群向更好的解进化。传统上,解用二进制表示(即0和1的串),但也可以用其他表示方法。进化从完全随机个体的种群开始,之后一代一代发生。在每一代中,整个种群的适应度被评价,从当前种群中随机地选择多个个体(基于它们的适应度),通过自然选择和突变产生新的生命种群,该种群在算法的下一次迭代中成为当前种群。

遗传算法是受达尔文的进化论的启发,借鉴生物进化过程而提出的一种启发式搜索算法。因此在介绍遗传算法前有必要简单的介绍生物进化知识。

种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群。
个体:组成种群的单个生物。
基因 ( Gene ) :一个遗传因子。
染色体 ( Chromosome ) :包含一组的基因。
生存竞争,适者生存:对环境适应度高的、牛B的个体参与繁殖的机会比较多,后代就会越来越多。适应度低的个体参与繁殖的机会比较少,后代就会越来越少。
遗传与变异:新个体会遗传父母双方各一部分的基因,同时有一定的概率发生基因变异。

遗传算法是如何运行的

程遗传算法的基本过是:

  1. 初始化 – 创建一个初始种群。这种群通常是随机生成的,种群的大小根据实际情况而定。(demo中大小为50,个体随机生成)。
  2. 评价 – 计算每一个个体的适应值。适应值是根据我们所期望的要求进行计算。这些要求可以是简单的“更快的算法更好”,或复杂的 “坚固的材料更好,但不要太重”。(demo中getFitness函数根据设定的预期结果solution计算个体的适应值)。
  3. 选择-我们要不断提高种群的整体适应值。我们选择当前这一代种群中较优秀的,即适应值高的。有几个不同的选择方法,但基本思想是一样的。(demo中tournamentSelection函数进行选择)
  4. 交叉-交叉过程中,利用上面一步选择到的优秀个体进行交叉(暂且理解为make love的过程吧~)。主要目的是通过由两个或两个以上优秀的个体,来创建下一代,让下一代继承一些优秀的特征,即所谓虎父无犬子。(demo中crossover函数进行交叉操作)
  5. 突变- 突变是一个小概率的事件,我们需要为算法添加一些随机性。(demo中mutate进行突变操作)
  6. 重复2-5,直到达到我们期望的结果。

限制

想象一下,你被告知要戴上眼罩,然后你被放置在同一座山的底部,让你找最高峰 。你是唯一的选择就是不断爬山,直到你发现你不能在往上爬了。你可能会宣布你已经找到了高峰,但你怎么知道?看下面这个图,Local optimum就是局部最优,Peak就是全局最优。虽然遗传算法往往可以避免掉最优最优,当不是我们不能保证一定能找到全局最优解。遗传算法是属于近似算法,适合解决复杂问题

localopt

代码实现

下面是java代码的实现。源代码已经放在github:https://github.com/gaotong2055/Advanced-Algorithm

下面使用的面向对象的设计,主要的类如下:

  • Population – 一个种群,管理所有的个体
  • Individual – 个体,包含一个基因序列
  • Algorithm – 算法类,进行遗传算法的主要操作
  • FitnessCalc – 辅助类,计算个体的适应值等
  • MainTest- 测试类

Population.java

01 package simpleGa;
02  
03 public class Population {
04     Individual[] individuals;
05     // 创建一个种群
06     public Population(int populationSize, boolean initialise) {
07         individuals = new Individual[populationSize];
08         // 初始化种群
09         if (initialise) {
10             for (int i = 0; i < size(); i++) {
11                 Individual newIndividual = new Individual();
12                 newIndividual.generateIndividual();
13                 saveIndividual(i, newIndividual);
14             }
15         }
16     }
17  
18     public Individual getIndividual(int index) {
19         return individuals[index];
20     }
21  
22     public Individual getFittest() {
23         Individual fittest = individuals[0];
24         // Loop through individuals to find fittest
25         for (int i = 0; i < size(); i++) {
26             if (fittest.getFitness() <= getIndividual(i).getFitness()) {
27                 fittest = getIndividual(i);
28             }
29         }
30         return fittest;
31     }
32  
33     // Get population size
34     public int size() {
35         return individuals.length;
36     }
37  
38     // Save individual
39     public void saveIndividual(int index, Individual indiv) {
40         individuals[index] = indiv;
41     }
42 }

Individual.java

01 package simpleGa;
02  
03 public class Individual {
04  
05     static int defaultGeneLength = 64;
06     //基因序列
07     private byte[] genes = new byte[defaultGeneLength];
08     // 个体的 适应值
09     private int fitness = 0;
10  
11     // 创建一个随机的 基因个体
12     public void generateIndividual() {
13         for (int i = 0; i < size(); i++) {
14             byte gene = (byte) Math.round(Math.random());
15             genes[i] = gene;
16         }
17     }
18  
19     // Use this if you want to create individuals with different gene lengths
20     public static void setDefaultGeneLength(int length) {
21         defaultGeneLength = length;
22     }
23  
24     public byte getGene(int index) {
25         return genes[index];
26     }
27  
28     public void setGene(int index, byte value) {
29         genes[index] = value;
30         fitness = 0;
31     }
32  
33     /* Public methods */
34     public int size() {
35         return genes.length;
36     }
37  
38     public int getFitness() {
39         if (fitness == 0) {
40             fitness = FitnessCalc.getFitness(this);
41         }
42         return fitness;
43     }
44  
45     @Override
46     public String toString() {
47         String geneString = "";
48         for (int i = 0; i < size(); i++) {
49             geneString += getGene(i);
50         }
51         return geneString;
52     }
53 }

Algorithm.java

01 package simpleGa;
02  
03 public class Algorithm {
04  
05     /* GA 算法的参数 */
06     private static final double uniformRate = 0.5//交叉概率
07     private static final double mutationRate = 0.015//突变概率
08     private static final int tournamentSize = 5//淘汰数组的大小
09     private static final boolean elitism = true//精英主义
10  
11     // 进化一个种群
12     public static Population evolvePopulation(Population pop) {
13         // 存放新一代的种群
14         Population newPopulation = new Population(pop.size(), false);
15  
16         // 把最优秀的那个 放在第一个位置.
17         if (elitism) {
18             newPopulation.saveIndividual(0, pop.getFittest());
19         }
20  
21         // Crossover population
22         int elitismOffset;
23         if (elitism) {
24             elitismOffset = 1;
25         else {
26             elitismOffset = 0;
27         }
28         // Loop over the population size and create new individuals with
29         // crossover
30         for (int i = elitismOffset; i < pop.size(); i++) {
31             //随机选择两个 优秀的个体
32             Individual indiv1 = tournamentSelection(pop);
33             Individual indiv2 = tournamentSelection(pop);
34             //进行交叉
35             Individual newIndiv = crossover(indiv1, indiv2);
36             newPopulation.saveIndividual(i, newIndiv);
37         }
38  
39         // Mutate population  突变
40         for (int i = elitismOffset; i < newPopulation.size(); i++) {
41             mutate(newPopulation.getIndividual(i));
42         }
43  
44         return newPopulation;
45     }
46  
47     // 进行两个个体的交叉 (暂且想象为make love的过程吧)。 交叉的概率为uniformRate
48     private static Individual crossover(Individual indiv1, Individual indiv2) {
49         Individual newSol = new Individual();
50         // 随机的从 两个个体中选择
51         for (int i = 0; i < indiv1.size(); i++) {
52             if (Math.random() <= uniformRate) {
53                 newSol.setGene(i, indiv1.getGene(i));
54             else {
55                 newSol.setGene(i, indiv2.getGene(i));
56             }
57         }
58         return newSol;
59     }
60  
61     // 突变个体。 突变的概率为 mutationRate
62     private static void mutate(Individual indiv) {
63         for (int i = 0; i < indiv.size(); i++) {
64             if (Math.random() <= mutationRate) {
65                 // 生成随机的 0 或 1
66                 byte gene = (byte) Math.round(Math.random());
67                 indiv.setGene(i, gene);
68             }
69         }
70     }
71  
72     // 随机选择一个较优秀的个体,用了进行交叉
73     private static Individual tournamentSelection(Population pop) {
74         // Create a tournament population
75         Population tournamentPop = new Population(tournamentSize, false);
76         //随机选择 tournamentSize 个放入 tournamentPop 中
77         for (int i = 0; i < tournamentSize; i++) {
78             int randomId = (int) (Math.random() * pop.size());
79             tournamentPop.saveIndividual(i, pop.getIndividual(randomId));
80         }
81         // 找到淘汰数组中最优秀的
82         Individual fittest = tournamentPop.getFittest();
83         return fittest;
84     }
85 }

FitnessCalc.java

01 package simpleGa;
02  
03 public class FitnessCalc {
04  
05     static byte[] solution = new byte[64];
06  
07     /* Public methods */
08     // 设置候选结果为一个 byte array
09     public static void setSolution(byte[] newSolution) {
10         solution = newSolution;
11     }
12  
13     // 就是把01 字符串转换为 01数组, 放在 solution中
14     static void setSolution(String newSolution) {
15         solution = new byte[newSolution.length()];
16         // Loop through each character of our string and save it in our byte
17         for (int i = 0; i < newSolution.length(); i++) {
18             String character = newSolution.substring(i, i + 1);
19             if (character.contains("0") || character.contains("1")) {
20                 solution[i] = Byte.parseByte(character);
21             else {
22                 solution[i] = 0;
23             }
24         }
25     }
26  
27     // 通过和solution比较 ,计算个体的适应值
28     static int getFitness(Individual individual) {
29         int fitness = 0;
30         for (int i = 0; i < individual.size() && i < solution.length; i++) {
31             if (individual.getGene(i) == solution[i]) {
32                 fitness++;
33             }
34         }
35         return fitness;
36     }
37  
38     //最优的适应值,即为基因序列的长度
39     static int getMaxFitness() {
40         int maxFitness = solution.length;
41         return maxFitness;
42     }
43 }

下面开始测试:

MainTest.java

01 package simpleGa;
02  
03 public class MainTest {
04     public static void main(String[] args) {
05  
06         // 选择一个期望的基因序列。这个是由自己任意定
07         FitnessCalc
08                 .setSolution("1111000000000000000000000000000000000000000000000000000000001111");
09  
10         // 初始化一个种群
11         Population myPop = new Population(50true);
12  
13         // 不段迭代,进行进化操作。 直到找到期望的基因序列
14         int generationCount = 0;
15         while (myPop.getFittest().getFitness() < FitnessCalc.getMaxFitness()) {
16             generationCount++;
17             System.out.println("Generation: " + generationCount + " Fittest: "
18                     + myPop.getFittest().getFitness());
19             myPop = Algorithm.evolvePopulation(myPop);
20         }
21         System.out.println("Solution found!");
22         System.out.println("Generation: " + generationCount);
23         System.out.println("Final Fittest Genes:");
24         System.out.println(myPop.getFittest());
25  
26     }
27 }

输出的解应该是类似这样的:

01 Generation: 1 Fittest: 39
02 Generation: 2 Fittest: 45
03 Generation: 3 Fittest: 46
04 Generation: 4 Fittest: 48
05 Generation: 5 Fittest: 52
06 Generation: 6 Fittest: 55
07 Generation: 7 Fittest: 58
08 Generation: 8 Fittest: 60
09 Generation: 9 Fittest: 62
10 Generation: 10 Fittest: 63
11 Generation: 11 Fittest: 63
12 Solution found!
13 Generation: 11
14 Final Fittest Genes:
15 1111000000000000000000000000000000000000000000000000000000001111

注意,每次的运行结果会不一样,因为里面有很多随机因素。

本文代码参考自国外网站:http://www.theprojectspot.com/tutorial-post/creating-a-genetic-algorithm-for-beginners/3

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值