?? gajava.txt
字號:
-import java.sql.*;
import java.util.*;
import java.math.*;
import com.microsoft.jdbc.sqlserver.SQLServerDriver;
public class GA
{
//數據庫鏈接設置
String dbmsdriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://csy:1433;DatabaseName=GA_DATA";
public Connection con = null;
Statement stmt = null;
String sqlstr;
public String[]population = new String[40]; //存放父代種群
public String[]childrenpopulation = new String[40]; //存放子代種群
public double[]farray = new double[40]; //存放個體的適應度
//存放個體適應度的和,最優函數值,雜交概率
public double sumf, bestresult, mutationprobability,precision;
public String bestroot; //存放最優解對應的二進制串
//二進制轉換為十進制
public int BiToDec(String BiString)
{
int i, strlen, coefficient, result;
strlen = BiString.length();
coefficient = 1;
result = 0;
for (i = strlen - 1; i >= 0; i--)
{
if (BiString.substring(i, i + 1).equalsIgnoreCase("1"))
result = result + coefficient;
coefficient = coefficient * 2;
}
return result;
}
//計算個體適應度
public double EvaluateIndividaul(String BiString)
{
double result;
Integer dec;
dec = BiToDec(BiString);
//result = - 1+dec.doubleValue() * c.doubleValue() / d.doubleValue();
result = - 1 + dec.doubleValue() * precision;
result = result * Math.sin(10 * 3.14159265358979 * result) + 2.0;
return result;
}
//初始化種群
public void innitial()
{
//鏈接數據庫
try
{
Class.forName(dbmsdriver).newInstance();
con = DriverManager.getConnection(dbURL, "sa", "wq");
stmt = con.createStatement();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
Integer c, d;
c = 3;//自變量區間寬度:2-(-1)=3
d = 4194304;//2^22;
precision = c.doubleValue() / d.doubleValue();//精度
mutationprobability = 0.001;//設定編譯概率
String individaul = "";
Random ran = new Random();
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 22; j++)
{
if (ran.nextBoolean())
individaul += '1';
else
individaul += '0';
}
population[i] = individaul;
individaul = "";
}
}
//計算種群適應度
public void Evaluate()
{
sumf = 0;
bestresult = 0;
for (int i = 0; i < 40; i++)
{
farray[i] = EvaluateIndividaul(population[i]);
sumf = sumf + farray[i];
//記錄最優個體
if (farray[i] >= bestresult)
{
bestresult = farray[i];
bestroot = population[i];
}
}
}
//選擇操作,使用輪盤賭選擇法
public void Select()
{
double SelectProbability, Pi;
for (int i = 0; i < 40; i++)
{
Random ran = new Random();
SelectProbability = ran.nextDouble(); //選擇概率
Pi = 0;
for (int j = 0; j < 40; j++)
{
Pi = Pi + farray[j] / sumf;
if (SelectProbability < Pi)
{
childrenpopulation[i] = population[j];
break;
}
}
}
}
//雜交操作
public void Crossover()
{
int i, crossoverpos;
String parent1, parent2;
String temp1, temp2;
for (i = 0; i < 40; i = i + 2)
{
parent1 = childrenpopulation[i];
parent2 = childrenpopulation[i + 1];
Random ran = new Random();
crossoverpos = ran.nextInt(22);
if (crossoverpos == 0 || crossoverpos == 22)
;
else
{
temp1 = parent1.substring(0, crossoverpos)
+ parent2.substring(crossoverpos);
temp2 = parent2.substring(0, crossoverpos)
+ parent1.substring(crossoverpos);
childrenpopulation[i] = temp1;
childrenpopulation[i + 1] = temp2;
}
}
}
//變異操作
public void Mutation()
{
int mutationpos;
for (int i = 0; i < 40; i++)
{
Random ran = new Random();
if (mutationprobability > ran.nextDouble())
{
mutationpos = ran.nextInt(22);
if (mutationpos != 0)
{
if (childrenpopulation[i].substring(mutationpos,mutationpos + 1).equalsIgnoreCase("1"))
childrenpopulation[i] = childrenpopulation[i].substring(0, mutationpos)
+ "0" +childrenpopulation[i].substring(mutationpos + 1);
else
childrenpopulation[i] = childrenpopulation[i].substring(0, mutationpos)
+ "1" +childrenpopulation[i].substring(mutationpos + 1);
}
}
}
}
//把個體寫入數據庫,以分析個體的變化
public void SavePopulation(int k, int j)
{
try
{
for (int i = 0; i < 40; i++)
{
sqlstr ="INSERT INTO [POPULATION]([SelectMethod],[TestCount],[GENERATION], [INDIVIDAUL_INDEX],[BISTR])"
+ " values('roulette wheel selection',"
+ Integer.toString(k) + ","
+ Integer.toString(j) + ","
+ Integer.toString(i) + ","
+ "'" + population[i] + "')";
stmt.executeUpdate(sqlstr);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
//把最優解寫入數據庫
public void SaveBestValue(int k,int j)
{
double dbestroot;
Integer a;
a = BiToDec(bestroot);
//dbestroot = - 1+a.doubleValue() * b.doubleValue() / c.doubleValue();
dbestroot = - 1+a.doubleValue() * precision;
try
{
sqlstr =
"INSERT INTO [TESTDATA]([SelectMethod],[TestCount],[GenerationCount], [MaxValue],[BestRoot])"
+ " values('roulette wheel selection',"
+ Integer.toString(k) + ','
+ Integer.toString(j) + ','
+ Double.toString(bestresult) + ','
+ Double.toString(dbestroot) + ")";
stmt.executeUpdate(sqlstr);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
public void ClostDBConn()
{
try
{
con.close();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
//主函數
public static void main(String[]args)
{
//實驗次數
for (int k = 0; k < 1000; k++)
{
GA gatest = new GA();
gatest.innitial();
//每次實驗的最大代數
for (int j = 0; j < 50; j++)
{
gatest.Evaluate();
gatest.Select();
gatest.Crossover();
gatest.Mutation();
gatest.SavePopulation(k,j);//保存群體信息
//把產生的子代付給父代,為下一輪準備
for (int i = 0; i < 40; i++)
{
gatest.population[i] = gatest.childrenpopulation[i];
}
gatest.SaveBestValue(k,j);//保存最優解信息
//顯示進度
System.out.print(k);
System.out.print("次實驗|");
System.out.print(j);
System.out.println("代");
} //每次實驗代數
gatest.ClostDBConn();//關閉數據庫鏈接
} //實驗次數
} //main
//耗時38分9秒
}
我用java寫的遺傳算法的嚴重問題,程序沒錯,但不知道為什么結果總和預想的不同,實在是困惑,請幫忙啊!!!!
發表于: 2007-2-6 下午8:33 回復
源程序如下:
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.*;
public class GeneticAlgorithm {
/*
A. M:群體大小。一般取為20~100;
B. T:遺傳運算終止進化代數。一般取為100~500;
C. Pc:交叉概率。一般取為0.4~0.99;
D. Pm:變異概率。一般取為0.0001~0.1。
*/
/* Change any of these parameters to match your needs */
static int POPSIZE = 5; /* population size */
static int MAXGENS = 5; /* max. number of generations */
static int NVARS = 3; /* no. of problem variables */
static float PXOVER = 0.8f; /* probability of crossover */
static float PMUTATION = 0.3f; /* probability of mutation */
int E = 6;
int T = 120;
int generation; /* current generation no. */
int cur_best; /* best individual */
//FILE * galog; /* an output file */
BufferedReader infile;
FileReader in;
BufferedWriter outfile;
FileWriter out;
Genotype population[];
Genotype newpopulation[];
int p[][][] = { { {0, 1, 1}, {0, 0, 0}, {0, 1, 1}, {0, 0, 0}
}, { {1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 1, 1}, {0, 0, 0}, {0, 1, 1}
}, { {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, {1, 0, 0}
}
};
double a[][][] = { { {10, 1, 1}, {10, 2, 4}, {1, 2.3, 1}, {3, 5, 1}
}, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 2}, {2, 0.7, 4}
}, { {2.5, 1.2, 3.4}, {10, 1, 1}, {1, 0.8, 13}, {1.9, 1, 1}
}, { {0.4, 3, 2.3}, {1, 2.1, 4}, {3.2, 1, 0.5}, {1, 1.4, 1.6}
}
};
double u[][][] = { { {2, 1, 1}, {3, 2, 4}, {1, 2.3, 1}, {3, 2, 1}
}, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 0.9}, {2, 0.7, 4}
}, { {0.7, 1.2, 3.4}, {0.5, 1, 1}, {1, 0.8, 0.9}, {1.9, 1, 1}
}, { {0.4, 3, 2.3}, {1, 2.1, 4}, {0.4, 1, 0.3}, {1, 1.4, 0.8}
}
};
double s[][][] = { { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
}
};
GeneticAlgorithm() {
population = new Genotype[POPSIZE + 1]; /* population */
newpopulation = new Genotype[POPSIZE + 1]; /* new population; */
for (int i = 0; i <= POPSIZE; i++) {
population[i] = new Genotype();
newpopulation[i] = new Genotype();
}
}
class Genotype /* genotype (GT), a member of the population */
{
double gene[];
double fitness;
double upper[];
double lower[];
double cfitness;
double rfitness;
Genotype() {
gene = new double[NVARS]; /* a string of variables */
fitness = 0; /* GT's fitness */
upper = new double[NVARS];
lower = new double[NVARS]; /* GT's variables lower bound */
rfitness = 0;
cfitness = 0;
}
}
/***************************************************************/
/* Initialization function: Initializes the values of genes */
/* within the variables bounds. It also initializes (to zero) */
/* all fitness values for each member of the population. It */
/* reads upper and lower bounds of each variable from the */
/* input file `gadata.txt'. It randomly generates values */
/* between these bounds for each gene of each genotype in the */
/* population. The format of the input file `gadata.txt' is */
/* var1_lower_bound var1_upper bound */
/* var2_lower_bound var2_upper bound ... */
/***************************************************************/
void initialize() {
String str;
String parts[];
try {
in = new FileReader("gadata.txt");
infile = new BufferedReader(in);
int i, j;
double lbound, ubound;
while ((str = infile.readLine()) != null) {
parts = str.split(" ");
for (i = 0; i < NVARS; i++) {
lbound = Double.parseDouble(parts[0]);
ubound = Double.parseDouble(parts[1]);
for (j = 0; j < POPSIZE; j++) {
population[j].fitness = 0;
population[j].rfitness = 0;
population[j].cfitness = 0;
population[j].lower[i] = lbound;
population[j].upper[i] = ubound;
population[j].gene[i] = randval(population[j].lower[i],
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -