当前位置:首页 » 操作系统 » 遗传算法源代码

遗传算法源代码

发布时间: 2022-10-07 10:56:47

❶ MATLAB遗传算法编写的求函数最大值的源代码

这个可以去论坛里面搜搜吧,推荐的论坛是数学中国,里面有各种数学建模资料,而且全部免费。网络数学中国,第一个就是了。

c语言遗传算法在求解TSP问题 毕业论文+源代码



摘要
I
Abstract
II


1
第一章
基本遗传算法
2
1.1
遗传算法的产生及发展
3
1.2
基本原理
3
1.3
遗传算法的特点
3
1.4
基本遗传算法描述
5
1.5
遗传算法构造流程
6
第二章
遗传算法的实现技术
6
2.1
编码方法
7
2.1.1
二进制编码
7
2.1.2
格雷码编码
7
2.1.3
符点数编码
8
2.1.4
参数编码
8
2.2
适应度函数
10
2.3
选择算子
10
2.4
交叉算子
10
2.4.1
单点交叉算子
10
2.4.2
双点交叉算子
11
2.4.3
均匀交叉算子
11
2.4.4
部分映射交叉
11
2.4.5
顺序交叉
12
2.5
变异算子
12
2.6
运行参数
12
2.7
约束条件的处理方法
13
2.8
遗传算法流程图
14
第三章
遗传算法在TSP上的应用
15
3.1
TSP问题的建模与描述
15
3.2
对TSP的遗传基因编码方法
16
3.3
针对TSP的遗传操作算子
17
3.3.1
选择算子
17
3.3.1.1
轮盘赌选择
17
3.3.1.2
最优保存策略选择
17
3.3.2
交叉算子
20
3.3.2.1
单点交叉
20
3.3.2.2
部分映射交叉
21
3.3.3
变异算子
23
3.4
TSP的混和遗传算法
26
第四章
实例分析
27
4.1
测试数据
27
4.2
测试结果
27
4.3
结果分析
27


TSP
(Traveling
Salesman
Problem)旅行商问题是一类典型的NP完全问题,遗传算法是解决NP问题的一种较理想的方法。文章首先介绍了基本遗传算法的基本原理、特点及其基本实现技术;接着针对TSP
问题,论述了遗传算法在编码表示和遗传算子(包括选择算子、交叉算子变异算子这三种算子)等方面的应用情况,分别指出几种常用的编码方法的优点和缺点,并且结合TSP的运行实例详细分析了基本遗传算法的4个运行参数群体大小、遗传算法的终止进化代数、交叉概率、变异概率,对遗传算法的求解结果和求解效率的影响,经过多次的测试设定出了它们一组比较合理的取值。最后,简单说明了混合遗传算法在求解TSP问题中的应用并对遗传算法解决TSP问题的前景提出了展望。
关键词:TSP
遗传算法
遗传算子
编码
@@@需要的话按我的名字找我吧

❸ 帮帮忙,用c语言写一个遗传算法程序解决y=x*x的最大值问题,x取0--31

一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从ftp.uncc.e,目录 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 indivial 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 indivial */
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 proceres 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 of the best indivial */
/***************************************************************/

void keep_the_best()
{
int mem;
int i;
cur_best = 0; /* stores the index of the best indivial */

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, 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 indivial from the new population is better than */
/* the best indivial from the previous population, then */
/* the best from the new population; else replace the */
/* worst indivial 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, 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 procere 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 */
/* mped into the output file are separated by commas */
/***************************************************************/
。。。。。
代码太多 你到下面呢个网站看看吧

void main(void)
{
int i;

if ((galog = fopen("galog.txt","w"))==NULL)
{
exit(1);
}
generation = 0;

fprintf(galog, "\n generation best average standard \n");
fprintf(galog, " number value fitness deviation \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");
}

❹ 跪求一份多目标优化遗传算法 matlab源代码,不甚感激。邮 箱991882239

我给你一个标准遗传算法程序供你参考:
该程序是遗传算法优化BP神经网络函数极值寻优:
%% 该代码为基于神经网络遗传算法的系统极值寻优
%% 清空环境变量
clc
clear

%% 初始化遗传算法参数
%初始化参数
maxgen=100; %进化代数,即迭代次数
sizepop=20; %种群规模
pcross=[0.4]; %交叉概率选择,0和1之间
pmutation=[0.2]; %变异概率选择,0和1之间

lenchrom=[1 1]; %每个变量的字串长度,如果是浮点变量,则长度都为1
bound=[-5 5;-5 5]; %数据范围

indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %将种群信息定义为一个结构体
avgfitness=[]; %每一代种群的平均适应度
bestfitness=[]; %每一代种群的最佳适应度
bestchrom=[]; %适应度最好的染色体

%% 初始化种群计算适应度值
% 初始化种群
for i=1:sizepop
%随机产生一个种群
indivials.chrom(i,:)=Code(lenchrom,bound);
x=indivials.chrom(i,:);
%计算适应度
indivials.fitness(i)=fun(x); %染色体的适应度
end
%找最好的染色体
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色体
avgfitness=sum(indivials.fitness)/sizepop; %染色体的平均适应度
% 记录每一代进化中最好的适应度和平均适应度
trace=[avgfitness bestfitness];

%% 迭代寻优
% 进化开始
for i=1:maxgen
i
% 选择
indivials=Select(indivials,sizepop);
avgfitness=sum(indivials.fitness)/sizepop;
%交叉
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 变异
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,[i maxgen],bound);

% 计算适应度
for j=1:sizepop
x=indivials.chrom(j,:); %解码
indivials.fitness(j)=fun(x);
end

%找到最小和最大适应度的染色体及它们在种群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次进化中最好的染色体
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;

avgfitness=sum(indivials.fitness)/sizepop;

trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度
end
%进化结束

%% 结果分析
[r c]=size(trace);
plot([1:r]',trace(:,2),'r-');
title('适应度曲线','fontsize',12);
xlabel('进化代数','fontsize',12);ylabel('适应度','fontsize',12);
axis([0,100,0,1])
disp('适应度 变量');
x=bestchrom;
% 窗口显示
disp([bestfitness x]);

❺ 求遗传算法(GA)C语言代码

.----来个例子,大家好理解..--
基于遗传算法的人工生命模拟
#include<stdio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>
#include<time.h>
#include<string.h>
#include "graph.c"
/* 宏定义 */
#define TL1 20 /* 植物性食物限制时间 */
#define TL2 5 /* 动物性食物限制时间 */
#define NEWFOODS 3 /* 植物性食物每代生成数目 */
#define MUTATION 0.05 /* 变异概率 */
#define G_LENGTH 32 /* 个体染色体长度 */
#define MAX_POP 100 /* 个体总数的最大值 */
#define MAX_FOOD 100 /* 食物总数的最大值 */
#define MAX_WX 60 /* 虚拟环境的长度最大值 */
#define MAX_WY 32 /* 虚拟环境的宽度最大值 */
#define SX1 330 /* 虚拟环境图左上角点x坐标 */
#define SY1 40 /* 虚拟环境图左上角点y坐标 */
#define GX 360 /* 个体数进化图形窗口的左上角点X坐标 */
#define GY 257 /* 个体数进化图形窗口的左上角点Y坐标 */
#define GXR 250 /* 个体数进化图形窗口的长度 */
#define GYR 100 /* 个体数进化图形窗口的宽度 */
#define GSTEP 2 /* 个体数进化图形窗口的X方向步长 */
#define R_LIFE 0.05 /* 初期产生生物数的环境比率 */
#define R_FOOD 0.02 /* 初期产生食物数的环境比率 */
#define SL_MIN 10 /* 个体寿命最小值 */
/* 全局变量 */
unsigned char gene[MAX_POP][G_LENGTH]; /* 遗传基因 */
unsigned char iflg[MAX_POP]; /* 个体死活状态标志变量 */

❻ 大家好,请问谁有基于matlab的遗传算法源代码,很需要呀

function [Zp,Y1p,Y2p,Y3p,Xp,LC1,LC2]=JSPGA(M,N,Pm,T,P)
%--------------------------------------------------------------------------
% JSPGA.m
% 车间作业调度问题遗传算法
%--------------------------------------------------------------------------
% 输入参数列表
% M 遗传进化迭代次数
% N 种群规模(取偶数)
% Pm 变异概率
% T m×n的矩阵,存储m个工件n个工序的加工时间
% P 1×n的向量,n个工序中,每一个工序所具有的机床数目
% 输出参数列表
% Zp 最优的Makespan值
% Y1p 最优方案中,各工件各工序的开始时刻,可根据它绘出甘特图
% Y2p 最优方案中,各工件各工序的结束时刻,可根据它绘出甘特图
% Y3p 最优方案中,各工件各工序使用的机器编号
% Xp 最优决策变量的值,决策变量是一个实数编码的m×n矩阵
% LC1 收敛曲线1,各代最优个体适应值的记录
% LC2 收敛曲线2,各代群体平均适应值的记录
% 最后,程序还将绘出三副图片:两条收敛曲线图和甘特图(各工件的调度时序图)

%第一步:变量初始化
[m,n]=size(T);%m是总工件数,n是总工序数
Xp=zeros(m,n);%最优决策变量
LC1=zeros(1,M);%收敛曲线1
LC2=zeros(1,N);%收敛曲线2

%第二步:随机产生初始种群
farm=cell(1,N);%采用细胞结构存储种群
for k=1:N
X=zeros(m,n);
for j=1:n
for i=1:m
X(i,j)=1+(P(j)-eps)*rand;
end
end
farm=X;
end

counter=0;%设置迭代计数器
while counter

%第三步:交叉
newfarm=cell(1,N);%交叉产生的新种群存在其中
Ser=randperm(N);
for i=1:2:(N-1)
A=farm;%父代个体
B=farm;
Manner=unidrnd(2);%随机选择交叉方式
if Manner==1
cp=unidrnd(m-1);%随机选择交叉点
%双亲双子单点交叉
a=[A(1:cp,:);B((cp+1):m,:)];%子代个体
b=[B(1:cp,:);A((cp+1):m,:)];
else
cp=unidrnd(n-1);%随机选择交叉点
a=[A(:,1:cp),B(:,(cp+1):n)];%双亲双子单点交叉
b=[B(:,1:cp),A(:,(cp+1):n)];
end
newfarm=a;%交叉后的子代存入newfarm
newfarm=b;
end
%新旧种群合并
FARM=[farm,newfarm];

%第四步:选择复制
FITNESS=zeros(1,2*N);
fitness=zeros(1,N);
plotif=0;
for i=1:(2*N)
X=FARM;
Z=COST(X,T,P,plotif);%调用计算费用的子函数
FITNESS(i)=Z;
end
%选择复制采取两两随机配对竞争的方式,具有保留最优个体的能力
Ser=randperm(2*N);
for i=1:N
f1=FITNESS(Ser(2*i-1));
f2=FITNESS(Ser(2*i));
if f1<=f2
farm=FARM;
fitness(i)=FITNESS(Ser(2*i-1));
else
farm=FARM;
fitness(i)=FITNESS(Ser(2*i));
end
end
%记录最佳个体和收敛曲线
minfitness=min(fitness)
meanfitness=mean(fitness)
LC1(counter+1)=minfitness;%收敛曲线1,各代最优个体适应值的记录
LC2(counter+1)=meanfitness;%收敛曲线2,各代群体平均适应值的记录
pos=find(fitness==minfitness);
Xp=farm;

%第五步:变异
for i=1:N
if Pm>rand;%变异概率为Pm
X=farm;
I=unidrnd(m);
J=unidrnd(n);
X(I,J)=1+(P(J)-eps)*rand;
farm=X;
end
end
farm=Xp;

counter=counter+1
end

%输出结果并绘图
figure(1);
plotif=1;
X=Xp;
[Zp,Y1p,Y2p,Y3p]=COST(X,T,P,plotif);
figure(2);
plot(LC1);
figure(3);
plot(LC2);

❼ 请问这个MATLAB遗传算法源代码应该怎样使用

在command窗口中输入函数名字加参数值,把括号里的参数变成具体数后在命令窗口中输入ga(d,termops,num,pc,cxops,pm,alpha)

❽ C遗传算法

一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从ftp.uncc.e,目录 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 indivial 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 indivial */
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 proceres 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 of the best indivial */
/***************************************************************/

void keep_the_best()
{
int mem;
int i;
cur_best = 0; /* stores the index of the best indivial */

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, 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 indivial from the new population is better than */
/* the best indivial from the previous population, then */
/* the best from the new population; else replace the */
/* worst indivial 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, 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 procere 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 */
/* mped into the output file are separated by commas */
/***************************************************************/
。。。。。
代码太多 你到下面呢个网站看看吧

void main(void)
{
int i;

if ((galog = fopen("galog.txt","w"))==NULL)
{
exit(1);
}
generation = 0;

fprintf(galog, "\n generation best average standard \n");
fprintf(galog, " number value fitness deviation \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");
}
另外,虚机团上产品团购,超级便宜

❾ MATLAB编遗传算法源程序

遗传算法实例:

也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。
对于初学者,尤其是还没有编程经验的非常有用的一个文件
遗传算法实例

% 下面举例说明遗传算法 %
% 求下列函数的最大值 %
% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %
% 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。 %
% 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。 %
% %
%--------------------------------------------------------------------------------------------------------------%
%--------------------------------------------------------------------------------------------------------------%

% 编程
%-----------------------------------------------
% 2.1初始化(编码)
% initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),
% 长度大小取决于变量的二进制编码的长度(在本例中取10位)。
%遗传算法子程序
%Name: initpop.m
%初始化
function pop=initpop(popsize,chromlength)
pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,
% roud对矩阵的每个单元进行圆整。这样产生的初始种群。

% 2.2 计算目标函数值
% 2.2.1 将二进制数转化为十进制数(1)
%遗传算法子程序
%Name: decodebinary.m
%产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制
function pop2=decodebinary(pop)
[px,py]=size(pop); %求pop行和列数
for i=1:py
pop1(:,i)=2.^(py-i).*pop(:,i);
end
pop2=sum(pop1,2); %求pop1的每行之和

% 2.2.2 将二进制编码转化为十进制数(2)
% decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置
% (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),
% 参数1ength表示所截取的长度(本例为10)。
%遗传算法子程序
%Name: decodechrom.m
%将二进制编码转换成十进制
function pop2=decodechrom(pop,spoint,length)
pop1=pop(:,spoint:spoint+length-1);
pop2=decodebinary(pop1);

% 2.2.3 计算目标函数值
% calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。
%遗传算法子程序
%Name: calobjvalue.m
%实现目标函数的计算
function [objvalue]=calobjvalue(pop)
temp1=decodechrom(pop,1,10); %将pop每行转化成十进制数
x=temp1*10/1023; %将二值域 中的数转化为变量域 的数
objvalue=10*sin(5*x)+7*cos(4*x); %计算目标函数值

% 2.3 计算个体的适应值
%遗传算法子程序
%Name:calfitvalue.m
%计算个体的适应值
function fitvalue=calfitvalue(objvalue)
global Cmin;
Cmin=0;
[px,py]=size(objvalue);
for i=1:px
if objvalue(i)+Cmin>0
temp=Cmin+objvalue(i);
else
temp=0.0;
end
fitvalue(i)=temp;
end
fitvalue=fitvalue';

% 2.4 选择复制
% 选择或复制操作是决定哪些个体可以进入下一代。程序中采用赌轮盘选择法选择,这种方法较易实现。
% 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤:
% 1) 在第 t 代,由(1)式计算 fsum 和 pi
% 2) 产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum
% 3) 求 ∑fi≥s 中最小的 k ,则第 k 个个体被选中
% 4) 进行 N 次2)、3)操作,得到 N 个个体,成为第 t=t+1 代种群
%遗传算法子程序
%Name: selection.m
%选择复制
function [newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue); %求适应值之和
fitvalue=fitvalue/totalfit; %单个个体被选择的概率
fitvalue=cumsum(fitvalue); %如 fitvalue=[1 2 3 4],则 cumsum(fitvalue)=[1 3 6 10]
[px,py]=size(pop);
ms=sort(rand(px,1)); %从小到大排列
fitin=1;
newin=1;
while newin<=px
if(ms(newin))<fitvalue(fitin)
newpop(newin)=pop(fitin);
newin=newin+1;
else
fitin=fitin+1;
end
end

% 2.5 交叉
% 交叉(crossover),群体中的每个个体之间都以一定的概率 pc 交叉,即两个个体从各自字符串的某一位置
% (一般是随机确定)开始互相交换,这类似生物进化过程中的基因分裂与重组。例如,假设2个父代个体x1,x2为:
% x1=0100110
% x2=1010001
% 从每个个体的第3位开始交叉,交又后得到2个新的子代个体y1,y2分别为:
% y1=0100001
% y2=1010110
% 这样2个子代个体就分别具有了2个父代个体的某些特征。利用交又我们有可能由父代个体在子代组合成具有更高适合度的个体。
% 事实上交又是遗传算法区别于其它传统优化方法的主要特点之一。
%遗传算法子程序
%Name: crossover.m
%交叉
function [newpop]=crossover(pop,pc)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:2:px-1
if(rand<pc)
cpoint=round(rand*py);
newpop(i,:)=[pop(i,1:cpoint),pop(i+1,cpoint+1:py)];
newpop(i+1,:)=[pop(i+1,1:cpoint),pop(i,cpoint+1:py)];
else
newpop(i,:)=pop(i);
newpop(i+1,:)=pop(i+1);
end
end

% 2.6 变异
% 变异(mutation),基因的突变普遍存在于生物的进化过程中。变异是指父代中的每个个体的每一位都以概率 pm 翻转,即由“1”变为“0”,
% 或由“0”变为“1”。遗传算法的变异特性可以使求解过程随机地搜索到解可能存在的整个空间,因此可以在一定程度上求得全局最优解。
%遗传算法子程序
%Name: mutation.m
%变异
function [newpop]=mutation(pop,pm)
[px,py]=size(pop);
newpop=ones(size(pop));
for i=1:px
if(rand<pm)
mpoint=round(rand*py);
if mpoint<=0
mpoint=1;
end
newpop(i)=pop(i);
if any(newpop(i,mpoint))==0
newpop(i,mpoint)=1;
else
newpop(i,mpoint)=0;
end
else
newpop(i)=pop(i);
end
end

% 2.7 求出群体中最大得适应值及其个体
%遗传算法子程序
%Name: best.m
%求出群体中适应值最大的值
function [bestindivial,bestfit]=best(pop,fitvalue)
[px,py]=size(pop);
bestindivial=pop(1,:);
bestfit=fitvalue(1);
for i=2:px
if fitvalue(i)>bestfit
bestindivial=pop(i,:);
bestfit=fitvalue(i);
end
end

% 2.8 主程序
%遗传算法主程序
%Name:genmain05.m
clear
clf
popsize=20; %群体大小
chromlength=10; %字符串长度(个体长度)
pc=0.6; %交叉概率
pm=0.001; %变异概率

pop=initpop(popsize,chromlength); %随机产生初始群体
for i=1:20 %20为迭代次数
[objvalue]=calobjvalue(pop); %计算目标函数
fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度
[newpop]=selection(pop,fitvalue); %复制
[newpop]=crossover(pop,pc); %交叉
[newpop]=mutation(pop,pc); %变异
[bestindivial,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值
y(i)=max(bestfit);
n(i)=i;
pop5=bestindivial;
x(i)=decodechrom(pop5,1,chromlength)*10/1023;
pop=newpop;
end

fplot('10*sin(5*x)+7*cos(4*x)',[0 10])
hold on
plot(x,y,'r*')
hold off

[z index]=max(y); %计算最大值及其位置
x5=x(index)%计算最大值对应的x值
y=z

【问题】求f(x)=x 10*sin(5x) 7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x 10*sin(5*x) 7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2 x2.^2)))-exp(0.5*(cos(2*pi*x1) cos(2*pi*x2))) 22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv) 22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x 10*sin(5*x) 7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。

【问题】求f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中0<=x<=9
【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08
【程序清单】
%编写目标函数
function[sol,eval]=fitness(sol,options)
x=sol(1);
eval=x+10*sin(5*x)+7*cos(4*x);
%把上述函数存储为fitness.m文件并放在工作目录下
initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小为10
[x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',...
[0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25次遗传迭代
运算借过为:x =
7.8562 24.8553(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。
遗传算法实例2
【问题】在-5<=Xi<=5,i=1,2区间内,求解
f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2+x2.^2)))-exp(0.5*(cos(2*pi*x1)+cos(2*pi*x2)))+22.71282的最小值。
【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3
【程序清单】
%源函数的matlab代码
function [eval]=f(sol)
numv=size(sol,2);
x=sol(1:numv);
eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x))/numv)+22.71282;
%适应度函数的matlab代码
function [sol,eval]=fitness(sol,options)
numv=size(sol,2)-1;
x=sol(1:numv);
eval=f(x);
eval=-eval;
%遗传算法的matlab代码
bounds=ones(2,1)*[-5 5];
[p,endPop,bestSols,trace]=ga(bounds,'fitness')
注:前两个文件存储为m文件并放在工作目录下,运行结果为
p =
0.0000 -0.0000 0.0055
大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:
fplot('x+10*sin(5*x)+7*cos(4*x)',[0,9])
evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。

热点内容
重新编目数据库 发布:2025-05-16 00:54:34 浏览:513
android语音控制 发布:2025-05-16 00:53:50 浏览:265
win8windows无法访问 发布:2025-05-16 00:37:53 浏览:894
八种排序算法 发布:2025-05-16 00:37:17 浏览:55
左旋螺纹数控编程实例 发布:2025-05-16 00:11:49 浏览:10
安卓游戏旧版本从哪个软件下载 发布:2025-05-16 00:00:20 浏览:329
连接聚类算法 发布:2025-05-15 23:55:09 浏览:978
工资算法单休 发布:2025-05-15 23:52:30 浏览:819
超凡先锋配置不行怎么办 发布:2025-05-15 23:27:54 浏览:532
win7取消加密 发布:2025-05-15 23:26:37 浏览:472