日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

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

發(fā)布時(shí)間:2024/7/19 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 遗传算法_[原]遗传算法Java实现源代码 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

【Title】[原]遺傳算法Java實(shí)現(xiàn)源代碼

【Date】2013-04-07

【Abstract】以前學(xué)習(xí)遺傳算法時(shí),用Java實(shí)現(xiàn)的遺傳算法程序,現(xiàn)整理分享出來(lái)。

【Keywords】wintys、遺傳、算法、algorithm、種群、基因、個(gè)體、進(jìn)化、染色體、適應(yīng)度、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、簡(jiǎn)介

此程序是對(duì)照《遺傳算法原理及應(yīng)用》(周明、孫樹(shù)棟編著),附錄所列C程序改編而來(lái),用Java實(shí)現(xiàn)的遺傳算法程序。相關(guān)理論請(qǐng)參考《遺傳算法原理及應(yīng)用》。

2、類圖

類圖由源代碼經(jīng)PowerDesigner反向生成。

(類圖)

3、代碼

3.1、染色體

//染色體:Chromesone.java

class Chromosome implements Cloneable{

private StringBuffer chromosome;

private int chromosomeLength;//染色體長(zhǎng)度

private char defaultChar; //默認(rèn)基因填充字符

public Chromosome(int chromosomeLength){

chromosome = new StringBuffer(chromosomeLength);

chromosome.setLength(chromosomeLength);

defaultChar = '0';

this.chromosomeLength = chromosomeLength;

}

//設(shè)置基因

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、個(gè)體

3.2.1、抽象個(gè)體

//Individual.java

abstract class Individual implements Cloneable{

protected Chromosome chrom;//個(gè)體基因型:一個(gè)基因型染色體由多個(gè)基因組成

protected int genelen;//基因長(zhǎng)度

protected double fitness;//適應(yīng)度

protected double targetValue;//目標(biāo)函數(shù)值

public abstract void coding();//編碼

public abstract void decode();//解碼

public abstract void calFitness();//計(jì)算個(gè)體適應(yīng)度

public abstract void generateIndividual();//隨機(jī)產(chǎn)生個(gè)體

public abstract void calTargetValue();//獲取目標(biāo)函數(shù)值

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個(gè)體實(shí)現(xiàn)

//RosenbrockIndividual.java

class RosenbrockIndividual extends Individual {

private double x1 , x2; // 個(gè)體表現(xiàn)型

//基因型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);

}

//計(jì)算目標(biāo)函數(shù)值

public? void calTargetValue(){

decode();

targetValue = rosenbrock(x1 , x2);

}

//計(jì)算個(gè)體適應(yīng)度

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+= "表現(xiàn)型:" + "[x1,x2]=" + "[" + x1 + "," + x2 + "]" + "\t";

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

return ?? ?str;

}

/**

*Rosenbrock函數(shù):

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

*在當(dāng)x在[-2.048 , 2.048]內(nèi)時(shí),

*函數(shù)有兩個(gè)極大點(diǎn):

*f(2.048 , -2.048) = 3897.7342

*f(-2.048,-2.048) = 3905.926227

*其中后者為全局最大點(diǎn)。

*/

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;

}

//隨機(jī)產(chǎn)生個(gè)體

public void generateIndividual(){

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

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

//同步編碼和適應(yīng)度

coding();

calTargetValue();

calFitness();

}

}

3.3、種群

//Population.java

class Population{

private int generation; //種群的代數(shù)

private int size;?? ??? ??? ?//群體大小

private Individual[] pop;?? //種群

private double averageFitness;??? //平均適應(yīng)度

private double[] relativeFitness;?? ?//相對(duì)適應(yīng)度

private int chromlen;//基因長(zhǎng)度

Individual bestIndividual;//當(dāng)前代適應(yīng)度最好的個(gè)體

Individual worstIndividual;//當(dāng)前代適應(yīng)度最差的個(gè)體

Individual currentBest;//到目前代為止最好的個(gè)體

private int worstIndex;//bestIndividual對(duì)應(yīng)的數(shù)組下標(biāo)

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();

//產(chǎn)生賭盤

rouletteWheel? = new double[size];

rouletteWheel[0] = relativeFitness[0];

for(int i=1;i

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

}

rouletteWheel[size - 1] = 1;

//進(jìn)行賭盤選擇,產(chǎn)生新種群

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;

}

//求總適應(yīng)度

private double calTotalFitness(){

double total = 0;

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

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

return total;

}

//計(jì)算相對(duì)適應(yīng)度

public double[] calRelativeFitness(){

double totalFitness = calTotalFitness();

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

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

}

return relativeFitness;

}

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

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

//單點(diǎn)交叉

public void crossover(){

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

int rnd;

//隨機(jī)兩兩配對(duì)

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);

}

}

}

//執(zhí)行交叉操作

private void cross(int i){

String chromFragment1,chromFragment2;//基因片段

int rnd = rand(0 , getChromlen() - 1);//交叉點(diǎn)為rnd之后,可能的位置有chromlen - 1個(gè).

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);

}

//產(chǎn)生隨機(jī)數(shù)

private int rand(int start , int end){//產(chǎn)生區(qū)間為[start , end)的隨機(jī)整數(shù)

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 + "? ");///

}

}

}

}

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

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

//進(jìn)化

public void evolve(){

select();

crossover();

mutate();

evaluate();

}

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

//計(jì)算目標(biāo)函數(shù)值、適應(yīng)度、找出最優(yōu)個(gè)體。

public void evaluate(){

//同步目標(biāo)函數(shù)值和適應(yīng)度

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

pop[i].calTargetValue();

pop[i].calFitness();

}

//使用最優(yōu)保存策略(Elitist Model)保存最優(yōu)個(gè)體

findBestAndWorstIndividual();

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

generation++;

}

//找出適應(yīng)度最大的個(gè)體

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();

}

}

//判斷進(jìn)化是否完成

public boolean isEvolutionDone(){

if(generation < GeneticAlgorithms.maxGeneration)

return false;

return true;

}

//計(jì)算平均適應(yīng)度

public double calAverageFitness(){

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

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

}

averageFitness/=size;

return averageFitness;

}

//產(chǎn)生隨機(jī)數(shù)

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 測(cè)試

//GeneticAlgorithms.java 給定參數(shù),測(cè)試遺傳算法

import java.io.*;

//2008-11-21

class GeneticAlgorithms{

public static double crossoverRate;//交叉概率

public static double mutateRate;//變異概率

public static int maxGeneration;//進(jìn)化代數(shù)

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]《遺傳算法原理及應(yīng)用》(周明、孫樹(shù)棟編著)

【Attachment】

總結(jié)

以上是生活随笔為你收集整理的java 遗传算法_[原]遗传算法Java实现源代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。