人工智能实验二-遗传算法解决最大值

XTU计网的选修课实验,任课老师为申老师。

 

 

 

 

 实验其实也很简单,重要的是你要跟着上述的指导书一步一步来。

 定义结构体,第一个参数表示在[-1,2]里面的值,第二个则表示在群体之中的值,第三个就是适应度。
其中存在对应关系:mySpecies[i].second = (mySpecies[i].first + 1) / 3 * speciesNums;

后面就是跟着实验指导书来,没什么好说的。
唯一与实验指导书不同的是,我才用了精英选择算法,使用上一代最强的个体替换掉最弱的个体,保证种群不会退化。

关于早熟的理解:例如只有两个个体:[1,1,1,0,0], [1.0.0.1.1],我们不难看出他们的第一个都是1,无论你怎么交叉,它都是1,我们可以假设如果所有的种群在某一位相等,那么他就永远不会改变,那样就失去了交叉的意义,所以需要强制变异。

主代码如下:

package Solutions.GenAlgorithm;import java.util.Arrays;
import java.util.Random;public class MaxValue {public static class MyEntity{//first is the number of interval [left, right].//second is the number of a representation on binary//third is the fitness of this entitypublic double first, second, third;}//really Species Populationprivate int count = 0;public int speciesCounts = 0;public int speciesNums = 0;//Crossover probabilitypublic double p = 0.7;//Mutation probabilitypublic double mutationProbability = 0.001;//better species that each cycle to selectpublic MyEntity[] mySpecies;//the number of a speciespublic int mySpeciesPopulation;//the best Entitypublic MyEntity bestEntity = new MyEntity();//a class to reserve the function about fitnesspublic AdaptiveFunctions adaptiveFunctions = new AdaptiveFunctions();//calculate Species populationpublic void initSpecies(int left, int right, int accurateValue){//expected Species populationspeciesNums = 0;speciesCounts = 0;bestEntity.third = 0;bestEntity.first = 0;bestEntity.second = 0;int entityLength = (int) Math.pow(10, accurateValue) * (right - left);int temp = 1;do {speciesCounts++;temp *= 2;} while (temp < entityLength);speciesNums = temp;}//create a speciespublic void createSpecies(int population){//random to create entity.this.mySpecies = new MyEntity[population];this.mySpeciesPopulation = population;//the range is from left to right.//example: if our interval is [-1,2].//the random is [0,1], we need mul 3 and subtract 1 to get [-1,2].for(int i = 0;i < population;i++){mySpecies[i] = new MyEntity();mySpecies[i].first = (Math.random() * 3) - 1;mySpecies[i].second = (mySpecies[i].first + 1) / 3 * speciesNums;}}//to calculate the fitness to select better entitypublic void selectSpecies(){int n = mySpecies.length;double sum = 0, m = 0;//calculate the sum of fitness.for (var specy : mySpecies) {specy.third = adaptiveFunctions.maxFunctions(specy.first);sum += specy.third;}//to get the probability of each entity//select better entityMyEntity worstEntity = new MyEntity();MyEntity[] myTempSpecies = new MyEntity[n];for(int i = 0;i < n;i++){double r = Math.random() * sum;myTempSpecies[i] = new MyEntity();double preFitnessValue = 0;for (var mySpecy : mySpecies) {preFitnessValue += mySpecy.third;if (preFitnessValue >= r) {myTempSpecies[i] = mySpecy;break;}}}count++;for(int i = 0;i < mySpeciesPopulation;i++){if(mySpecies[i].third > bestEntity.third){count = 0;bestEntity.third = mySpecies[i].third;bestEntity.second = mySpecies[i].second;bestEntity.first = mySpecies[i].first;}}//exchange the valueSystem.arraycopy(myTempSpecies, 0, mySpecies, 0, n);}public void crossoverSpecies(){for(int i = 0, pre = -1;i < mySpecies.length;i++){if(Math.random() < p){if (pre == -1) pre = i;else {//start crossoverint crossoverPoint = new Random().nextInt(speciesCounts + 1);//System.out.println(l + " " + r);//we need 22 bit, so we use this format to get that.StringBuilder p1 = new StringBuilder(String.format("%22s", Integer.toBinaryString((int)mySpecies[pre].second)).replace(' ', '0'));StringBuilder p2 = new StringBuilder(String.format("%22s", Integer.toBinaryString((int)mySpecies[i].second)).replace(' ', '0'));//from crossoverPoint to start crossover.for(int j = crossoverPoint;j < p1.length();j++){var sp = p1.charAt(j);p1.setCharAt(j, p2.charAt(j));p2.setCharAt(j, sp);}//change the 2 bit to 10 bit.int num1 = Integer.parseInt(p1.toString(), 2);int num2 = Integer.parseInt(p2.toString(), 2);//other value also be changed synchronouslymySpecies[pre].second = num1;mySpecies[pre].first = 3 * num1 * 1.0 / speciesNums - 1;mySpecies[pre].third = adaptiveFunctions.maxFunctions(mySpecies[pre].first);mySpecies[i].second = num2;mySpecies[i].first = 3 * num2 * 1.0 / speciesNums - 1;mySpecies[i].third = adaptiveFunctions.maxFunctions(mySpecies[i].first);}}}}public void mutation(){StringBuilder[] sb = new StringBuilder[mySpeciesPopulation];for(int i = 0;i < mySpeciesPopulation;i++){sb[i] = new StringBuilder(String.format("%22s", Integer.toBinaryString((int)mySpecies[i].second)).replace(' ', '0'));var r = Math.random();//start mutateif(r < mutationProbability){//select entity to mutateint mutationIndex = new Random().nextInt(speciesCounts);StringBuilder p = new StringBuilder(String.format("%22s", Integer.toBinaryString((int)mySpecies[i].second)).replace(' ', '0'));var target = p.charAt(mutationIndex);if(target == '0') p.setCharAt(mutationIndex, '1');else p.setCharAt(mutationIndex, '0');int num = Integer.parseInt(p.toString(), 2);var m = adaptiveFunctions.maxFunctions(3 * num * 1.0 / speciesNums - 1);mySpecies[i].second = num;mySpecies[i].first = 3 * num * 1.0 / speciesNums - 1;mySpecies[i].third = m;}}//Prevent the entry of local optimal solutionsfor(int i = 0;i < speciesCounts;i++){boolean isSample = true;for(int j = 1;j < mySpeciesPopulation;j++){if(sb[j].charAt(i) != sb[j-1].charAt(i)){isSample = false;break;}}if (isSample){for(int k = 0;k < mySpeciesPopulation / 5;k++){int j = new Random().nextInt(mySpeciesPopulation);var target = sb[j].charAt(i);if(target == '0') sb[j].setCharAt(i, '1');else sb[j].setCharAt(i, '0');}//System.out.println("陷入了局部最优");}}for(int i = 0;i < mySpeciesPopulation ;i++){//System.out.println(sb[i] + " " +  "Best Entity : " + " " + bestEntity.third);int num = Integer.parseInt(sb[i].toString(), 2);var m = adaptiveFunctions.maxFunctions(3 * num * 1.0 / speciesNums - 1);mySpecies[i].second = num;mySpecies[i].first = 3 * num * 1.0 / speciesNums - 1;mySpecies[i].third = m;}//System.out.println("********下一代********");}//to find the worstEntityprivate int findWorstEntity(){double f = mySpecies[0].third;int index = 0;for(int i = 0;i < mySpeciesPopulation;i++){if(mySpecies[i].third < f){f = mySpecies[i].third;index = i;}}return index;}public double startIterate(int left, int right, int accurateValue, int population, int iteratingCounts){double ans = 0, fitness = 0;//fist we init the population.//to seek how many counts we need.initSpecies(left, right, accurateValue);//then we can create the population by the formercreateSpecies(population);//start to iterator the population to find the best entitywhile(iteratingCounts-- != 0){if(this.count >= 100){System.out.println("迭代100结束");break;}selectSpecies();crossoverSpecies();mutation();//use bestEntity to replace worstEntity/*for(var species : mySpecies){System.out.println(String.format("%22s", Integer.toBinaryString((int)species.second)).replace(' ', '0'));}*/int index = findWorstEntity();mySpecies[index].first = bestEntity.first;mySpecies[index].second = bestEntity.second;mySpecies[index].third = bestEntity.third;}//we can seek the result when we finish iteration.for(var species : mySpecies){if(species.third > fitness){ans = species.first;fitness = species.third;}}System.out.println("X值为:\t" + ans);return fitness;}
}

适应函数:

package Solutions.GenAlgorithm;public class AdaptiveFunctions {public double maxFunctions(double x){return x * Math.sin(10 * Math.PI * x) + 2.0;}
}

主函数:

package org.example;import Solutions.GenAlgorithm.MaxValue;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);MaxValue maxValue = new MaxValue();System.out.println(maxValue.startIterate(-1, 2, 6, 50, 1));}
}

使用如下:

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部