遺傳演算法源代碼
❶ 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是傳遞給變異函數的參數。