java 遗传算法_[原]遗传算法Java实现源代码

【Title】[原]遗传算法Java实现源代码

【Date】2013-04-07

【Abstract】以前学习遗传算法时,用Java实现的遗传算法程序,现整理分享出来。

【Keywords】wintys、遗传、算法、algorithm、种群、基因、个体、进化、染色体、适应度、Rosenbrock

【Environment】Windows 7、PowerDesigner16

【Author】wintys (wintys@gmail.com) http://wintys.cnblogs.com

【URL】http://www.cnblogs.com/wintys/archive/2013/04/07/genetic_algorithms.html

【Content】:

1、简介

此程序是对照《遗传算法原理及应用》(周明、孙树栋编著),附录所列C程序改编而来,用Java实现的遗传算法程序。相关理论请参考《遗传算法原理及应用》。

2、类图

类图由源代码经PowerDesigner反向生成。

8adb6c49d2bac275add048ff85aa9c1f.png

(类图)

3、代码

3.1、染色体

//染色体:Chromesone.java

class Chromosome implements Cloneable{

private StringBuffer chromosome;

private int chromosomeLength;//染色体长度

private char defaultChar; //默认基因填充字符

public Chromosome(int chromosomeLength){

chromosome = new StringBuffer(chromosomeLength);

chromosome.setLength(chromosomeLength);

defaultChar = '0';

this.chromosomeLength = chromosomeLength;

}

//设置基因

public boolean setGene(int begin , int end , String gene){

int len = gene.length();

if(len > end - begin + 1)

return false;

//index => chromosome , idx => gene

for (int index = begin , idx = 0; index <= end; index++ , idx++) {

if(idx < len)

chromosome.setCharAt(index , gene.charAt(idx));

else

chromosome.setCharAt(index , defaultChar);

}

return true;

}

//获取基因

public String getGene(int begin , int end){

char[] dest = new char[end - begin + 1];

chromosome.getChars(begin , end + 1 , dest , 0);

return new String(dest);

}

public int getLength(){

return chromosomeLength;

}

public String toString(){

return chromosome.toString();

}

@Override

public     Object clone()throws CloneNotSupportedException{

Chromosome c = null;

try{

c = (Chromosome)super.clone();

c.chromosome = new StringBuffer(chromosome);

}catch(CloneNotSupportedException e ){

System.out.println(e.getMessage());

}

return c;

}

}

3.2、个体

3.2.1、抽象个体

//Individual.java

abstract class Individual implements Cloneable{

protected Chromosome chrom;//个体基因型:一个基因型染色体由多个基因组成

protected int genelen;//基因长度

protected double fitness;//适应度

protected double targetValue;//目标函数值

public abstract void coding();//编码

public abstract void decode();//解码

public abstract void calFitness();//计算个体适应度

public abstract void generateIndividual();//随机产生个体

public abstract void calTargetValue();//获取目标函数值

public double getFitness(){

return fitness;

}

public double getTargetValue(){

return targetValue;

}

public int getChromlen(){

return chrom.getLength();

}

public boolean setChrom(int begin , int end , String gene){

return chrom.setGene(begin,end,gene);

}

public String getChrom(int begin , int end){

return chrom.getGene(begin,end);

}

public void mutateSingleBit(int index){

String gene , gn;

gene = chrom.getGene(index , index);

gn = gene.equals("0") ? "1":"0";

chrom.setGene(index , index , gn);

}

@Override

public Object clone(){

Individual indv = null;

try{

indv = (Individual)super.clone();

indv.chrom = (Chromosome)chrom.clone();

}catch(CloneNotSupportedException e ){

System.out.println(e.getMessage());

}

return indv;

}

}

3.2.2、Rosenbrock个体实现

//RosenbrockIndividual.java

class RosenbrockIndividual extends Individual {

private double x1 , x2; // 个体表现型

//基因型chromosome由 (x1 , x2)编码而成

RosenbrockIndividual(int chromlen){

genelen = 10;

chrom = new Chromosome(chromlen);

}

//编码

public void coding(){

String code1,code2;

code1 = codingVariable(x1);

code2 = codingVariable(x2);

chrom.setGene(0 , 9 , code1);

chrom.setGene(10, 19 , code2);

}

//解码

public void decode(){

String gene1,gene2;

gene1 = chrom.getGene(0 , 9);

gene2 = chrom.getGene(10 , 19);

x1 = decodeGene(gene1);

x2 = decodeGene(gene2);

}

//计算目标函数值

public  void calTargetValue(){

decode();

targetValue = rosenbrock(x1 , x2);

}

//计算个体适应度

public void calFitness(){

fitness = getTargetValue();

}

private String codingVariable(double x){

double y = (((x + 2.048) * 1023) / 4.096);

String code = Integer.toBinaryString((int) y);

StringBuffer codeBuf = new StringBuffer(code);

for(int i = code.length(); i

codeBuf.insert(0,'0');

return codeBuf.toString();

}

private double decodeGene(String gene){

int value ;

double decode;

value = Integer.parseInt(gene, 2);

decode = value/1023.0*4.096 - 2.048;

return decode;

}

public String toString(){

String str = "";

///str = "基因型:" + chrom + "  ";

///str+= "表现型:" + "[x1,x2]=" + "[" + x1 + "," + x2 + "]" + "\t";

str+="函数值:" + rosenbrock(x1 , x2) + "\n";

return     str;

}

/**

*Rosenbrock函数:

*f(x1,x2) = 100*(x1**2 - x2)**2 + (1 - x1)**2

*在当x在[-2.048 , 2.048]内时,

*函数有两个极大点:

*f(2.048 , -2.048) = 3897.7342

*f(-2.048,-2.048) = 3905.926227

*其中后者为全局最大点。

*/

public static double rosenbrock(double x1 , double x2){

double fun;

fun = 100*Math.pow((x1*x1 - x2) , 2) + Math.pow((1 - x1) , 2);

return fun;

}

//随机产生个体

public void generateIndividual(){

x1 = Math.random() * 4.096 - 2.048;

x2 = Math.random() * 4.096 - 2.048;

//同步编码和适应度

coding();

calTargetValue();

calFitness();

}

}

3.3、种群

//Population.java

class Population{

private int generation; //种群的代数

private int size;            //群体大小

private Individual[] pop;   //种群

private double averageFitness;    //平均适应度

private double[] relativeFitness;    //相对适应度

private int chromlen;//基因长度

Individual bestIndividual;//当前代适应度最好的个体

Individual worstIndividual;//当前代适应度最差的个体

Individual currentBest;//到目前代为止最好的个体

private int worstIndex;//bestIndividual对应的数组下标

public Population(int size){

this.generation = 0;

this.size = size;

this.pop = new Individual[size];

this.averageFitness = 0;

this.relativeFitness = new double[size];

this.chromlen = 20;

for(int i = 0; i < size; i++){

pop[i] = new RosenbrockIndividual(chromlen);

}

}

//初始化种群

public void initPopulation(){

for(int i = 0;i < size;i++){

pop[i].generateIndividual();

}

findBestAndWorstIndividual();

}

//----------------------------------------------------

//比例选择

public void  select(){

double[] rouletteWheel; //赌盘

Individual[] childPop = new Individual[size];

calRelativeFitness();

//产生赌盘

rouletteWheel  = new double[size];

rouletteWheel[0] = relativeFitness[0];

for(int i=1;i

rouletteWheel[i] = relativeFitness[i] + rouletteWheel[i - 1];

}

rouletteWheel[size - 1] = 1;

//进行赌盘选择,产生新种群

for(int i = 0;i < size ; i++){

double rnd = rand();

for(int j = 0; j < size; j++){

if(rnd < rouletteWheel[j]){

childPop[i] = pop[j];

break;

}

}

}

for(int i = 0;i < size; i++){

pop[i] = childPop[i];

}

//return     childPop;

}

//求总适应度

private double calTotalFitness(){

double total = 0;

for(int i = 0 ; i < size ;i++)

total += pop[i].getFitness();

return total;

}

//计算相对适应度

public double[] calRelativeFitness(){

double totalFitness = calTotalFitness();

for(int i = 0 ;i < size ; i++){

relativeFitness[i] = pop[i].getFitness() / totalFitness;

}

return relativeFitness;

}

//================================

//------------------------------------------------------

//单点交叉

public void crossover(){

for(int i = 0 ; i < size/2*2; i+=2){

int rnd;

//随机两两配对

rnd = rand(i , size);

if(rnd != i)

exchange(pop , i , rnd);

rnd = rand(i , size);

if(rnd != i+1)

exchange(pop , i + 1 , rnd);

//交叉

double random = rand();

if(random < GeneticAlgorithms.crossoverRate){

cross(i);

}

}

}

//执行交叉操作

private void cross(int i){

String chromFragment1,chromFragment2;//基因片段

int rnd = rand(0 , getChromlen() - 1);//交叉点为rnd之后,可能的位置有chromlen - 1个.

chromFragment1 = pop[i].getChrom(rnd + 1 , getChromlen() - 1);

chromFragment2 = pop[i+1].getChrom(rnd + 1 , getChromlen() - 1);

pop[i].setChrom(rnd + 1 , getChromlen() - 1 , chromFragment2);

pop[i+1].setChrom(rnd + 1 , getChromlen() - 1 , chromFragment1);

}

//产生随机数

private int rand(int start , int end){//产生区间为[start , end)的随机整数

return (int)(rand()*(end - start) + start);

}

//交换

private void exchange(Individual[] p ,int src , int dest){

Individual temp;

temp = p[src];

p[src] = p[dest];

p[dest] = temp;

}

//==============================

//-----------------------------------------------------

//变异

public void mutate(){

for(int i = 0 ; i < size;i++){

for(int j = 0 ;j < getChromlen(); j++){

if(rand() < GeneticAlgorithms.mutateRate){

pop[i].mutateSingleBit(j);

///System.out.print("变异"+ i +" - "+ j + "  ");///

}

}

}

}

//==============================

//-----------------------------------------------------

//进化

public void evolve(){

select();

crossover();

mutate();

evaluate();

}

//==============================

//计算目标函数值、适应度、找出最优个体。

public void evaluate(){

//同步目标函数值和适应度

for(int i = 0; i < size; i++){

pop[i].calTargetValue();

pop[i].calFitness();

}

//使用最优保存策略(Elitist Model)保存最优个体

findBestAndWorstIndividual();

pop[worstIndex] = (Individual)currentBest.clone();

generation++;

}

//找出适应度最大的个体

public void findBestAndWorstIndividual(){

bestIndividual = worstIndividual = pop[0];

for(int i = 1; i

if(pop[i].fitness > bestIndividual.fitness){

bestIndividual = pop[i];

}

if(pop[i].fitness < worstIndividual.fitness){

worstIndividual = pop[i];

worstIndex = i;

}

}

if( generation == 0 ){//初始种群

currentBest = (Individual)bestIndividual.clone();

}else{

if(bestIndividual.fitness > currentBest.fitness)

currentBest = (Individual)bestIndividual.clone();

}

}

//判断进化是否完成

public boolean isEvolutionDone(){

if(generation < GeneticAlgorithms.maxGeneration)

return false;

return true;

}

//计算平均适应度

public double calAverageFitness(){

for(int i = 0 ; i < size; i++){

averageFitness += pop[i].getFitness();

}

averageFitness/=size;

return averageFitness;

}

//产生随机数

private double rand(){

return Math.random();

}

public int getChromlen(){

return chromlen;

}

public void setGeneration(int generation){

this.generation = generation;

}

public int getGeneration(){

return generation;

}

/*

public String printPop(Individual[] pop){

String str="";

for(int i = 0 ; i < size ; i++)

str += pop[i];

return str;

}*/

public String toString(){

String str="";

for(int i = 0 ; i < size ; i++)

str += pop[i];

return str;

}

}

3.4 测试

//GeneticAlgorithms.java 给定参数,测试遗传算法

import java.io.*;

//2008-11-21

class GeneticAlgorithms{

public static double crossoverRate;//交叉概率

public static double mutateRate;//变异概率

public static int maxGeneration;//进化代数

public static int populationSize;//群体大小

static {

//crossoverRate = 0.6;

//mutateRate = 0.001;

//maxGeneration  = 100;

//populationSize = 500;

maxGeneration  = 100;

populationSize = 500;

crossoverRate = 0.6;

mutateRate = 0.001;

}

public static void main(String[] args)throws IOException{

FileWriter fw = new FileWriter("result.txt");

BufferedWriter bw = new BufferedWriter(fw);

PrintWriter pw = new PrintWriter(bw);

Population pop = new Population(populationSize);

pop.initPopulation();

pw.println("初始种群:\n" + pop);

while(!pop.isEvolutionDone()){

pop.evolve();

pw.print("第" + pop.getGeneration() + "代Best:" + pop.bestIndividual );

pw.print("第" + pop.getGeneration()  + "代current:" + pop.currentBest );

pw.println("");

}

pw.println();

pw.println("第"+ pop.getGeneration()  + "代群体:\n" + pop);

pw.close();

}

public void print(){

}

}

【Reference】

[1]《遗传算法原理及应用》(周明、孙树栋编著)

【Attachment】

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/487948.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

防止表单按钮多次提交

1. <form namefm method"POST" action"/"><p>按钮变灰</p>name: <input type"text" name"name"/><input type"button" value"提交" οnclick"javascript:{this.disabledtrue;doc…

理解进化的五座“桥”

来源&#xff1a;原理古往今来&#xff0c;达尔文是不是最具革命性的科学家之一&#xff1f;如果革命指的是把一个已经公认的学说颠倒过来&#xff0c;那挑战者还有很多&#xff0c;至少包括牛顿、爱因斯坦和量子力学的奠基者。这些物理学家超群绝伦的智慧能量&#xff0c;可能…

ACM训练计划建议(转)

ACM训练计划建议 From&#xff1a;freecode# Date&#xff1a;2015/5/20 前言&#xff1a; 老师要我们整理一份训练计划给下一届的学弟学妹们&#xff0c;整理出来了&#xff0c;费了不少笔墨&#xff0c;就也将它放到博客园上供大家参考。 菜鸟之作&#xff0c;大牛勿喷&…

java下载文件夹_java如何通过共享目录下载文件夹(有子文件夹)到本地目录?...

有没有大神会操作的&#xff1f;下面的代码只能下载文件夹下只是文件的&#xff0c;不能下载文件夹下包含子文件夹的文件public static void getShareFile(){System.out.println("开始");NtlmPasswordAuthentication auth new NtlmPasswordAuthentication("192…

【AI】【机器人】AI与机器人的42个终极问题与解答

来源&#xff1a;产业智能官 未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评测体系&#xff0c;开展世界人工智能智商评测&#xff1b;开展互联网&#xff08;城市&#xff09;云脑研究计划&#xff0c;构建互联网&#xff08;城市&#xff09;云脑技术和企业图…

With you With me

With you With me 回来了&#xff0c;一起从零开始... 据说每一个敢说从零开始的都特么是个大牛&#xff08;for example hiphop-Man欧阳靖&#xff09;... 这些年的时间多有自己问自己&#xff0c;你特么到底在迷茫什么&#xff0c;想不通就去撞墙啊&#xff01;&#xff01;…

java集合转字符串,Java集合将字符串转换为字符列表

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?List charList new ArrayList("abc".toCharArray());解决方案You will have to either use a loop, or create a collectio…

Linux服务器iops性能测试-fio

FIO是测试IOPS的非常好的工具&#xff0c;用来对硬件进行压力测试和验证&#xff0c;支持13种不同的I/O引擎&#xff0c;包括:sync,mmap, libaio, posixaio, SG v3, splice, null, network, syslet,guasi, solarisaio 等等。 fio 官网地址&#xff1a;http://freecode.com/proj…

志澄观察:卫星互联网——太空经济新动力

图1 卫星互联网的组成来源&#xff1a;远望智库 引 言2020年04月20日国家发改委首次明确&#xff0c;将卫星互联网列入我国新型基础设施的范围&#xff0c;这项重大的战略决策&#xff0c;大大鼓舞了我国商业航天行业的信心。另一方面&#xff0c;2020年3月27日,在发展低…

java中位数_java 计算中位数方法

最近工作需要 要求把python的代码写成java版本&#xff0c;python中有一个np.median()求中位数的方法&#xff0c;java决定手写一个先说说什么是中位数&#xff1a;中位数就是中间的那个数&#xff0c;如果一个集合是奇数个&#xff0c;那么中位数就是按大小排列后&#xff0c;…

Unity 找到隐藏的UGUI

问题描述&#xff1a;在项目中需要在一开始将一个UGUI隐藏&#xff0c;之后在特定的时候再显示。 本来想的办法是在需要显示的时候调用GameObject.Find()找到这个UI并设置active&#xff0c; 但发现找出来的为null&#xff0c;经查阅资料发现GameObject.Find()只能find没有被隐…

一文读懂电磁学发展史[图文版]

来源&#xff1a;电子万花筒电磁学或称电动力学或经典电动力学。之所以称为经典&#xff0c;是因为它不包括现代的量子电动力学的内容。电动力学这样一个术语使用并不是非常严格&#xff0c;有时它也用来指电磁学中去除了静电学、静磁学后剩下的部分&#xff0c;是指电磁学与力…

java判断优先级代码_java运算符的优先级

下图是每种运算符的优先级&#xff0c;按照运算先后顺序排序(优先级相同的情况下&#xff0c;按照从左到右的顺序依次运算)优先级描述运算符1括号()、[]2正负号、-3自增自减&#xff0c;非、--、!4乘除&#xff0c;取余*、/、%5加减、-6移位运算<>、>>>7大小关系…

python语言学习笔记整理

什么是程序? 程序等于数据结构加算法&#xff0c;那么数据结构是一个静态的东西&#xff0c;算法是一个动态的东西&#xff0c;我们用一个新的语言编写这个程序&#xff0c;我们要考虑到语言也主要由数据结构和算法相关的东西&#xff0c;或静态或动态的东西来构成&#xff0c…

人机智能既不是人类智能,也不是人工智能

来源&#xff1a;人机与认知实验室从前&#xff0c;一个教授&#xff0c;去一个穷乡僻壤里头坐船过江&#xff0c;就问船上的船工&#xff1a;你学点数学没有&#xff1f;没有。你学点物理没有&#xff1f;没有。那懂不懂计算机啊&#xff1f;不懂。教授感叹这三样都不会&#…

使用HDFS客户端java api读取hadoop集群上的信息

本文介绍使用hdfs java api的配置方法。 1、先解决依赖&#xff0c;pom <dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-client</artifactId><version>2.7.2</version><scope>provided</scope>&l…

USACO 1.2 Milking Cows (枚举)

标记数组&#xff08;哈希&#xff09; 1e6的范围&#xff0c;开一个char数组全然能够&#xff0c;有人为1&#xff0c;无人为0&#xff0c;注意边界就可以。最后线性扫描就可以。时间复杂度&#xff0c;应该是O(n),n为最后结束的时间。缺点就是……比較慢 /*ID:twd30651PROG:m…

赛博朋克之后的科幻建筑是什么样的?

来源&#xff1a;苇草智酷粗略地浏览一下 tumblr 或 Pinterest 论坛的兴趣推送&#xff0c;你会发现我最近痴迷于科幻作品美学。更具体地说&#xff0c;我一直在想&#xff0c;在过去35年甚至更久时间里流行的设计美学——赛博朋克&#xff08;Cyberpunk&#xff09;之后&#…

牛客网java_牛客网java

1&#xff1a;下列代码运行的结果是什么&#xff1f;public classP {public static int abc 123;static{System.out.println("P is init");}}public class S extendsP {static{System.out.println("S is init");}}public classTest {public static voidma…

C#代理多样性

一、代理 首先我们要弄清代理是个什么东西。别让一串翻译过来的概念把大家搞晕了头。有的文章把代理称委托、代表等&#xff0c;其实它们是一个东西&#xff0c;英文表述都是“Delegate”。由于没有一本权威的书来规范这个概念&#xff0c;所以现在网上对它的称谓不一。本文我将…