C++遗传算法

项目说明
问题描述:对于方程f(x1,x2)=100*(x12-x2)2+(1-x1)^2,求出f的最大值并且求出对应的x1和x2(精确到0.001)。
遗传算法描述:随机生成多组等长二进制字符串作为初代祖先,经过多代的繁殖(包括自然选择、基因交叉、基因突变),评价出其适应度最好的基因作为全局最优解。
-自然选择:用的是轮盘法
-基因交叉:参考生物知识,不用我说了吧
-基因突变:随机在某基因的某个基因点将0变1或者1变0(当然有突变概率的,不是想变就变)
-适应度:将基因中x1、x2代入方程f,f值作为他的适应度
运行环境:vs2013可以运行,也可以将文件夹中的源.cpp中的代码复制到你的编译器运行

遗传算法说明

遗传算法流程图

:
这里写图片描述

基本遗传算法的步骤

1、 染色体编码:使用固定长度的二进制符号串来表示群体中的个体,其等位基因值由二值{0,1}组成。包括编码、解码公式。

2、 个体适应度的监测评估:所有个体的适应度必须为非负数。需要预先确定好由目标函数值到个体适应度之间的转换规律,特别是要预先确定好当目标函数为负数时的处理方法。例如:可选取一个适当大的正数C,使个体的适应度为目标函数值加上正数C

3、 遗传算子:

(1) 选择运算使用比例选择算子。比例选择因子是利用比例于各个个体适应度的概率决定其子孙的遗传可能性。

(2) 交叉运算使用单点交叉算子。任意挑选经过选择操作中两个个体作为交叉对象,随机产生一个交叉点位置,两个个体在交叉点位置互换部分基因码,形成两个子个体。

(3) 变异运算使用基本位变异算子或均匀变异算子。为了避免过早收敛,对于二进制的基因码组成的个体种群,实现基因码的小概率翻转,即0变为1,1变为0。

4、 基本遗传算法的运行参数:

(1) 群体大小:一般取为20—100

(2) 遗传算法的终止进化代数:一般取为100—500

(3) 交叉概率:一般取为0.4—0.99

(4) 变异概率:一般取为0.0001—0.1

研究方向

1、在遗传算法中,群体规模和遗传算子的控制参数的选取非常困难。存在过早收敛。

2、遗传算法的并行性主要有三个方面:个体适应度评价的并行性、整个群体各个个体适应度评价的并行性和子代群体产生过程的并行性。

3、分类系统属于基于遗传算法的机器学习中的一类,包括一个简单的基于串规则的并行生成子系统、规则评价子系统和遗传算法子系统。

4、遗传神经网络包括连接级、网络结构和学习规则的进化。

5、进化算法包括遗传算法、进化规划和进化策略,三种算法是独立发展起来的。
遗传算法的缺点:

1、遗传算法的编程实现比较复杂,首先需要对问题进行编码,找到最优解之后还需要对问题进行解码,

2、另外三个算子的实现也有许多参数,如交叉率和变异率,并且这些参数的选择严重影响解的品质,而目前这些参数的选择大部分是依靠经验.
3、没有能够及时利用网络的反馈信息,故算法的搜索速度比较慢,要得要较精确的解需要较多的训练时间。
4、算法对初始种群的选择有一定的依赖性,能够结合一些启发算法进行改进。
5、算法的并行机制的潜在能力没有得到充分的利用,这也是当前遗传算法的一个研究热点方向。

遗传算法Github地址

#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<stdlib.h>
#include<iostream>
#include<time.h>
using namespace std;

/*The Definition of Constant*/
#define POPSIZE 500 //population size
#define MAXIMIZATION 1 //maximization flag
#define MINIMIZATION 2 //minimization flag
/*The Definition of User Data*/
#define Cmax 100//certain maximal value
#define Cmin 0 //certain minimun value
#define LENGTH1 10//the chromosome length of 1st variable
#define LENGTH2 10//the chromosome length of 2nd variable
#define CHROMLENGTH LENGTH1 + LENGTH2 //total length of chromosome
int FunctionMode = MAXIMIZATION;//optimization type
int PopSize = 80;//population size
int MaxGeneration = 200;//max number of generation
double Pc = 0.6;//probability of crossover
double Pm = 0.001;//probability of mutation
/*The Definition of Data Structure*/
struct individual//data structure of individual
{
	char chrom[CHROMLENGTH + 1];//a string of code representing
	double value;//object value of this individual
	double fitness;//fitness value of this individual
};
/*the Definition of Global Variables*/
int generation;//number of generation
int best_index;//index of best individual
int worst_index;//index of worst individua
struct individual bestindividual;//best individual of current generation
struct individual worstindividual;//worst individual of current generation
struct individual currentbest;//best individual by now
struct individual population[POPSIZE];//population
/*Declaration of Prototype*/
void GenerateInitialPopulation();
void GenerateNextPopulation();
void EvaluatePopulation();
long DecodeChromosome(char *, int, int);
void CalculateObjectValue();
void CalculateFitnessValue();
void FindBestAndWorstIndividual();
void PerformEvolution();
void SelectionOperator();
void CrossoverOperator();
void MutationOperator();
void OutputTextReport();
int main()
{
	generation = 0;
	GenerateInitialPopulation();
	EvaluatePopulation();
	while (generation < MaxGeneration){
		generation++;
		GenerateNextPopulation();
		EvaluatePopulation();
		PerformEvolution();
		OutputTextReport();
	}
	return 0;
}
/*Function:Generate the first population.
Variable:None.*/
void GenerateInitialPopulation()
{
	int i, j;
	int flag = 1;
	srand((unsigned)time(NULL));
	for (i = 0; i < PopSize; i++)
	{
		for (j = 0; j < CHROMLENGTH; j++)
		{
			population[i].chrom[j] = (rand()%10 < 5) ? '0' : '1';
		}
		population[i].chrom[CHROMLENGTH] = '\0';
	}
}
/*Function:Initialize the first generation
Variable:None*/
void GenerateNextPopulation()
{
	SelectionOperator();
	CrossoverOperator();
	MutationOperator();
}
/*Function:Evaluate population according to certain formula
Variable:None*/
void EvaluatePopulation()
{
	CalculateObjectValue();//calculate object value
	CalculateFitnessValue();//calculate fitness value
	FindBestAndWorstIndividual();//find the best and worst individual
}
/*Function:To decode a binary chromosome into a decimal integer.
Variable:None.
Note:The returned value may be plus,or minus.For different coding method,this 
value may be changed into "unsigned int".*/
long DecodeChromosome(char * string, int point, int length)
{
	int i;
	long decimal = 0L;
	char * pointer;
	for (i = 0, pointer = string + point; i < length; i++, pointer++)
	{
		decimal += (*pointer - '0') << (length - 1 - i);
	}
	return (decimal);
}
/*Function:To calcluate object value.
Variable:None.
note:For different problem, user must change these code.
This example is dealing with Rosenbrock function.
Rosenbrock function is defined as:
f(x1,x2)=100*(x1^2-x2)^2+(1-x1)^2
Its maximal value is:
f(-2.048,-2.048)=3905.926227*/
void CalculateObjectValue()
{
	int i;
	long temp1, temp2;
	double x1, x2;
	//Rosenbrock function
	for (i = 0; i < PopSize; i++)
	{
		temp1 = DecodeChromosome(population[i].chrom, 0, LENGTH1);
		temp2 = DecodeChromosome(population[i].chrom, LENGTH1, LENGTH2);
		x1 = 4.096*temp1 / 1023.0 - 2.048;
		x2 = 4.096*temp2 / 1023.0 - 2.048;
		population[i].value = 100 * (x1*x1 - x2)*(x1*x1 - x2) + (1 - x1)*(1 - x1);
	}
}
/*Function:To calculate fitness value.
Variable:None.*/
void CalculateFitnessValue()
{
	int i;
	double temp;
	for (i = 0; i < PopSize; i++)
	{
		if (FunctionMode == MAXIMIZATION)//maximization
		{
			if ((population[i].value + Cmin) > 0.0)
			{
				temp = Cmin + population[i].value;
			}
			else
			{
				temp = 0.0;
			}
		}
		else if (FunctionMode == MINIMIZATION)//minimization
		{
			if (population[i].value < Cmax)
			{
				temp = Cmax - population[i].value;
			}
			else
			{
				temp = 0.0;
			}
		}
		population[i].fitness = temp;
	}
}
/*Function:To Find out the best individual so far current generation.
Variable:None.*/
void FindBestAndWorstIndividual()
{
	int i;
	double sum = 0.0;
	//find out the best and worst individual of this generation
	bestindividual = population[0];
	worstindividual = population[0];
	for (i = 1; i < PopSize; i++)
	{
		if (population[i].fitness > bestindividual.fitness)
		{
			bestindividual = population[i];
			best_index = i;
		}
		else if (population[i].fitness < worstindividual.fitness)
		{
			worstindividual = population[i];
			worst_index = i;
		}
		sum += population[i].fitness;
	}
	//find out the best individual so far
	if (generation == 0)
	{
		//initialize the best individual
		currentbest = bestindividual;
	}
	else
	{
		if (bestindividual.fitness>currentbest.fitness)
		{
			currentbest = bestindividual;
		}
	}
}
/*Function:To perform evolution operation based on elitise
model.Elitist model is to replace the worst
individual of this generation by the current
best one.
Variable:None.*/
void PerformEvolution()
{
	if (bestindividual.fitness > currentbest.fitness)
	{
		currentbest = population[best_index];
	}
	else
	{
		population[worst_index] = currentbest;
	}
}
/*Function:To reproduce a chromosome by
proportional selection.
Variable:None.*/
void SelectionOperator()
{
	int i, index;
	double p, sum = 0.0;
	double cfitness[POPSIZE];//cumulative fitness value
	struct individual newpopulation[POPSIZE];
	//calculate relative fitness
	for (i = 0; i < PopSize; i++)
	{
		sum += population[i].fitness;
	}
	for (i = 0; i < PopSize; i++)
	{
		cfitness[i] = population[i].fitness / sum;
	}
	//calculate cumulative fitness
	for (i = 1; i < PopSize; i++)
	{
		cfitness[i] = cfitness[i - 1] + cfitness[i];
	}
	//selection operation
	for (i = 0; i < PopSize; i++)
	{
		p = rand() % 1000 / 1000.0;
		index = 0;
		while (p>cfitness[index])
		{
			index++;
		}
		newpopulation[i] = population[index];
	}
	for (i = 0; i < PopSize; i++)
	{
		population[i] = newpopulation[i];
	}
}
/*Function:Crossover two chromosome by means 
 of one point crossover.
 Variable:None.*/
void CrossoverOperator()
{
	int i, j;
	int index[POPSIZE];
	int point, temp;
	double p;
	char ch;
	//make a pair of individual randomly
	for (i = 0; i < PopSize; i++)
	{
		index[i] = i;
	}
	for (i = 0; i < PopSize; i++)
	{
		point = rand() % (PopSize - i);
		temp = index[i];
		index[i] = index[i + point];
		index[point + i] = temp;
	}
	//one point crossover operation
	for (i = 0; i < PopSize - 1; i += 2)
	{
		p = rand() % 1000 / 1000.0;
		if (p < Pc)
		{
			point = rand() % (CHROMLENGTH - 1) + 1;
			for (j = point; j < CHROMLENGTH; j++)
			{
				ch = population[index[i]].chrom[j];
				population[index[i]].chrom[j] = population[index[i + 1]].chrom[j];
				population[index[i + 1]].chrom[j] = ch;
			}
		}
	}
}
/*Function:Mutation of a chromosome.
Variable:None*/
void MutationOperator()
{
	int i, j;
	double p;
	//bit mutation
	for (i = 0; i < PopSize; i++){
		for (j = 0; j < CHROMLENGTH; j++){
			p = rand() % 1000 / 1000.0;
			if (p < Pm){
				population[i].chrom[j] = (population[i].chrom[j] == '0') ? '1' : '0';
			}
		}
	}

}
/*Function:Output the results of current population.
Variable:None.*/
void OutputTextReport()
{
	int i;
	double sum;//temporary sum
	double average;//average of population object value
	//calculate average object value
	sum = 0.0;
	for (i = 0; i < PopSize; i++)
	{
		sum += population[i].value;
	}
	average = sum / PopSize;
	//print results of this population
	printf("gen=%d,avg=%f,best=%f,", generation, average, currentbest.value);
	printf("chromosome=");
	for (i = 0; i < CHROMLENGTH; i++)
	{
		printf("%c", currentbest.chrom[i]);
	}
	printf("\n");
}
  • 6
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++遗传算法是一种模拟自然选择和遗传机制的优化技术,常用于解决复杂问题中的全局优化问题。以下是一个简单的C++遗传算法程序的demo概述: ```cpp // 假设我们正在解决一个简单的函数优化问题,如找到函数f(x) = x^2 + y^2的最小值 #include <iostream> #include <vector> #include <random> #include <algorithm> class Individual { public: std::vector<double> genes; double fitness; // 构造函数,初始化基因(可能是一个随机数列) Individual(int size) : genes(size, 0.0), fitness(0.0) {} // 计算个体的适应度(这里用平方和作为例子) void calculateFitness() { fitness = 0.0; for (double gene : genes) { fitness += gene * gene; } } }; // 遗传操作(例如选择、交叉和变异) std::vector<Individual> geneticOperators(std::vector<Individual>& population) { // 选择操作(选择适应度较高的个体) // ... // 交叉操作(将两个个体的部分基因交换) // ... // 变异操作(随机改变某个基因) // ... return population; } int main() { // 初始化种群 int populationSize = 100; std::vector<Individual> population(populationSize); for (int i = 0; i < populationSize; ++i) { population[i].calculateFitness(); } // 进行迭代直到达到某个停止条件(如最大迭代次数或适应度阈值) while (/* stop condition */) { population = geneticOperators(population); // 更新适应度并可能进行排序 std::sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; }); // 打印当前最优解 std::cout << "Generation " << iterationCount << ", Best individual: Fitness = " << population.fitness << std::endl; } return 0; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值