📄 gajava.txt
字号:
private static Random random = new Random();
public Randomizer(int lower, int upper){
if(upper <= lower){
throw new IllegalStateException("Upper is smaller than lower!");
}
this.lower = lower;
this.upper = upper;
}
public Double nextDouble(){
return Double.valueOf(lower + (upper - lower) * random.nextDouble());
}
public Integer nextInteger(){
return Integer.valueOf(lower +random.nextInt(upper - lower));
}
public char[] nextBitArray(int length){
if(length <= 0){
throw new IllegalStateException("Length is less than ZERO!");
}
char[] temp = new char[length];
for(int i = 0; i < length ; i++){
temp[i] = random.nextBoolean() ? '1' : '0';
}
return temp;
}
}
染色体:
package edu.zsu.zouang.inheritence;
import java.util.Arrays;
import edu.zsu.zouang.util.Randomizer;
public class Chromosome implements Cloneable{
private double fitness = -1; //代表未计算适应函数
private double select = -1; // 选择概率
private char[] chromo; //染色体串
private Randomizer random;
private int lower;
private int upper;
public Chromosome(int lower, int upper, int length){
this.lower = lower;
this.upper = upper;
random = new Randomizer(lower, upper);
chromo = random.nextBitArray(length);
}
/** *//**
* 克隆一个染色体
*/
public Chromosome clone(){
Chromosome c = new Chromosome(lower,upper,chromo.length);
char[] temp = new char[c.chromo.length];
System.arraycopy(chromo, 0, temp, 0, chromo.length);
c.setChromo(temp);
return c;
}
public char[] getChromo() {
return chromo;
}
public void setChromo(char[] chromo) {
this.chromo = chromo;
}
public double getFitness() {
return fitness;
}
public void setFitness(double fitness) {
this.fitness = fitness;
}
public double getSelect() {
return select;
}
public void setSelect(double select) {
this.select = select;
}
}
适应函数接口:
package edu.zsu.zouang.inheritence;
public interface FitnessCalculate {
public double calculate(char[] chromosome);
}
本函数的适应函数,既然是求最大值,干脆用求解的函数来做适应函数
package edu.zsu.zouang.inheritence;
/** *//**
* 计算xyz*sin(xyz)最大值的遗传函数适应值
* 2007-4-25
* @author Zou Ang
* Contact <a href ="mailto:richardeee@gmail.com">Zou Ang</a>
*/
public class FunctionFitness implements FitnessCalculate {
public double calculate(char[] chromosome) {
/**//*
* x、y、z都用8位来编码,即x,y,z都属于[0,255]
*/
double x = 0;
double y = 0;
double z = 0;
for(int i = 0; i < 8; i++){
int j = i + 8;
int k = i + 16;
x = x + Math.pow(2, 7 - i) * (Integer.valueOf(chromosome[i]) - 48);
y = y + Math.pow(2, 7 - i) * (Integer.valueOf(chromosome[j]) - 48);
z = z + Math.pow(2, 7 - i) * (Integer.valueOf(chromosome[k]) - 48);
}
return x * y * z * Math.sin(x*y*z);
}
}
种群详细信息类:
package edu.zsu.zouang.inheritence;
public class GenerationDetail {
private double averageFitness = 0.0;
private double maxFitness = 0.0;
private double minFitness = 0.0;
public double getAverageFitness() {
return averageFitness;
}
public void setAverageFitness(double averageFitness) {
this.averageFitness = averageFitness;
}
public double getMaxFitness() {
return maxFitness;
}
public void setMaxFitness(double maxFitness) {
this.maxFitness = maxFitness;
}
public double getMinFitness() {
return minFitness;
}
public void setMinFitness(double minFitness) {
this.minFitness = minFitness;
}
}
最后是主类:
package edu.zsu.zouang.inheritence;
import java.util.ArrayList;
import java.util.List;
import edu.zsu.zouang.util.Randomizer;
public class GeneticAlgorithm {
private int generation; //进化代数
private int population; //种群数量
private double crossoverPossibility; //繁殖概率
private double mutationPossibility; //变异概率
private FitnessCalculate calculator = new FunctionFitness(); //适应函数计算
private List<Chromosome> clist = new ArrayList<Chromosome>();
private Randomizer random1; //随机数生成器1,用于生成变异位和交配位
private Randomizer random2 = new Randomizer(0,1); //随机数生成器2,用于生成0-1之间的概率
private GenerationDetail detail = new GenerationDetail();
public GeneticAlgorithm(int population, double sp, double cp, double mp,int length){
this.population = population;
this.crossoverPossibility = cp;
this.mutationPossibility = mp;
random1 = new Randomizer(0,length - 1);
generatePopulation(0,255,length); //用24位表示一组x,y,z的值
}
/** *//**
* 生成初始种群
* @param lower
* @param upper
* @param length
*/
private void generatePopulation(int lower, int upper, int length){
//随机生成染色体
for(int i = 0; i < population; i ++){
clist.add(new Chromosome(lower,upper,length));
}
//计算染色体的适应值
evaluate();
}
/** *//**
* 计算群体的适应值
*/
private void evaluate(){
double sum = 0.0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for(Chromosome c : clist){
double fitness = calculator.calculate(c.getChromo());
if(fitness > max){
max = fitness;
}
if(fitness < min){
min = fitness;
}
c.setFitness(fitness);
sum += fitness;
}
detail.setMaxFitness(max);
detail.setMinFitness(min);
detail.setAverageFitness(sum/population);
for(Chromosome c : clist){
c.setSelect((c.getFitness())/sum); //设置选择概率
}
}
/** *//**
* 在后代中选择新种群
*/
private void selectPopulation(){
List<Chromosome> tempList = new ArrayList<Chromosome>();
for(Chromosome c : clist){
long expectation = Math.round(c.getSelect() * population);
for(int i = 0; i < expectation; i ++){
tempList.add(c.clone());
}
}
//如果选择种群数量大于种群规定数量,则淘汰适应值最小的染色体
while(tempList.size() > population){
int location = 0;
double min = tempList.get(0).getFitness();
for(int i = 0 ; i < tempList.size(); i ++){
if(tempList.get(i).getFitness() < min){
location = i;
}
}
tempList.remove(location);
}
//如果选择种群数量小于种群规定数量,则加入适应值最大的染色体
while(tempList.size() < population){
int location = 0;
double max = tempList.get(0).getFitness();
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).getFitness() > max){
location = i;
}
}
tempList.add(tempList.get(location).clone());
}
clist = tempList;
}
/** *//**
* 交配两个染色体
* @param c1
* @param c2
* @param location
*/
private void crossover(Chromosome c1, Chromosome c2){
if(c1.getChromo().length != c2.getChromo().length){
throw new IllegalStateException("染色体长度不同!");
}
//交换染色体上的基因
//随机确定交配位
int location = random1.nextInteger();
for(int i = location ; i < c1.getChromo().length; i ++){
char temp;
temp = c1.getChromo()[i];
c1.getChromo()[i] = c2.getChromo()[i];
c2.getChromo()[i] = temp;
}
}
/** *//**
* 交配整个种群,完成一次进化
*
*/
public void crossoverPopulation(){
for(int j = 0; j < population; j ++){
for(int i = 0; i < population - 1; i++){
double temp = random2.nextDouble();
if(temp < crossoverPossibility){//在交配概率之内
crossover(clist.get(i), clist.get(i + 1));
}
}
double mutation = random2.nextDouble();
if(mutation < mutationPossibility){//在变异概率之内
mutation(clist.get(j));
}
}
//重新计算群体适应值
evaluate();
//重新选择种群
selectPopulation();
generation ++;
}
//随机变异一位
private void mutation(Chromosome ch){
int location = random1.nextInteger();
char c = ch.getChromo()[location];
if(c == '1'){
ch.getChromo()[location] = '0';
}else{
ch.getChromo()[location] = '1';
}
}
public void printDetail(){
System.out.println("/*****************************************");
System.out.println("* -----遗传算法报告----- ");
System.out.println("* 当前是第" + generation + "代");
System.out.println("* 当前种群平均适应值为: " + detail.getAverageFitness());
System.out.println("* 其中最大适应值为:" + detail.getMaxFitness());
System.out.println("* 其中最小适应值为:" + detail.getMinFitness());
System.out.println("*******************************************/");
}
public static void main(String[] args){
//种群数量:30
//选择概率:0.0
//交配概率:0.9
//变异概率: 0.01
GeneticAlgorithm ga = new GeneticAlgorithm(30,0.0,0.9,0.01,24);
for(int i = 0; i < 5; i ++){
ga.crossoverPopulation();
}
ga.printDetail();
for(int j = 0; j < 25; j++){
ga.crossoverPopulation();
}
ga.printDetail();
for(int k = 0; k < 1000; k++){
ga.crossoverPopulation();
}
ga.printDetail();
}
}
输出的结果是
/** *//*****************************************
* -----遗传算法报告-----
* 当前是第5代
* 当前种群平均适应值为: 7592451.0488077225
* 其中最大适应值为:9031331.437029611
* 对应最大适应值的染色体为:111011101101010010111000
* 其中最小适应值为:-1.2521097155031694E7
* 其中对应最小适应值的染色体为111011101101010011111011
*******************************************/
/** *//*****************************************
* -----遗传算法报告-----
* 当前是第30代
* 当前种群平均适应值为: 8785113.746617064
* 其中最大适应值为:9836674.727850026
* 对应最大适应值的染色体为:111111101101010010111000
* 其中最小适应值为:-1.1676031572464054E7
* 其中对应最小适应值的染色体为111011101101010011111000
*******************************************/
/** *//*****************************************
* -----遗传算法报告-----
* 当前是第1030代
* 当前种群平均适应值为: 8763072.724911185
* 其中最大适应值为:9836674.727850026
* 对应最大适应值的染色体为:111111101101010010111000
* 其中最小适应值为:-9580464.117842415
* 其中对应最小适应值的染色体为111101101101010010111000
*******************************************/
遗传算法的JAVA实现4
2008-06-19 01:20:33 本文已公布到博客频道校园·教育分类
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Population {
private ArrayList m_chromosomes = new ArrayList();
private Chromosome m_fittestChromosome=null;
private
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -