为了学习遗传算法并且熟悉jgap库。自己做了几个实例初步明白遗传算法和如何实际应用。
这里先做一个简单的例子:要求有2组数都是0-9999999,从每组数中抽出一个数,求最大的组合。以下为具体代码
/**
* <p><i>Copyright: youhow.net (c) 2005–2008<br>
* 遗传算法DEMO
* 从文件读取数字进行排序
*
* @version 1.0 (<i>2008–6–12 neo([email protected])</i>)
*/
public class GaDemo
{
public static void main(String[] args) throws Exception
{
//构型
Configuration conf = new DefaultConfiguration();
conf.setPreservFittestIndividual(true);
FitnessFunction myFunc = new GaDemoFitnessFunction();
conf.setFitnessFunction(myFunc);
Gene[] sampleGenes = new Gene[2];
sampleGenes[0] = new IntegerGene(conf,0,9999999);
sampleGenes[1] = new IntegerGene(conf,0,9999999);
IChromosome sampleChromosome = new Chromosome(conf, sampleGenes);
conf.setSampleChromosome(sampleChromosome);
conf.setPopulationSize(80);
Genotype population;
try
{
Document doc = XMLManager.readFile(new File("GADEMO.xml"));
population = XMLManager.getGenotypeFromDocument(conf, doc);
}
catch (UnsupportedRepresentationException uex)
{
population = Genotype.randomInitialGenotype(conf);
}
catch (FileNotFoundException fex)
{
population = Genotype.randomInitialGenotype(conf);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 50; i++)
{
population.evolve();
}
long endTime = System.currentTimeMillis();
System.out.println("Total evolution time: " + (endTime – startTime) + " ms");
IChromosome bestSolutionSoFar = population.getFittestChromosome();
System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0));
System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1));
DataTreeBuilder builder = DataTreeBuilder.getInstance();
IDataCreators doc2 = builder.representGenotypeAsDocument(population);
XMLDocumentBuilder docbuilder = new XMLDocumentBuilder();
Document xmlDoc = (Document) docbuilder.buildDocument(doc2);
XMLManager.writeFile(xmlDoc, new File("GADEMO.xml"));
}
}
/**
* <p><i>Copyright: youhow.net (c) 2005–2008<br>
* @version 1.0 (<i>2008–6–12 neo([email protected])</i>)
*/
public class GaDemoFitnessFunction extends FitnessFunction
{
protected double evaluate(IChromosome a_subject)
{
int totalCoins = 1;
int numberOfGenes = a_subject.size();
for (int i = 0; i < numberOfGenes; i++)
{
totalCoins += (Integer) a_subject.getGene(i).getAllele();
}
return totalCoins;
}
}
遗传算法基础知识参考:http://www.hoodong.com/wiki/%E9%81%97%E4%BC%A0%E7%AE%97%E6%B3%95
目前为止有一条评论