点击上方蓝字关注“公众号”

MATLAB遗传算法及其实现

遗传算法以一种群体中的所有个体为对象,并利用随机化技术指导对一个被编码的参数空间进行高效搜索。

其中,选择、交叉和变异构成了遗传算法的遗传操作;参数编码初始群体的设定适应度函数的设计遗传操作设计控制参数设定等5个要素组成了遗传算法的核心内容。

主要步骤如下所示:    

(1)编码:GA在进行搜索之前先将解空间的解数据表示成遗传空间的基因型串结构数据,这些串结构数据的不同组合便构成了不同的点。

(2)初始群体的生成:随机产生N个初始串结构数据,每个串结构数据称为一个个体,N个个体构成了—个群体。

GA以这N个串结构数据作为初始点开始迭代。

(3)适应性值评估检测:适应性函数表明个体或解的优劣性。对于不同的问题,适应性函数的定义方式也不同。

(4)选择:选择的目的是为了从当前群体个选出优良的个体,使它们有机会作为父代为下一代繁殖子孙。

遗传算法通过选择过程体现这一思想,进行选择的原则是适应性强的个体为下一代贡献一个或多个后代的概率大。

选择实现了达尔文的适者生存原则。

(5)交叉:交叉操作是遗传算法中最主要的遗传操作。

通过交叉操作可以得到新一代个体,新个体组合了其父辈个体的特性。交叉体现了信息交换的思想。

(6)变异:变异首先在群体中随机选择一个个体,对于选中的个体以一定的概率随机地改变串结构数据中某个串的值。

同生物界一样,GA中变异发生的概率很低,通常取值在0.001~0.01之间。变异为新个体的产中提供了机会。

遗传算法的MATLAB实现

需要如下主函数:

编码和种群生成

 function [pop] = initializega(num,bounds,evalFN,evalOps,options)

% pop    - the initial, evaluated, random population

% num    - the size of the population, i.e. the number to create

% bounds - the number of permutations in an individual (e.g., number

%          of cities in a tsp

% evalFN - the evaluation fn, usually the name of the .m file for evaluation

% evalOps- any options to be passed to the eval function defaults [ ]

% options- options to the initialize function, ie. [eps, float/binary, prec]

%        where eps is the epsilon value and the second option is 1 for

%     orderOps, prec is the precision of the variables defaults [1e-6 1]

01

交叉

function [c1,c2] = arithXover(p1,p2,bounds,Ops)

% Arith crossover takes two parents P1,P2 and performs an interpolation

% along the line formed by the two parents.

%

% function [c1,c2] = arithXover(p1,p2,bounds,Ops)

% p1      - the first parent ( [solution string function value] )

% p2      - the second parent ( [solution string function value] )

% bounds  - the bounds matrix for the solution space

% Ops     - Options matrix for arith crossover [gen #ArithXovers]

02

选择

normGeomSelect:NormGeomSelect is a ranking selection

function based on the normalized geometric distribution.

(基于正态分布的序列选择函数)

03

变异

function[newPop] = normGeomSelect(oldPop,options)

% NormGeomSelect is a ranking selection function based on

the normalized

% geometric distribution.

%

% function[newPop] = normGeomSelect(oldPop,options)

% newPop  - the new population selected from the oldPop

% oldPop  - the current population

% options - options to normGeomSelect

[gen probability_of_selecting_best]

04

一些辅助函数

f2b :Return the binary representation of the float number

fval(将浮点数转化为二进制数)

b2f:Return the float number corresponing to the binary

representation of bval. (将二进制数转化为

浮点数)

nonUnifMutation: Non uniform mutation changes one

of the parameters of the parent based on a non-uniform

probability distribution.  This Gaussian distribution starts wide,

and narrows to a point distribution as the current generation

approaches the maximum generation.

(基于非均一概率分布进行非均一变异)

maxGenTerm:Returns 1, i.e. terminates the GA when the

maximal_generation is reached.

(当迭代次数大于最大迭代次数时,终止遗传算法,返回

为1,否则返回为0。)

roulette:roulette is the traditional selection function with the

probability of surviving equal to the fittness of i / sum of the

fittness of all individuals

应用举例

01

1.计算下列函数的最大值。

f(x)=x+10*sin(5x)+7cos(4x) , x∈[0,9]

方式1  >>gademo

方式2

step 1 编写目标函数gademo1eval1.m

function [sol, val] = gaDemo1Eval(sol,options)

x=sol(1);

val = x + 10*sin(5*x)+7*cos(4*x);

step 2 生成初始种群,大小为10

initPop=initializega(10,[0, 9],'gademo1eval1',[],[1e-6,1]);

step 3  25次遗传迭代

[x, endPop,bpop,trace] = ga([0 9],'gademo1eval1',[],initPop,...

[1e-6 1 1],'maxGenTerm',25,...

'normGeomSelect',[0.08],...

['arithXover'],[2],...

'nonUnifMutation',[2, 25 ,3])

% Output Arguments:

%   x    - the best solution found during the course of the

run

%   endPop       - the final population

%   bPop         - a trace of the best population

(解的变化)

%   traceInfo    - a matrix of best and means of the ga

for each generation

(种群平均值的变化)

%

% Input Arguments:

%   bounds - a matrix of upper and lower bounds

on the variables

%   evalFN  - the name of the evaluation .m function

%   evalOps

- options to pass to the evaluation function ([NULL])

%   startPop   - a matrix of solutions that can be initialized

%              from initialize.m

%   opts   - [epsilon, prob_ops ,display]

change required to consider two solutions

different, prob_ops 0 if you want to apply the

%            genetic operators probabilisticly to each solution,

1 if you are supplying a deterministic number

of operator  applications and display is 1 to output

progress 0 for  quiet. ([1e-6 1 0])

%   termFN  - name of the .m termination function

(['maxGenTerm'])

%   termOps  - options string to be passed to the termination

function  ([100]).

%   selectFN     - name of the .m selection function

(['normGeomSelect'])

%   selectOpts   - options string to be passed to select after

%                  select(pop,#,opts) ([0.08])

%   xOverFNS     - a string containing blank seperated names

of Xover.m files (['arithXover heuristicXover

simpleXover'])

%   xOverOps     - A matrix of options to pass to Xover.m files

with the first column being the number of that

xOver to perform similiarly for mutation

([2 0;2 3;2 0])

%   mutFNs       - a string containing blank seperated names of

mutation.m files (['boundaryMutation

multiNonUnifMutation ...

%                           nonUnifMutation unifMutation'])

%   mutOps       - A matrix of options to pass to Xover.m files

with the first column being the number of that

xOver to perform similiarly for mutation

([4 0 0;6 100 3;4 100 3;4 0 0])

02

2.求sin(x) 在0到3.14之间的最大值.

function [sol, val] = sin1(sol,options)

x=sol(1);

val =sin(x);

initPop=initializega(10,[0, 3.14],'sin1',[],[1e-6,1]);

[x, endPop,bpop,trace] = ga([0 3.14],'sin1',[],initPop,...

[1e-6 1 1],'maxGenTerm',25,...

'normGeomSelect',[0.08],...

['arithXover'],[2],...

'nonUnifMutation',[2, 25 ,3])

03

3. binaryExample.m

二元函数例子 二进制编码

方式1 >> binaryExample

方式2

function [sol,val] = gaMichEval(sol,options)

val = 21.5 + sol(1) * sin(4*pi*sol(1)) + sol(2)*sin(20*pi*sol(2));

%%%%%%%%%%%%%%

global bounds

% Setting the seed back to the beginning for comparison sake

rand('seed',0)

% Crossover Operators

xFns = 'simpleXover';

xOpts = [.4];

% Mutation Operators

mFns = 'binaryMutation';

mOpts = [0.005];

% Termination Operators

termFns = 'maxGenTerm';

termOps = [200]; % 200 Generations

% Selection Function

selectFn = 'roulette'

selectOps = [];

% Evaluation Function

evalFn = 'gaMichEval';

evalOps = [];

% Bounds on the variables

bounds = [-3, 12.1; 4.1, 5.8];

% GA Options [epsilon float/binar display]

gaOpts=[1e-6 0 1];

% Generate an intialize population of size 20

startPop = initializega(20,bounds,'gaMichEval',[],[1e-6 0]);

[x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,...

termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts);

% x is the best solution found

x

% endPop is the ending population

endPop

% trace is a trace of the best value and average value of generations

trace

clf

plot(trace(:,1),trace(:,2));

hold on

plot(trace(:,1),trace(:,3));

% Lets increase the population size by running the defaults

%

rand('seed',0)

termOps=[100];

[x endPop bestPop trace]=ga(bounds,evalFn,evalOps,[],gaOpts,termFns,termOps,...

selectFn,selectOps);

% x is the best solution found

x

% endPop is the ending population

%endPop

% trace is a trace of the best value and average value of generations

%trace

% Plot the best over time

clf

plot(trace(:,1),trace(:,2));

% Add the average to the graph

hold on

plot(trace(:,1),trace(:,3));

04

4. floatExample.m

二元函数例子 浮点编码

global bounds

% Setting the seed to the same for binary

rand('seed',156789)

% Crossover Operators

xFns = 'arithXover heuristicXover simpleXover';

xOpts = [1 0; 1 3; 1 0];

% Mutation Operators

mFns = 'boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation';

mOpts = [2 0 0;3 200 3;2 200 3;2 0 0];

% Termination Operators

termFns = 'maxGenTerm';

termOps = [200]; % 200 Generations

% Selection Function

selectFn = 'normGeomSelect';

selectOps = [0.08];

% Evaluation Function

evalFn = 'gaMichEval';

evalOps = [];

% Bounds on the variables

bounds = [-3 12.1; 4.1 5.8];

% GA Options [epsilon float/binar display]

gaOpts=[1e-6 1 1];

% Generate an intialize population of size 20

startPop = initializega(20,bounds,'gaMichEval',[1e-6 1])

[x endPop bestPop trace]=ga(bounds,evalFn,evalOps,startPop,gaOpts,...

termFns,termOps,selectFn,selectOps,xFns,xOpts,mFns,mOpts);

% x is the best solution found

x

% endPop is the ending population

endPop

% bestPop is the best solution tracked over generations

bestPop

% Plot the best over time

clf

plot(trace(:,1),trace(:,2));

% Add the average to the graph

hold on

plot(trace(:,1),trace(:,3));

% Lets increase the population size by running the defaults

[x endPop bestPop trace]=ga(bounds,evalFn,evalOps,[],gaOpts);

% x is the best solution found

x

% endPop is the ending population

endPop

% bestPop is the best solution tracked over generations

bestPop

% Plot the best over time

clf

plot(trace(:,1),trace(:,2));

% Add the average to the graph

hold on

plot(trace(:,1),trace(:,3));

05

5. 求解非线性规划问题

max f(x)

s.t. gi(x)<=0,i=1,...,m

hi(x)=0,i=m+1,...,n

x∈Ω

& 拒绝策略

& 修复策略

& 改进遗传算子策略

& 惩罚策略

e.g. min  f(x)=(x1-2)2+(x2-1)2

s.t. g1(x)=x1-2x2+1>=0

g2(x)=x12/4-x22+1>=0

分析:取加法形式的适值函数:

val(x)=f(x)+p(x)

惩罚函数 p(x)由两部分组成,可变乘法因子和

违反约束乘法,其表达式如下:

其中ri是约束i的可变惩罚系数。

步骤如下:

function [sol,eval]=f552(sol,options)

x1=sol(1);

x2=sol(2);

r1=0.1;

r2=0.8;

%约束条件

g1=x1-2*x2+1;

g2=x1.^2/4-x2.^2+1;

%加惩罚项的适值

if (g1>=0)&(g2>=0)

eval=(x1-2).^2+(x2-1).^2;

else

eval=(x1-2).^2+(x2-1).^2+r1*g1+r2*g2;

end

eval=-eval;

%%%%%%%%%%%%%%%%%%%%%%%%%%%

%维数n=2

%设置参数边界

bounds = ones(2,1)*[-1 1];%??????

%遗传算法优化

[p,endPop,bestSols,trace]=ga(bounds,'f552');

p

%性能跟踪

plot(trace(:,1),trace(:,3),'b-')

hold on

plot(trace(:,1),trace(:,2),'r-')

xlabel('Generation');

ylabel('Fittness');

legend('解的变化','种群平均值的变化');

MATLAB各种版本下载,关注公众号即可获得链接。

未完待续

扫码关注

不迷路

算法 matlab_MATLAB遗传算法及其实现相关推荐

  1. 大白话解析模拟退火算法、遗传算法入门

    优化算法入门系列文章目录(更新中): 1. 模拟退火算法 2. 遗传算法 一. 爬山算法 ( Hill Climbing ) 介绍模拟退火前,先介绍爬山算法.爬山算法是一种简单的贪心搜索算法,该算法每 ...

  2. matlab bs2rv.m,Matlab智能算法之遗传算法(一)

    Matlab智能算法之遗传算法(1) 以往写过的一篇文章了,旧了 1)Sheffield遗传算法工具箱的安装 我共享了下修改过文件名和后缀名的原版工具箱,地址为:http://pan.baidu.co ...

  3. 数学建模国赛 常考赛题类型(模拟退火算法、粒子群算法、遗传算法)

    不知小伙伴们有没有发现,在1992~2020年历年国赛赛题中,优化类赛题所占的比例非常大,如在近五年的题目中: 2016A:系泊系统的设计: 2017B:"拍照赚钱"的任务定价 2 ...

  4. 智能优化算法:遗传算法(GA)

    目录 目录 1.遗传算法原理介绍及其算子选择 2.算法步骤 3.案例分析 4. 代码实现 1.遗传算法原理介绍及其算子选择 遗传算法(Genetic Algorithm,GA)起源于对生物系统所进行的 ...

  5. Python优化算法02——遗传算法

    参考文档链接:scikit-opt 本章继续Python的优化算法系列. 优化算法,尤其是启发式的仿生智能算法在最近很火,它适用于解决管理学,运筹学,统计学里面的一些优化问题.比如线性规划,整数规划, ...

  6. 智能优化算法之遗传算法(GA)的实现(基于二进制编码,Python附源码)

    文章目录 一.遗传算法的实现思路 二.基于二进制编码方式的遗传算法的实现 1.库的导入 2.目标函数 3.个体编码函数 4.个体解码函数 5.选择函数 6.交叉函数 7.变异函数 8.算法主流程 一. ...

  7. 演化计算(蚁群算法、粒子群算法、遗传算法、演化规则......)

    演化计算(蚁群算法.粒子群算法.遗传算法.演化规则......) 1.概念 2.传统算法和演化计算 3.一般步骤 1.概念   演化计算主要用于解决预测优化问题.由于演化计算利用一组解求解,所以这一组 ...

  8. 【优化算法】遗传算法GA求解混合流水车间调度问题(附C++代码)

    [优化算法]遗传算法GA求解混合流水车间调度问题(附C++代码) 00 前言 各位读者大家好,好久没有介绍算法的推文了,感觉愧对了读者们热爱学习的心灵.于是,今天我们带来了一个神奇的优化算法--遗传算 ...

  9. 粒子群算法和遗传算法求多元函数的最大值、最小值对比

    目录 前言 1.粒子群算法寻优 1.1 求目标函数最大值 1.2 求目标函数最小值 2.遗传算法寻优 前言 个人认为粒子群算法和遗传算法思想都很接近,都是一个通过对比去寻找最优解的过程,如果对比我比你 ...

最新文章

  1. 如何在 Linux 上永久挂载一个 Windows 共享
  2. 一周最新示例代码回顾 (5/7–5/13)
  3. 解决浮层弹出如何加上datepicker,并且浮动在上面
  4. android系统可以破吗,你的手机系统破到什么程度?一键查安卓漏洞
  5. 从央视到谷歌:聊一聊竞价广告的机制设计
  6. 如何快捷配置java路径_eclipse常用快捷设置
  7. oracle desc能看约束,ORACLE 12C新特性-DESC显示不可见字段 | 信春哥,系统稳,闭眼上线不回滚!...
  8. 《机器学习系列-强填EM算法在理论与工程之间的鸿沟(上)》
  9. 每日算法系列【LeetCode 875】爱吃香蕉的珂珂
  10. 经典机器学习系列(四)【神经网络详解】
  11. matlab中的语言,把c语言变成matlab语言,可以在matlab中运行。
  12. 将Altera FPGA的sof文件和NIOS II的elf固件合并为一个jic文件以使用Quartus Programmer烧写
  13. html中描文本链接,锚文本、超链接和纯文本链接的区别以及使用方法
  14. 1534 棋子游戏(博弈论,未知规律... ...)
  15. Airbnb短租分析
  16. iol植入手术过程_有晶体眼IOL植入技术
  17. JAVA:基本运算符及应用:这是一个闰年吗?
  18. 麒麟合盛(APUS)李涛:APUS云重新定义“云联邦”
  19. matlab中求立方根,matlab实现求复数立方根的函数代码怎么写
  20. 通常所说微型计算机的奔3,求江西省2011年计算机等级一级考试试题

热门文章

  1. 漫画:什么是流行病的 R0 和 R ?
  2. 人生苦短,不光要用 Python,还要在 VSCode 里用 | 原力计划
  3. 真实版“删库跑路”?程序员蓄意破坏线上生产环境!
  4. Python 大数据分析疫情:如何实现实时数据爬取及 Matplotlib 可视化?
  5. 21 个必须知道的机器学习开源工具!
  6. 华为 P40 或首发鸿蒙系统;新 iPhone Logo 移至中间;React 组件库 uiw 3.4.0 发布 | 极客头条​...
  7. 程序员如何从初中级历练为高级开发者?
  8. 看动画轻松理解「链表」实现「 LRU 缓存淘汰算法」
  9. 零基础程序员如何花 8 个月时间获得特斯拉实习机会?
  10. 东北到底有没有互联网?!