遗传算法的C++代码实现教程.doc
遗传算法的C+代码实现教程此例程总共包含3个文件:main.c(主函数);GA.c(包含3个所用函数);GA.h(头文件),3个文件截图如下:用visual c+或者visual stutio创建工程,然后将上述3个文件包含进工程,编译运行即可。亲测可行!3个文件代码分别如下:1、 main.c:includeiostreaminclude"GA.h"using namespace std;/* GA demo求函数y=x*sin(10*pai*x)+2.0的最大值编码:浮点数,1位初始群体数:50变异概率:0。8进化代数:100取值范围:0,4变异步长:0.004注:因为是单数浮点数编码,所以未使用基因重组函数*/int main()GenEngine genEngine(50,0。8,0.8,1,100,0,4);genEngine.OnStartGenAlg();getchar();2、 GA。c:#includevector>include<stdio.h>include stdlib。hinclude <time.h#include<iostream>include”GA.h"using namespace std;/srand((unsigned) time(NULL));double random()double randNum;randNum=rand()*1。0/RAND_MAX;return randNum; GenAlg:GenAlg()void GenAlg:init(int popsize, double MutRate, double CrossRate, int GenLenght,double LeftPoint,double RightPoint)popSize = popsize;mutationRate = MutRate;crossoverRate = CrossRate;chromoLength = GenLenght;totalFitness = 0;generation = 0;/fittestGenome = 0;bestFitness = 0.0;worstFitness = 99999999;averageFitness = 0;maxPerturbation=0.004;leftPoint=LeftPoint;rightPoint=RightPoint;/清空种群容器,以初始化vecPop.clear();for (int i=0; i<popSize; i+) /类的构造函数已经把适应性评分初始化为0vecPop.push_back(Genome());/把所有的基因编码初始化为函数区间内的随机数。for (int j=0; j<chromoLength; j+)vecPopi。vecGenome。push_back(random() (rightPoint leftPoint) + leftPoint);void GenAlg:Reset()totalFitness=0;/bestFitness=0; /worstFitness=9999;averageFitness=0;void GenAlg::CalculateBestWorstAvTot()for (int i=0; i<popSize; +i)/累计适应性分数。totalFitness+= vecPopi。fitness;if(vecPopi.fitness=bestFitness)bestFitness=vecPopi.fitness;fittestGenome=vecPopi;if(vecPopi.fitness=worstFitness)worstFitness=vecPopi.fitness;averageFitness=totalFitness/popSize;Genome GenAlg:: GetChromoRoulette()/产生一个0到人口总适应性评分总和之间的随机数./中m_dTotalFitness记录了整个种群的适应性分数总和)double Slice = (random() totalFitness;/这个基因将承载转盘所选出来的那个个体.Genome TheChosenOne;/累计适应性分数的和。double FitnessSoFar = 0;/遍历总人口里面的每一条染色体.for (int i=0; i<popSize; +i)/累计适应性分数.FitnessSoFar += vecPopi.fitness;/如果累计分数大于随机数,就选择此时的基因。if (FitnessSoFar = Slice)TheChosenOne = vecPopi;break;/返回转盘选出来的个体基因return TheChosenOne;void GenAlg::Mutate(vectordouble> chromo)/遵循预定的突变概率,对基因进行突变for (int i=0; i<chromo.size(); +i)/如果发生突变的话if (random() < mutationRate)/使该权值增加或者减少一个很小的随机数值chromoi += (random()-0。5) maxPerturbation);/限定范围if(chromoi < leftPoint)chromoi = rightPoint;else if(chromoi rightPoint)chromoi = leftPoint;/以上代码非基因变异的一般性代码只是用来保证基因编码的可行性。/此函数产生新的一代,见证着整个进化的全过程./以父代种群的基因组容器作为参数传进去,该函数将往该容器里放入新一代的基因组(当然是经过了优胜劣汰的)void GenAlg:Epoch(vector<Genome> &vecNewPop)/用类的成员变量来储存父代的基因组(在此之前m_vecPop储存的是不带估值的所有基因组)vecPop = vecNewPop;/初始化相关变量Reset();/为相关变量赋值CalculateBestWorstAvTot();/清空装载新种群的容器vecNewPop.clear(); /产生新一代的所有基因组while (vecNewPop.size() popSize)/转盘随机抽出两个基因Genome mum = GetChromoRoulette();Genome dad = GetChromoRoulette();/创建两个子代基因组vectordouble baby1, baby2;/先把他们分别设置成父方和母方的基因baby1 = mum.vecGenome;baby2 = dad.vecGenome;/使子代基因发生基因突变Mutate(baby1);Mutate(baby2);/把两个子代基因组放到新的基因组容器里面vecNewPop。push_back( Genome(baby1, 0) );vecNewPop。push_back( Genome(baby2, 0) );/子代产生完毕/如果你设置的人口总数非单数的话,就会出现报错if(vecNewPop。size() != popSize)/MessageBox("你的人口数目不是单数!!”);cout<”error"<endl;return;Genome GenAlg::GetBestFitness()return fittestGenome;double GenAlg:GetAverageFitness()return averageFitness;void GenEngine::report(const int&genNum)cout<<"第"<<genNum<”代”<endl; cout<”最佳适应度:”<bestFitness<endl;cout<”最佳适应度基因取值:"<bestSearchendl;cout<”平均适应度:”averageFitness<endl<endl;void GenEngine:: OnStartGenAlg()/产生随机数srand( (unsigned)time( NULL ) );/初始化遗传算法引擎genAlg。init(g_popsize, g_dMutationRate, g_dCrossoverRate, g_numGen,g_LeftPoint,g_RightPoint);/清空种群容器m_population。clear();/种群容器装进经过随机初始化的种群m_population = genAlg.vecPop;vector <double input;double output;input。push_back(0);for(int Generation = 0;Generation <= g_Generation;Generation+)/里面是对每一条染色体进行操作for(int i=0;ig_popsize;i+) input = m_populationi.vecGenome;/为每一个个体做适应性评价,如之前说的,评价分数就是函数值。其/Function函数的作用是输入自变量返回函数值,读者可以参考其代码.output = (double)curve.function(input);m_populationi.fitness = output;/由父代种群进化出子代种群genAlg.Epoch(m_population);/if(genAlg。GetBestFitness().fitness>=bestFitness)bestSearch=genAlg。GetBestFitness().vecGenome0;bestFitness=genAlg.GetBestFitness()。fitness;averageFitness=genAlg。GetAverageFitness();/cout<<bestSearch<<endl;report(Generation+1);/return bestSearch;3、GA。h:include<vectorusing namespace std;const double pai=3.1415926;class Genomepublic: friend class GenAlg; friend class GenEngine; Genome():fitness(0) Genome(vector <double> vec, double f): vecGenome(vec), fitness(f) /类的带参数初始化参数。private: vector double> vecGenome; / dFitness用于存储对该基因的适应性评估。 double fitness; /类的无参数初始化参数.;/遗传算法class GenAlgpublic:/这个容器将储存每一个个体的染色体vector <Genome> vecPop;/人口(种群)数量int popSize; /每一条染色体的基因的总数目int chromoLength;/所有个体对应的适应性评分的总和double totalFitness;/在所有个体当中最适应的个体的适应性评分double bestFitness;/所有个体的适应性评分的平均值double averageFitness;/在所有个体当中最不适应的个体的适应性评分double worstFitness;/最适应的个体在m_vecPop容器里面的索引号Genome fittestGenome;/基因突变的概率,一般介于0.05和0。3之间double mutationRate;/基因交叉的概率一般设为0。7double crossoverRate;/代数的记数器int generation;/最大变异步长double maxPerturbation;double leftPoint;double rightPoint;/构造函数GenAlg();/初始化变量void Reset();/初始化函数void init(int popsize, double MutRate, double CrossRate, int GenLenght,double LeftPoint,double RightPoint);/计算TotalFitness, BestFitness, WorstFitness, AverageFitness等变量void CalculateBestWorstAvTot();/轮盘赌选择函数Genome GetChromoRoulette();/基因变异函数void Mutate(vector<double chromo);/这函数产生新一代基因void Epoch(vector<Genome> &vecNewPop);Genome GetBestFitness();double GetAverageFitness();;class Curvepublic:double function(const vector<double>& input)double x=input0; double output;output=xsin(10*paix)+2.0;return output;private:;/遗传运算引擎class GenEnginepublic:GenEngine(const int& popsize,const double mutationRate,const double& crossoverRate,const intnumGen,const intgeneration,const double leftPoint, const double& rightPoint):genAlg(),curve(),m_population()g_popsize=popsize;g_dMutationRate=mutationRate;g_dCrossoverRate=crossoverRate;g_numGen=numGen;g_Generation=generation;g_LeftPoint=leftPoint;g_RightPoint=rightPoint; bestFitness=0; bestSearch=0;void OnStartGenAlg();/报告每一代的运行情况void report(const intgenNum);private:GenAlg genAlg;Curve curve;vector<Genome m_population;int g_popsize;double g_dMutationRate;double g_dCrossoverRate;int g_numGen;int g_Generation;double g_LeftPoint;double g_RightPoint;double bestFitness; double bestSearch;double averageFitness;