Java算法---遗传算法示例

  用一个简单的实例带大家走进遗传算法的神奇世界。

  问题描述:

        求下面二元函数的最大值:

        

       遗传算法主要核心包括:编码,初始种群的产生,适应度计算,选择算子,交叉算子,变异算子。

      这个示例中采用二进制编码,x1,x2的范围在[1-7]直接,可以选择3位二进制进行编码,3为二进制编码刚好和每个数字对应。适应度计算,可以采取目标函数f(x1.x2),算法具体实现如下:

 

[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3. import java.util.Random;  
  4. /** 
  5.  * Created by yaobo on 2016/6/20. 
  6.  */  
  7. public class GAMAX {  
  8.     public  static int MaxGen=1000;//最大遗传代数  
  9.     public static int generate;//全局变量,控制循环的代数  
  10.     double Pc=0.7;//交叉概率  
  11.     double Pm=0.05;//变异概率  
  12.     int Chromlenth=6;//染色体长度  
  13.     int scale=10;// 种群规模  
  14.     int everchromlength=3;//变量的编码长度  
  15.     int bestIndex;//当前代最好个体的索引  
  16.     int worstIndex;//当前代最坏个体的索引  
  17.     Individual bestIndividual;//当前代最好的个体  
  18.     Individual worstIndividual;//当前代最坏的个体  
  19.     Individual currentBest=new Individual();  
  20.     static double Rs=00.;//保存出现最好结果值  
  21.     static int Rsindex=-1;//保存出现最好结果的代数  
  22.     Individual[] population=new Individual[scale];//定义数组保存种群  
  23.     Random random=new Random();//随机函数  
  24.     public static void main(String[] args) {  
  25.         GAMAX gamax=new GAMAX();  
  26.         generate=0;//从0代开始  
  27.         gamax.generateInitalPopulation();//产生第一代个体  
  28.         gamax.evaluatePopulation();  
  29.         while (generate<MaxGen){//循环迭代  
  30.             generate++;  
  31.             gamax.generateNextPopulation();  
  32.             gamax.evaluatePopulation();  
  33.             gamax.performEvolution();  
  34.             gamax.printInf();  
  35.             gamax.findBest();  
  36.         }  
  37.         System.out.println("最优结果"+Rs+"产生代数"+Rsindex);  
  38.   
  39.     }  
  40.   
  41.       void findBest(){//找到最好的结果和代数  
  42.       if(Rs<bestIndividual.fitness){  
  43.             Rs=bestIndividual.fitness;  
  44.             Rsindex=bestIndex;  
  45.         }  
  46.       }  
  47.   
  48.     void generateNextPopulation(){//产生下一代样本  
  49.         selectionOperator();  
  50.         crossoverOperator();  
  51.         mutationOperator();  
  52.     }  
  53.     void evaluatePopulation(){  
  54.         calculateFitnessValue();  
  55.         findBestAndWorstIndividual();  
  56.   
  57.     }  
  58.      void generateInitalPopulation(){//产生第一代样本种群  
  59.          StringBuffer sb;  
  60.          Individual individual;  
  61.         for(int i=0;i<scale;i++){  
  62.             sb=new StringBuffer();  
  63.             for(int j=0;j<Chromlenth;j++){  
  64.                 sb.append(((random.nextInt(65535)%10)<5)?'0':'1');  
  65.             }  
  66.             individual=new Individual();  
  67.             individual.chrom=sb.toString();  
  68.             population[i]=individual;  
  69.         }  
  70.     }  
  71.   
  72.   
  73.     void mutationOperator(){//变异算子  
  74.         double p;  
  75.         for (int i=0;i<scale;i++){  
  76.             for(int j=0;j<Chromlenth;j++) {  
  77.                 p = random.nextInt(65535) % 1000 / 1000.0;  
  78.                 if (p < Pm) {  
  79.                     char temp=population[i].chrom.charAt(j);  
  80.                     temp=(temp=='1'?'0':'1');  
  81.                     population[i].chrom=population[i].chrom.substring(0,j)+temp+population[i].chrom.substring(j+1);  
  82.                 }  
  83.             }  
  84.         }  
  85.     }  
  86.     void crossoverOperator(){//交叉算子  
  87.         ArrayList<Integer> index=new ArrayList<Integer>();  
  88.         int point;  
  89.         double p;  
  90.         String str1,str2;  
  91.         for(int i=0;i<scale;i++){  
  92.             index.add(i);  
  93.         }  
  94.         Collections.shuffle(index);//随机打乱样本,也就是随机配对  
  95.         for(int i=0;i<scale-1;i=i+2){  
  96.             p=random.nextInt(65535)%1000/1000.0;  
  97.             if(p<Pc){//如果小于这个数,则进行交叉遗传  
  98.                 point=random.nextInt(65536)%(Chromlenth-1)+1;  
  99.                 str1=population[index.get(i)].chrom.substring(point);  
  100.                 str2=population[index.get(i+1)].chrom.substring(point);  
  101.                 population[index.get(i)].chrom= population[index.get(i)].chrom.substring(0,point)+str2;  
  102.                 population[index.get(i+1)].chrom= population[index.get(i+1)].chrom.substring(0,point)+str1;  
  103.             }  
  104.         }  
  105.     }  
  106.     void selectionOperator(){//选择算子并计算累积概率  
  107.         double p;  
  108.         double sum=0;  
  109.         double[] cfitness=new double[scale];  
  110.         int index;  
  111.         Individual[] newpoputation=new Individual[scale];//新的种群  
  112.         for (int i=0;i<scale;i++){  
  113.             sum+=population[i].fitness;  
  114.         }  
  115.         for(int i=0;i<scale;i++){  
  116.             cfitness[i]=population[i].fitness/sum;  
  117.         }  
  118.   
  119.         for(int i=1;i<scale;i++){  
  120.             cfitness[i]=cfitness[i]+cfitness[i-1];  
  121.         }  
  122.   
  123.         for(int i=0;i<scale;i++){  
  124.             p=random.nextInt(65535)%1000/1000.0;  
  125.             index=0;  
  126.             while (p>cfitness[index]){  
  127.                 index++;  
  128.             }  
  129.             newpoputation[i]=population[index];  
  130.         }  
  131.   
  132.         for(int i=0;i<scale;i++){  
  133.             population[i]=newpoputation[i];  
  134.         }  
  135.     }  
  136.   
  137.   
  138.     void findBestAndWorstIndividual(){//找出当前最好的个体  
  139.         bestIndividual=population[0];  
  140.         worstIndividual=population[0];  
  141.         for(int i=0;i<scale;i++){  
  142.             if(population[i].fitness>bestIndividual.fitness){  
  143.                 bestIndividual=population[i];  
  144.                 bestIndex=i;  
  145.             }  
  146.             else if(population[i].fitness<worstIndividual.fitness){  
  147.                 worstIndividual=population[i];  
  148.                 worstIndex=i;  
  149.             }  
  150.         }  
  151.         if(generate==0){  
  152.             currentBest=bestIndividual;  
  153.         }  
  154.         else {  
  155.             if(bestIndividual.fitness>currentBest.fitness){  
  156.                 currentBest=bestIndividual;  
  157.             }  
  158.         }  
  159.   
  160.   
  161.     }  
  162.     void calculateFitnessValue(){//计算个体的适应度值  
  163.         String temp1,temp2;  
  164.         double x1,x2;  
  165.         for(int i=0;i<scale;i++){  
  166.             temp1=Integer.valueOf(population[i].chrom.substring(0,everchromlength),2).toString();  
  167.             temp2=Integer.valueOf(population[i].chrom.substring(everchromlength),2).toString();  
  168.             x1=Integer.parseInt(temp1)*Integer.parseInt(temp1);  
  169.             x2=Integer.parseInt(temp2)*Integer.parseInt(temp2);  
  170.             population[i].fitness=x1+x2;  
  171.   
  172.         }  
  173.   
  174.     }  
  175.     public void performEvolution(){  
  176.         if(bestIndividual.fitness>currentBest.fitness){  
  177.             currentBest=population[bestIndex];  
  178.         }else {  
  179.             population[worstIndex]=currentBest;  
  180.         }  
  181.     }  
  182.     void printInf(){  
  183.         double sum=0;  
  184.         double average;  
  185.         for (int i=0;i<scale;i++){  
  186.             sum+=population[i].fitness;  
  187.         }  
  188.         average=sum/scale;  
  189.         System.out.println("generate " + generate + " ava " + average + " best " + currentBest.fitness + " chrom " + currentBest.chrom);  
  190.     }  
  191.   
  192. }  
  193. class Individual{  
  194.     String chrom;  
  195.     double fitness;  
  196. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值