遗传算法代码(遗传算法代码MATLAB)

各位老铁们,大家好,今天由我来为大家分享遗传算法代码,以及遗传算法代码MATLAB的相关问题知识,希望对大家有所帮助。如果可以帮助到大家,还望关注收藏下本站,您的支持是我们最大的动力,谢谢大家了哈,下面我们开始吧!

在众多优化算法中,遗传算法(Genetic Algorithm,GA)因其强大的搜索能力而被广泛应用于各种问题求解领域。遗传算法是一种模拟自然界生物进化过程的优化算法,通过模拟自然选择和遗传变异,在搜索空间中寻找最优解。本文将深入解析遗传算法的原理,并提供实战技巧,助你轻松掌握遗传算法代码。

一、遗传算法原理

1. 基本概念

遗传算法是一种模拟自然界生物进化过程的优化算法。在遗传算法中,问题求解的解集被模拟为种群,每个个体代表一个解,通过模拟自然选择和遗传变异,种群中的个体逐渐进化,最终找到最优解。

2. 基本操作

(1)选择:根据个体适应度选择部分个体进行繁殖。

(2)交叉:将两个个体的部分基因进行交换,生成新的个体。

(3)变异:对个体的基因进行随机改变,增加种群的多样性。

二、遗传算法代码实现

下面以Python语言为例,介绍遗传算法的代码实现。

“`python

import random

定义问题

def fitness_function(individual):

这里以求最大值为目标,将适应度设置为个体值

return sum(individual)

初始化种群

def create_population(size, individual_length):

return [[random.randint(0, 1) for _ in range(individual_length)] for _ in range(size)]

选择

def select(population, size):

根据适应度选择个体

return sorted(population, key=fitness_function, reverse=True)[:size]

交叉

def crossover(parent1, parent2, individual_length):

crossover_point = random.randint(1, individual_length – 1)

child = parent1[:crossover_point] + parent2[crossover_point:]

return child

变异

def mutate(individual, mutation_rate):

for i in range(len(individual)):

if random.random() < mutation_rate:

individual[i] = 1 – individual[i]

return individual

遗传算法主函数

def genetic_algorithm(fitness_function, population_size, individual_length, crossover_rate, mutation_rate, generations):

population = create_population(population_size, individual_length)

for _ in range(generations):

new_population = []

for _ in range(population_size // 2):

parent1, parent2 = select(population, 2)

child1 = crossover(parent1, parent2, individual_length)

child2 = crossover(parent2, parent1, individual_length)

child1 = mutate(child1, mutation_rate)

child2 = mutate(child2, mutation_rate)

new_population.extend([child1, child2])

population = new_population

return max(population, key=fitness_function)

测试

individual_length = 10

population_size = 100

crossover_rate = 0.8

mutation_rate = 0.02

generations = 100

best_individual = genetic_algorithm(fitness_function, population_size, individual_length, crossover_rate, mutation_rate, generations)

print(“

遗传算法优化概率神经网络的matlab代码

原理大概是,设置一个初始种群,种群里的个体就是平滑因子,经过遗传算法的选择、交叉、变异后,逐渐找到一个最佳的spread,即为最终结果。

附件是一个GA-BP算法的程序,虽然不同,但是原理是相近的,可以参考。

遗传算法的基本运算过程如下:

a)初始化:设置进化代数计数器t=0,设置最大进化代数T,随机生成M个个体作为初始群体P(0)。

b)个体评价:计算群体P(t)中各个个体的适应度。

c)选择运算:将选择算子作用于群体。选择的目的是把优化的个体直接遗传到下一代或通过配对交叉产生新的个体再遗传到下一代。选择操作是建立在群体中个体的适应度评估基础上的。

d)交叉运算:将交叉算子作用于群体。遗传算法中起核心作用的就是交叉算子。

e)变异运算:将变异算子作用于群体。即是对群体中的个体串的某些基因座上的基因值作变动。

群体P(t)经过选择、交叉、变异运算之后得到下一代群体P(t+1)。

f)终止条件判断:若t=T,则以进化过程中所得到的具有最大适应度个体作为最优解输出,终止计算。

谁能给一个C语言的遗传算法例题

这是一个非常简单的遗传算法源代码,是由Denis Cormier(North Carolina State University)开发的,Sita S.Raghavan(University of North Carolina at Charlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从ftp.uncc.edu,目录 coe/evol中的文件prog.c中获得。要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。

/**************************************************************************/

/* This is a simple genetic algorithm implementation where the*/

/* evaluation function takes positive values only and the*/

/* fitness of an individual is the same as the value of the*/

/* objective function*/

/**************************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

/* Change any of these parameters to match your needs*/

#define POPSIZE 50/* population size*/

#define MAXGENS 1000/* max. number of generations*/

#define NVARS 3/* no. of problem variables*/

#define PXOVER 0.8/* probability of crossover*/

#define PMUTATION 0.15/* probability of mutation*/

#define TRUE 1

#define FALSE 0

int generation;/* current generation no.*/

int cur_best;/* best individual*/

FILE*galog;/* an output file*/

struct genotype/* genotype(GT), a member of the population*/

{

double gene[NVARS];/* a string of variables*/

double fitness;/* GT's fitness*/

double upper[NVARS];/* GT's variables upper bound*/

double lower[NVARS];/* GT's variables lower bound*/

double rfitness;/* relative fitness*/

double cfitness;/* cumulative fitness*/

};

struct genotype population[POPSIZE+1];/* population*/

struct genotype newpopulation[POPSIZE+1];/* new population;*/

/* replaces the*/

/* old generation*/

/* Declaration of procedures used by this genetic algorithm*/

void initialize(void);

double randval(double, double);

void evaluate(void);

void keep_the_best(void);

void elitist(void);

void select(void);

void crossover(void);

void Xover(int,int);

void swap(double*, double*);

void mutate(void);

void report(void);

/***************************************************************/

/* 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(void)

{

FILE*infile;

int i, j;

double lbound, ubound;

if((infile= fopen(“gadata.txt”,”r”))==NULL)

{

fprintf(galog,”\nCannot open input file!\n”);

exit(1);

}

/* initialize variables within the bounds*/

for(i= 0; i< NVARS; i++)

{

fscanf(infile,”%lf”,&lbound);

fscanf(infile,”%lf”,&ubound);

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],

population[j].upper[i]);

}

}

fclose(infile);

}

/***********************************************************/

/* Random value generator: Generates a value within bounds*/

/***********************************************************/

double randval(double low, double high)

{

double val;

val=((double)(rand()%1000)/1000.0)*(high- low)+ low;

return(val);

}

/*************************************************************/

/* Evaluation function: This takes a user defined function.*/

/* Each time this is changed, the code has to be recompiled.*/

/* The current function is:x[1]^2-x[1]*x[2]+x[3]*/

/*************************************************************/

void evaluate(void)

{

int mem;

int i;

double x[NVARS+1];

for(mem= 0; mem< POPSIZE; mem++)

{

for(i= 0; i< NVARS; i++)

x[i+1]= population[mem].gene[i];

population[mem].fitness=(x[1]*x[1])-(x[1]*x[2])+ x[3];

}

}

/***************************************************************/

/* Keep_the_best function: This function keeps track of the*/

/* best member of the population. Note that the last entry in*/

/* the array Population holds a copy of the best individual*/

/***************************************************************/

void keep_the_best()

{

int mem;

int i;

cur_best= 0;/* stores the index of the best individual*/

for(mem= 0; mem< POPSIZE; mem++)

{

if(population[mem].fitness> population[POPSIZE].fitness)

{

cur_best= mem;

population[POPSIZE].fitness= population[mem].fitness;

}

}

/* once the best member in the population is found, copy the genes*/

for(i= 0; i< NVARS; i++)

population[POPSIZE].gene[i]= population[cur_best].gene[i];

}

/****************************************************************/

/* Elitist function: The best member of the previous generation*/

/* is stored as the last in the array. If the best member of*/

/* the current generation is worse then the best member of the*/

/* previous generation, the latter one would replace the worst*/

/* member of the current population*/

/****************************************************************/

void elitist()

{

int i;

double best, worst;/* best and worst fitness values*/

int best_mem, worst_mem;/* indexes of the best and worst member*/

best= population[0].fitness;

worst= population[0].fitness;

for(i= 0; i< POPSIZE- 1;++i)

{

if(population[i].fitness> population[i+1].fitness)

{

if(population[i].fitness>= best)

{

best= population[i].fitness;

best_mem= i;

}

if(population[i+1].fitness<= worst)

{

worst= population[i+1].fitness;

worst_mem= i+ 1;

}

}

else

{

if(population[i].fitness<= worst)

{

worst= population[i].fitness;

worst_mem= i;

}

if(population[i+1].fitness>= best)

{

best= population[i+1].fitness;

best_mem= i+ 1;

}

}

}

/* if best individual from the new population is better than*/

/* the best individual from the previous population, then*/

/* copy the best from the new population; else replace the*/

/* worst individual from the current population with the*/

/* best one from the previous generation*/

if(best>= population[POPSIZE].fitness)

{

for(i= 0; i< NVARS; i++)

population[POPSIZE].gene[i]= population[best_mem].gene[i];

population[POPSIZE].fitness= population[best_mem].fitness;

}

else

{

for(i= 0; i< NVARS; i++)

population[worst_mem].gene[i]= population[POPSIZE].gene[i];

population[worst_mem].fitness= population[POPSIZE].fitness;

}

}

/**************************************************************/

/* Selection function: Standard proportional selection for*/

/* maximization problems incorporating elitist model- makes*/

/* sure that the best member survives*/

/**************************************************************/

void select(void)

{

int mem, i, j, k;

double sum= 0;

double p;

/* find total fitness of the population*/

for(mem= 0; mem< POPSIZE; mem++)

{

sum+= population[mem].fitness;

}

/* calculate relative fitness*/

for(mem= 0; mem< POPSIZE; mem++)

{

population[mem].rfitness=population[mem].fitness/sum;

}

population[0].cfitness= population[0].rfitness;

/* calculate cumulative fitness*/

for(mem= 1; mem< POPSIZE; mem++)

{

population[mem].cfitness=population[mem-1].cfitness+

population[mem].rfitness;

}

/* finally select survivors using cumulative fitness.*/

for(i= 0; i< POPSIZE; i++)

{

p= rand()%1000/1000.0;

if(p< population[0].cfitness)

newpopulation[i]= population[0];

else

{

for(j= 0; j< POPSIZE;j++)

if(p>= population[j].cfitness&&

p<population[j+1].cfitness)

newpopulation[i]= population[j+1];

}

}

/* once a new population is created, copy it back*/

for(i= 0; i< POPSIZE; i++)

population[i]= newpopulation[i];

}

/***************************************************************/

/* Crossover selection: selects two parents that take part in*/

/* the crossover. Implements a single point crossover*/

/***************************************************************/

void crossover(void)

{

int i, mem, one;

int first=0;/* count of the number of members chosen*/

double x;

for(mem= 0; mem< POPSIZE;++mem)

{

x= rand()%1000/1000.0;

if(x< PXOVER)

{

++first;

if(first% 2== 0)

Xover(one, mem);

else

one= mem;

}

}

}

/**************************************************************/

/* Crossover: performs crossover of the two selected parents.*/

/**************************************************************/

void Xover(int one, int two)

{

int i;

int point;/* crossover point*/

/* select crossover point*/

if(NVARS> 1)

{

if(NVARS== 2)

point= 1;

else

point=(rand()%(NVARS- 1))+ 1;

for(i= 0; i< point; i++)

swap(&population[one].gene[i],&population[two].gene[i]);

}

}

/*************************************************************/

/* Swap: A swap procedure that helps in swapping 2 variables*/

/*************************************************************/

void swap(double*x, double*y)

{

double temp;

temp=*x;

*x=*y;

*y= temp;

}

/**************************************************************/

/* Mutation: Random uniform mutation. A variable selected for*/

/* mutation is replaced by a random value between lower and*/

/* upper bounds of this variable*/

/**************************************************************/

void mutate(void)

{

int i, j;

double lbound, hbound;

double x;

for(i= 0; i< POPSIZE; i++)

for(j= 0; j< NVARS; j++)

{

x= rand()%1000/1000.0;

if(x< PMUTATION)

{

/* find the bounds on the variable to be mutated*/

lbound= population[i].lower[j];

hbound= population[i].upper[j];

population[i].gene[j]= randval(lbound, hbound);

}

}

}

/***************************************************************/

/* Report function: Reports progress of the simulation. Data*/

/* dumped into theoutput file are separated by commas*/

/***************************************************************/

void report(void)

{

int i;

double best_val;/* best population fitness*/

double avg;/* avg population fitness*/

double stddev;/* std. deviation of population fitness*/

double sum_square;/* sum of square for std. calc*/

double square_sum;/* square of sum for std. calc*/

double sum;/* total population fitness*/

sum= 0.0;

sum_square= 0.0;

for(i= 0; i< POPSIZE; i++)

{

sum+= population[i].fitness;

sum_square+= population[i].fitness* population[i].fitness;

}

avg= sum/(double)POPSIZE;

square_sum= avg* avg* POPSIZE;

stddev= sqrt((sum_square- square_sum)/(POPSIZE- 1));

best_val= population[POPSIZE].fitness;

fprintf(galog,”\n%5d,%6.3f,%6.3f,%6.3f\n\n”, generation,

best_val, avg, stddev);

}

/**************************************************************/

/* Main function: Each generation involves selecting the best*/

/* members, performing crossover& mutation and then*/

/* evaluating the resulting population, until the terminating*/

/* condition is satisfied*/

/**************************************************************/

void main(void)

{

int i;

if((galog= fopen(“galog.txt”,”w”))==NULL)

{

exit(1);

}

generation= 0;

fprintf(galog,”\n generationbestaveragestandard\n”);

fprintf(galog,” numbervalue fitnessdeviation\n”);

initialize();

evaluate();

keep_the_best();

while(generation<MAXGENS)

{

generation++;

select();

crossover();

mutate();

report();

evaluate();

elitist();

}

fprintf(galog,”\n\n Simulation completed\n”);

fprintf(galog,”\n Best member:\n”);

for(i= 0; i< NVARS; i++)

{

fprintf(galog,”\n var(%d)=%3.3f”,i,population[POPSIZE].gene[i]);

}

fprintf(galog,”\n\n Best fitness=%3.3f”,population[POPSIZE].fitness);

fclose(galog);

printf(“Success\n”);

}

/***************************************************************/

遗传算法的基本原理

遗传算法的基本原理和方法

一、编码

编码:把一个问题的可行解从其解空间转换到遗传算法的搜索空间的转换方法。

解码(译码):遗传算法解空间向问题空间的转换。

二进制编码的缺点是汉明悬崖(Hamming Cliff),就是在某些相邻整数的二进制代码之间有很大的汉明距离,使得遗传算法的交叉和突变都难以跨越。

格雷码(Gray Code):在相邻整数之间汉明距离都为1。

(较好)有意义的积木块编码规则:所定编码应当易于生成与所求问题相关的短距和低阶的积木块;最小字符集编码规则,所定编码应采用最小字符集以使问题得到自然的表示或描述。

二进制编码比十进制编码搜索能力强,但不能保持群体稳定性。

动态参数编码(Dynamic Paremeter Coding):为了得到很高的精度,让遗传算法从很粗糙的精度开始收敛,当遗传算法找到一个区域后,就将搜索现在在这个区域,重新编码,重新启动,重复这一过程,直到达到要求的精度为止。

编码方法:

1、二进制编码方法

缺点:存在着连续函数离散化时的映射误差。不能直接反映出所求问题的本身结构特征,不便于开发针对问题的专门知识的遗传运算算子,很难满足积木块编码原则

2、格雷码编码:连续的两个整数所对应的编码之间仅仅只有一个码位是不同的,其余码位都相同。

3、浮点数编码方法:个体的每个基因值用某一范围内的某个浮点数来表示,个体的编码长度等于其决策变量的位数。

4、各参数级联编码:对含有多个变量的个体进行编码的方法。通常将各个参数分别以某种编码方法进行编码,然后再将他们的编码按照一定顺序连接在一起就组成了表示全部参数的个体编码。

5、多参数交叉编码:将各个参数中起主要作用的码位集中在一起,这样它们就不易于被遗传算子破坏掉。

评估编码的三个规范:完备性、健全性、非冗余性。

二、选择

遗传算法中的选择操作就是用来确定如何从父代群体中按某种方法选取那些个体遗传到下一代群体中的一种遗传运算,用来确定重组或交叉个体,以及被选个体将产生多少个子代个体。

常用的选择算子:

1、轮盘赌选择(Roulette Wheel Selection):是一种回放式随机采样方法。每个个体进入下一代的概率等于它的适应度值与整个种群中个体适应度值和的比例。选择误差较大。

2、随机竞争选择(Stochastic Tournament):每次按轮盘赌选择一对个体,然后让这两个个体进行竞争,适应度高的被选中,如此反复,直到选满为止。

3、最佳保留选择:首先按轮盘赌选择方法执行遗传算法的选择操作,然后将当前群体中适应度最高的个体结构完整地复制到下一代群体中。

4、无回放随机选择(也叫期望值选择Excepted Value Selection):根据每个个体在下一代群体中的生存期望来进行随机选择运算。方法如下

(1)计算群体中每个个体在下一代群体中的生存期望数目N。

(2)若某一个体被选中参与交叉运算,则它在下一代中的生存期望数目减去0.5,若某一个体未被选中参与交叉运算,则它在下一代中的生存期望数目减去1.0。

(3)随着选择过程的进行,若某一个体的生存期望数目小于0时,则该个体就不再有机会被选中。

5、确定式选择:按照一种确定的方式来进行选择操作。具体操作过程如下:

(1)计算群体中各个个体在下一代群体中的期望生存数目N。

(2)用N的整数部分确定各个对应个体在下一代群体中的生存数目。

(3)用N的小数部分对个体进行降序排列,顺序取前M个个体加入到下一代群体中。至此可完全确定出下一代群体中M个个体。

6、无回放余数随机选择:可确保适应度比平均适应度大的一些个体能够被遗传到下一代群       体中,因而选择误差比较小。

7、均匀排序:对群体中的所有个体按期适应度大小进行排序,基于这个排序来分配各个个体被选中的概率。

8、最佳保存策略:当前群体中适应度最高的个体不参与交叉运算和变异运算,而是用它来代替掉本代群体中经过交叉、变异等操作后所产生的适应度最低的个体。

9、随机联赛选择:每次选取几个个体中适应度最高的一个个体遗传到下一代群体中。

10、排挤选择:新生成的子代将代替或排挤相似的旧父代个体,提高群体的多样性。

三、交叉

遗传算法的交叉操作,是指对两个相互配对的染色体按某种方式相互交换其部分基因,从而形成两个新的个体。

适用于二进制编码个体或浮点数编码个体的交叉算子:

1、单点交叉(One-point Crossover):指在个体编码串中只随机设置一个交叉点,然后再该点相互交换两个配对个体的部分染色体。

2、两点交叉与多点交叉:

(1)两点交叉(Two-point Crossover):在个体编码串中随机设置了两个交叉点,然后再进行部分基因交换。

(2)多点交叉(Multi-point Crossover)

3、均匀交叉(也称一致交叉,Uniform Crossover):两个配对个体的每个基因座上的基因都以相同的交叉概率进行交换,从而形成两个新个体。

4、算术交叉(Arithmetic Crossover):由两个个体的线性组合而产生出两个新的个体。该操作对象一般是由浮点数编码表示的个体。

四、变异

遗传算法中的变异运算,是指将个体染色体编码串中的某些基因座上的基因值用该基因座上的其它等位基因来替换,从而形成以给新的个体。

以下变异算子适用于二进制编码和浮点数编码的个体:

1、基本位变异(Simple Mutation):对个体编码串中以变异概率、随机指定的某一位或某几位仅因座上的值做变异运算。

2、均匀变异(Uniform Mutation):分别用符合某一范围内均匀分布的随机数,以某一较小的概率来替换个体编码串中各个基因座上的原有基因值。(特别适用于在算法的初级运行阶段)

3、边界变异(Boundary Mutation):随机的取基因座上的两个对应边界基因值之一去替代原有基因值。特别适用于最优点位于或接近于可行解的边界时的一类问题。

4、非均匀变异:对原有的基因值做一随机扰动,以扰动后的结果作为变异后的新基因值。对每个基因座都以相同的概率进行变异运算之后,相当于整个解向量在解空间中作了一次轻微的变动。

5、高斯近似变异:进行变异操作时用符号均值为P的平均值,方差为P2的正态分布的一个随机数来替换原有的基因值。

关于遗传算法代码和遗传算法代码MATLAB的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享