XTU计网的选修课实验,任课老师为申老师。
实验其实也很简单,重要的是你要跟着上述的指导书一步一步来。
关于早熟的理解:例如只有两个个体:[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 entity public double first, second, third; } //really Species Population private int count = 0; public int speciesCounts = 0; public int speciesNums = 0; //Crossover probability public double p = 0.7; //Mutation probability public double mutationProbability = 0.001; //better species that each cycle to select public MyEntity[] mySpecies; //the number of a species public int mySpeciesPopulation; //the best Entity public MyEntity bestEntity = new MyEntity(); //a class to reserve the function about fitness public AdaptiveFunctions adaptiveFunctions = new AdaptiveFunctions(); //calculate Species population public void initSpecies(int left, int right, int accurateValue){ //expected Species population speciesNums = 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 species public 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 entity public 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 entity MyEntity 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 value System.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 crossover int 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 synchronously mySpecies[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 mutate if(r < mutationProbability){ //select entity to mutate int 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 solutions for(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 worstEntity private 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 former createSpecies(population); //start to iterator the population to find the best entity while(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)); } }
使用如下:



版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/87025.html