導航:首頁 > 源碼編譯 > 遺傳演算法程序

遺傳演算法程序

發布時間:2022-01-20 11:57:46

A. matlab遺傳演算法程序

在matlab里沒有
for
i
=
1
to
80
...
endfor
這樣的語法的
在matlab里應該是:
for
i
=
1:
1:
80
...
end
1:1:80
第一個1是初始值,第二個是每次+1的意思
當然如果是我古若寡聞那也請見諒~~哈哈~~

B. 遺傳演算法程序

#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 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 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");
}
/***************************************************************/

C. 遺傳演算法的matlab代碼實現是什麼

遺傳演算法我懂,我的論文就是用著這個演算法,具體到你要遺傳演算法是做什麼?優化什麼的。。。我給你一個標准遺傳演算法程序供你參考:
該程序是遺傳演算法優化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]);

D. 遺傳演算法C++程序

。。。。估計你這樣問不會有人懂的,上網的人很少會遺傳演算法的,就算是學計算機和軟體的也很少用這類概率優化演算法,再者,一般寫遺傳用matlab很多,而且資料也多。。。。用c/c++能寫出來的都是很變態的高手。。。

E. 遺傳演算法 簡單程序應用

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class Best {
public int generations; //最佳適應值代號
public String str; //最佳染色體
public double fitness; //最佳適應值
}

public class SGAFrame extends JFrame {

private JTextArea textArea;
private String str = "";
private Best best = null; //最佳染色體
private String[] ipop = new String[10]; //染色體
private int gernation = 0; //染色體代號
public static final int GENE = 22; //基因數
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
SGAFrame frame = new SGAFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Create the frame
*/
public SGAFrame() {
super();

this.ipop = inialPops();

getContentPane().setLayout(null);
setBounds(100, 100, 461, 277);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JLabel label = new JLabel();
label.setText("X的區間:");
label.setBounds(23, 10, 88, 15);
getContentPane().add(label);

final JLabel label_1 = new JLabel();
label_1.setText("[-255,255]");
label_1.setBounds(92, 10, 84, 15);
getContentPane().add(label_1);

final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
SGAFrame s = new SGAFrame();
str = str + s.process() + "\n";
textArea.setText(str);
}
});
button.setText("求最小值");
button.setBounds(323, 27, 99, 23);
getContentPane().add(button);

final JLabel label_2 = new JLabel();
label_2.setText("利用標准遺傳演算法求解函數f(x)=(x-5)*(x-5)的最小值:");
label_2.setBounds(23, 31, 318, 15);
getContentPane().add(label_2);

final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBounds(23, 65, 399, 164);
getContentPane().add(panel);

final JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);

textArea = new JTextArea();
scrollPane.setViewportView(textArea);
//
}

/**
* 初始化一條染色體(用二進制字元串表示)
* @return 一條染色體
*/
private String inialPop() {
String res = "";
for (int i = 0; i < GENE; i++) {
if (Math.random() > 0.5) {
res += "0";
} else {
res += "1";
}
}
return res;
}

/**
* 初始化一組染色體
* @return 染色體組
*/
private String[] inialPops() {
String[] ipop = new String[10];
for (int i = 0; i < 10; i++) {
ipop[i] = inialPop();
}
return ipop;
}

/**
* 將染色體轉換成x的值
* @param str 染色體
* @return 染色體的適應值
*/
private double calculatefitnessvalue(String str) {
int b = Integer.parseInt(str, 2);
//String str1 = "" + "/n";
double x = -255 + b * (255 - (-255)) / (Math.pow(2, GENE) - 1);
//System.out.println("X = " + x);
double fitness = -(x - 5) * (x - 5);
//System.out.println("f(x)=" + fitness);
//str1 = str1 + "X=" + x + "/n"
//+ "f(x)=" + "fitness" + "/n";
//textArea.setText(str1);

return fitness;
}

/**
* 計算群體上每個個體的適應度值;
* 按由個體適應度值所決定的某個規則選擇將進入下一代的個體;
*/
private void select() {
double evals[] = new double[10]; // 所有染色體適應值
double p[] = new double[10]; // 各染色體選擇概率
double q[] = new double[10]; // 累計概率
double F = 0; // 累計適應值總和
for (int i = 0; i < 10; i++) {
evals[i] = calculatefitnessvalue(ipop[i]);
if (best == null) {
best = new Best();
best.fitness = evals[i];
best.generations = 0;
best.str = ipop[i];
} else {
if (evals[i] > best.fitness) // 最好的記錄下來
{
best.fitness = evals[i];
best.generations = gernation;
best.str = ipop[i];
}
}
F = F + evals[i]; // 所有染色體適應值總和

}
for (int i = 0; i < 10; i++) {
p[i] = evals[i] / F;
if (i == 0)
q[i] = p[i];
else {
q[i] = q[i - 1] + p[i];
}
}
for (int i = 0; i < 10; i++) {

double r = Math.random();
if (r <= q[0]) {
ipop[i] = ipop[0];

} else {
for (int j = 1; j < 10; j++) {
if (r < q[j]) {
ipop[i] = ipop[j];
break;
}
}
}
}
}

/**
* 交叉操作
* 交叉率為25%,平均為25%的染色體進行交叉
*/
private void cross() {
String temp1, temp2;
for (int i = 0; i < 10; i++) {
if (Math.random() < 0.25) {
double r = Math.random();
int pos = (int) (Math.round(r * 1000)) % GENE;
if (pos == 0) {
pos = 1;
}
temp1 = ipop[i].substring(0, pos)
+ ipop[(i + 1) % 10].substring(pos);
temp2 = ipop[(i + 1) % 10].substring(0, pos)
+ ipop[i].substring(pos);
ipop[i] = temp1;
ipop[(i + 1) / 10] = temp2;
}
}
}

/**
* 基因突變操作
* 1%基因變異m*pop_size 共180個基因,為了使每個基因都有相同機會發生變異,
* 需要產生[1--180]上均勻分布的
*/
private void mutation() {
for (int i = 0; i < 4; i++) {
int num = (int) (Math.random() * GENE * 10 + 1);
int chromosomeNum = (int) (num / GENE) + 1; // 染色體號

int mutationNum = num - (chromosomeNum - 1) * GENE; // 基因號
if (mutationNum == 0)
mutationNum = 1;
chromosomeNum = chromosomeNum - 1;
if (chromosomeNum >= 10)
chromosomeNum = 9;
//System.out.println("變異前" + ipop[chromosomeNum]);
String temp;
if (ipop[chromosomeNum].charAt(mutationNum - 1) == '0') {
if (mutationNum == 1) {
temp = "1" + ipop[chromosomeNum].substring

(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -

1) + "1" + ipop

[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
} else {
if (mutationNum == 1) {
temp = "0" + ipop[chromosomeNum].substring

(mutationNum);
} else {
if (mutationNum != GENE) {
temp = ipop[chromosomeNum].substring(0, mutationNum -

1) + "0" + ipop

[chromosomeNum].substring(mutationNum);
} else {
temp = ipop[chromosomeNum].substring(0, mutationNum -
1) + "1";
}
}
}
ipop[chromosomeNum] = temp;
//System.out.println("變異後" + ipop[chromosomeNum]);
}
}
/**
* 執行遺傳演算法
*/
public String process() {
String str = "";
for (int i = 0; i < 10000; i++) {
this.select();
this.cross();
this.mutation();
gernation = i;
}
str = "最小值" + best.fitness + ",第" + best.generations + "個染色體";
return str;
}

}

F. 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是傳遞給變異函數的參數。

G. 遺傳演算法程序運行這個該用什麼軟體能運行

MATLAB用於圖像建模演算法的設計和運行
這個用MATLAB實現可以運行。

H. 高分求遺傳演算法程序

遺傳演算法作為一種快速有效的尋優演算法,在工業控制、經濟決策和交通規劃等居多領域得到廣泛應用。其特點就是其不同於傳統的搜索尋優方式而是模擬自然界生物進化過程,通過基因的變異交叉重組使整體得到進化,不斷的進化最終得到最優的組群,即最優解。
下面是一個具體實例,是小可在別人程序的基礎上改寫優化而成。這里首先要建立數學模型,即問題的數學公式描述,數學建模是一門對數學能力有相當要求的課程,一個人的數學能力往往決定其從事工作的層次。下面的程序是求多項式y=x^6-10x^5-26x^4+344x^3+193x^2-1846x-1680在區間[-8,8]的最小值,誤差不超過0.001。對於這個復雜的多項式,可先用matlab繪制函數的大概曲線,確認函數的最小值大概處於[-8,8]之間,再用本程序求出精確解。
程序已在Dev-c++下運行通過,結果正確。
如有什麼疑問,給我消息。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define SUM 20 /* 總共的染色體數量 */
#define MAXloop 1200 /* 最大循環次數 */
#define error 0.01 /* 若兩次最優值之差小於此數則認為結果沒有改變 */
#define crossp 0.7 /* 交叉概率 */
#define mp 0.04 /* 變異概率 */

struct gen /* 定義染色體結構 */
{
int info;
double suitability;
};
struct gen gen_group[SUM];/* 定義一個含有20個染色體的組 */
struct gen gen_new[SUM];

struct gen gen_result; /* 記錄最優的染色體 */
int result_unchange_time; /* 記錄在error前提下最優值未改變的循環次數 */

struct log /* 形成鏈表,記錄每次循環所產生的最優的適應度 */
{
double suitability;
struct log *next;
}llog,*head,*end;
int log_num; /* 鏈表長度 */

void initiate(); /*初始化函數*/
void evaluation(int flag); /*適應度評估和排序函數*/
void cross(); /*交叉函數*/
void selection(); /*選擇函數*/
int record(); /*記錄每次最優解和判斷循環是否終止*/
void mutation(); /*變異函數*/
void showresult(int); /*顯示結果*/

int randsign(double p); /*按概率p產生0,1隨機數,p表示產生值1的概率*/
int randbit(int i,int j);/*產生i,j間的隨機整數*/
int randnum(); /*隨機產生14個位(基因)組成的染色體*/
int convertionD2B(double x); /*編碼*/
double convertionB2D(int x); /*解碼*/
int createmask(int a); /*交叉操作*/

int main()
{
int i,flag;
flag=0;
initiate();
evaluation( 0 );
for( i = 0 ; i < MAXloop ; i++ )
{
cross();
evaluation( 1 );
selection();
if( record() == 1 )
{
flag = 1;
break;
}
mutation();
}
showresult( flag );
system("pause");
return 0
}

void initiate()
{
int i , stime;
long ltime;
ltime=time(NULL);
stime=(unsigned)ltime/2;
srand(stime);
for( i = 0 ; i < SUM ; i++ )
{
gen_group[i].info = randnum();
}
gen_result.suitability=1000;
result_unchange_time=0;
head=end=(struct log *)malloc(sizeof(llog));
if(head==NULL)
{
printf("\n內存不夠!\n");
exit(0);
}
end->next = NULL;
log_num = 1;
}

void evaluation(int flag)
{
int i,j,k;
struct gen *genp;
int gentinfo;
double gentsuitability;
double x;
if( flag == 0 )
genp = gen_group;
else genp = gen_new;
for(i = 0 ; i < SUM ; i++)/* 計算各染色體對應的表達式值 */
{
x = convertionB2D( genp[i].info );
genp[i].suitability = x*(x*(x*(x*(x*(x-10)-26)+344)+193)-1846)-1680;
}
for(i = 0 ; i < SUM - 1 ; i++)/* 按表達式的值進行排序 */
{ k=i;
for(j = i + 1 ; j < SUM ; j++)
if( genp[i].suitability > genp[j].suitability ) k=j;
if( k!=i )
{
gentinfo = genp[i].info;
genp[i].info = genp[k].info;
genp[k].info = gentinfo;

gentsuitability = genp[i].suitability;
genp[i].suitability = genp[k].suitability;
genp[k].suitability = gentsuitability;
}
}
}

void cross()
{
int i , j , k ;
int mask1 , mask2;
int a[SUM];
for(i = 0 ; i < SUM ; i++) a[i] = 0;
k = 0;
for(i = 0 ; i < SUM ; i++)
{
if( a[i] == 0)
{
for( ; ; )/* 隨機找到一組未進行過交叉的染色體與a[i]交叉 */
{
j = randbit(i + 1 , SUM - 1);
if( a[j] == 0) break;
}
if(randsign(crossp) == 1)
{
mask1 = createmask(randbit(0 , 14-1));
mask2 = ~mask1;
gen_new[k].info = (gen_group[i].info) & mask1 + (gen_group[j].info) & mask2;
gen_new[k+1].info=(gen_group[i].info) & mask2 + (gen_group[j].info) & mask1;
k = k + 2;
}
else
{
gen_new[k].info=gen_group[i].info;
gen_new[k+1].info=gen_group[j].info;
k=k+2;
}
a[i] = a[j] = 1;
}
}
}

void selection()
{
int i , j , k;
j = 0;
i = SUM/2-1;
if(gen_group[i].suitability < gen_new[i].suitability)
{
for(j = 1 ; j < SUM / 2 ; j++)
{
if(gen_group[i+j].suitability > gen_new[i-j].suitability)
break;
}
}
else
if(gen_group[i].suitability>gen_new[i].suitability)
{
for(j=-1;j>-SUM/2;j--)
{
if(gen_group[i+j].suitability<=gen_new[i-j].suitability)
break;
}
}
for(k=j;k<SUM/2+1;k++)
{
gen_group[i+k].info = gen_new[i-k].info;
gen_group[i+k].suitability = gen_new[i-k].suitability;
}
}

int record()
{
double x;
struct log *r;
r=(struct log *)malloc(sizeof(llog));
if(r==NULL)
{
printf("\n內存不夠!\n");
exit(0);
}
r->next = NULL;
end->suitability = gen_group[0].suitability;
end->next = r;
end = r;
log_num++;

x = gen_result.suitability - gen_group[0].suitability;
if(x < 0)x = -x;
if(x < error)
{
result_unchange_time++;
if(result_unchange_time >= 20)return 1;
}
else
{
gen_result.info = gen_group[0].info;
gen_result.suitability = gen_group[0].suitability;
result_unchange_time=0;
}
return 0;
}

void mutation()
{
int i , j , k, m;
double x;
double gmp;
int gentinfo;
double gentsuitability;
gmp = 1 - pow(1 - mp , 11);/* 在基因變異概率為mp時整條染色體的變異概率 */
for(i = 0 ; i < SUM ; i++)
{
if(randsign(gmp) == 1)
{
j = randbit(0 , 14);
m = 1 << j;
gen_group[i].info = gen_group[i].info^m;
x = convertionB2D(gen_group[i].info);
gen_group[i].suitability = x*(x*(x*(x*(x*(x-10)-26)+344)+193)-1846)-1680;
}
}
for(i = 0 ; i < SUM - 1 ; i++)
{ k=i;
for(j = i + 1 ; j < SUM ; j++)
if(gen_group[i].suitability > gen_group[j].suitability) k=j;
if(k!=i)
{
gentinfo = gen_group[i].info;
gen_group[i].info = gen_group[k].info;
gen_group[k].info = gentinfo;

gentsuitability = gen_group[i].suitability;
gen_group[i].suitability = gen_group[k].suitability;
gen_group[k].suitability = gentsuitability;
}
}
}

void showresult(int flag)/* 顯示搜索結果並釋放內存 */
{
int i , j;
struct log *logprint,*logfree;
FILE *logf;
if(flag == 0)
printf("已到最大搜索次數,搜索失敗!");
else
{
printf("當取值%f時表達式達到最小值為%f\n",convertionB2D(gen_result.info),gen_result.suitability);
printf("收斂過程記錄於文件log.txt");
if((logf = fopen("log.txt" , "w+")) == NULL)
{
printf("Cannot create/open file");
exit(1);
}
logprint=head;
for(i = 0 ; i < log_num ; i = i + 5)/* 對收斂過程進行顯示 */
{
for(j = 0 ; (j < 5) & ((i + j) < log_num-1) ; j++)
{
fprintf(logf , "%20f" , logprint->suitability);
logprint=logprint->next;
}
fprintf(logf,"\n\n");
}
}
for(i = 0 ; i< log_num ; i++)/* 釋放內存 */
{
logfree=head;
head=head->next;
free(logfree);
}
fclose(logf);
getch();
}

int randsign(double p)/* 按概率p返回1 */
{
if(rand() > (p * 32768))
return 0;
else return 1;
}
int randbit(int i, int j)/* 產生在i與j之間的一個隨機數 */
{
int a , l;
l = j - i + 1;
a = i + rand() * l / 32768;
return a;
}
int randnum()
{
int x;
x = rand() / 2;
return x;
}
double convertionB2D(int x)
{
double y;
y = x;
y = (y - 8192) / 1000;
return y;

}
int convertionD2B(double x)
{
int g;
g = (x * 1000) + 8192;
return g;
}
int createmask(int a)
{
int mask;
mask=(1 << a) - 1;
return mask;
}

I. 求遺傳演算法(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]; /* 個體死活狀態標志變數 */

J. 求matlab遺傳演算法源程序

matlab自帶的有遺傳演算法工具箱,也就是兩個函數,分別是

x=ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon,options)
options=gaoptimset('param1',value1,'param2',value2,...)

在幫助文件(doc ga/gaoptimset)裡面自己好還看看它的用法就可以了,每一個參數都有詳細的說明,應該可以幫助到你。

閱讀全文

與遺傳演算法程序相關的資料

熱點內容
listsortjava 瀏覽:180
plc閃光電路編程實例 瀏覽:297
socket編程試題 瀏覽:201
華為的伺服器怎麼設置從光碟機啟動 瀏覽:867
程序員真的累嗎 瀏覽:323
學信網app為什麼刷臉不了 瀏覽:871
天蠍vs程序員 瀏覽:991
單片機下載口叫什麼 瀏覽:186
程序員的道 瀏覽:924
雲伺服器不實名違法嗎 瀏覽:556
怎樣查看文件夾圖片是否重復 瀏覽:993
文件怎麼導成pdf文件 瀏覽:806
打開sql表的命令 瀏覽:101
安卓手機如何面部支付 瀏覽:37
天元數學app為什麼登錄不上去 瀏覽:823
明日之後為什麼有些伺服器是四個字 瀏覽:104
安卓系統l1是什麼意思 瀏覽:25
伺服器一直崩應該用什麼指令 瀏覽:924
cm202貼片機編程 瀏覽:729
php構造函數帶參數 瀏覽:179