数学建模社区-数学中国

标题: 遗传算法(python版) [打印本页]

作者: 1440359316    时间: 2021-6-19 15:17
标题: 遗传算法(python版)
1.png
1 i0 Y3 N( L  ^遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。该法则很好地诠释了生物进化的自然选择过程。遗传算法也是借鉴该基本法则,通过基于种群的思想,将问题的解通过编码的方式转化为种群中的个体,并让这些个体不断地通过选择、交叉和变异算子模拟生物的进化过程,然后利用“优胜劣汰”法则选择种群中适应性较强的个体构成子种群,然后让子种群重复类似的进化过程,直到找到问题的最优解或者到达一定的进化(运算)时间。
& z% L2 w6 `' ~4 A
6 N9 w. [: D0 U& h0 UGa算法中的几个重要名词概念。
' ~" i) ^8 d2 B/ C8 @! C
- w( s, D: n( B/ O. @4 Z( M个体(染色体):自然界中一个个体(染色体)代表一个生物,在GA算法中,个体(染色体)代表了具体问题的一个解。
/ O& P+ S' E. h: `. j 2.png - x5 x6 b+ @$ \0 o

8 A7 K1 f) F% W基因:在GA算法中,基因代表了具体问题解的一个决策变量,问题解和染色体中基因的对应关系如下所示:+ n7 n3 l) K* U3 O7 P0 K; X

0 ~# j! I$ g- w. f) W/ ]9 g- v 3.png ( A2 W) P/ X4 L. D& D: q7 |
种群:多个个体即组成一个种群。GA算法中,一个问题的多组解即构成了问题的解的种群。
2 i9 t, m, M; {- ?2 }3 C1 u
% u. Q2 j. u2 u2、主要步骤
0 e! C) D' c5 {, V) \; RGA算法的基本步骤如下:
( _4 E0 }6 Y3 }  h" @/ P
/ Z  r: U5 _# t+ M+ P  EStep 1. 种群初始化。选择一种编码方案然后在解空间内通过随机生成的方式初始化一定数量的个体构成GA的种群。# I1 A" s7 |0 M+ k$ b6 I( z
9 ~: L  ?; ^4 B9 @& F8 I" u
Step 2. 评估种群。利用启发式算法对种群中的个体(矩形件的排入顺序)生成排样图并依此计算个体的适应函数值(利用率),然后保存当前种群中的最优个体作为搜索到的最优解。
; _2 M% k5 \+ k, z* `+ j. E: q! l
Step 3. 选择操作。根据种群中个体的适应度的大小,通过轮盘赌或者期望值方法,将适应度高的个体从当前种群中选择出来。' ~5 q( `" W! q& w
& A1 L& w$ y" f8 n& y9 U& @
Step 4. 交叉操作。将上一步骤选择的个体,用一定的概率阀值Pc控制是否利用单点交叉、多点交叉或者其他交叉方式生成新的交叉个体。
1 m* s4 e% F+ p* L2 e. `  e( G  E8 n7 D' e! W+ {  j" \
Step 5. 变异操作。用一定的概率阀值Pm控制是否对个体的部分基因执行单点变异或多点变异。
+ n, V3 x# h; v# @. M( K
) S( b  T& ~$ Z: L. Q. R( u8 [Step 6. 终止判断。若满足终止条件,则终止算法,否则返回Step 2。
  |* D! h: t  X8 ?/ y' J
0 W, @/ U% J$ m2 e0 k; E6 d流程图如下所示:
9 o$ k$ `3 }4 n5 E 4.png
8 c6 Z( C4 u# @* U. ^5 C. R! q1 p/ S$ J2 D
3、主要操作介绍+ w# x- i( W8 S4 s0 O
3.1 种群初始化
2 g8 N- u+ G8 R: ~种群的初始化和具体的问题有关。比如一个问题有n个决策变量{x1,x2,…,xn}。每个决策变量有取值范围:下界{L1,L2,…,Ln}和上界{U1,U2,…,Un},则种群中个体的初始化即随机地在决策变量的取值范围内生成各个决策变量的值:Xj={x1,x2,...,xn},其中xi属于范围(Li,Ui)内。所有的个体即构成种群。当每个个体都初始化后,即种群完成初始化。
$ u: V. Z3 u' O: r* a% J8 a1 q/ E- U7 p0 v
3.2 评价种群
! K2 g7 q' l6 z9 @& q" a种群的评价即计算种群中个体的适应度值。假设种群population有popsize个个体。依次计算每个个体的适应度值及评价种群。+ Y% ^8 g0 _) A* t, Z3 ^

- l  H) t" c$ c) `3.3 选择操作
1 a! \* a/ f9 xGA算法中常见的选择操作有轮盘赌方式:种群中适应度值更优的个体被选择的概率越大。假设popsize=4,按照如下表达式计算各个个体的被选择概率的大小,然后用圆饼图表示如下。3 }+ [- b- X$ M% w, ^! ~
3 }4 M3 x  i2 D* ]9 E
P(Xj) = fit(Xj)/(fit(X1)+fit(X2)+fit(X3)+fit(X4)),j=1,2,3,4- z+ d% T( I" m  z7 ?
5.png 8 r! c8 G7 O0 b7 h! w

2 }# j: A8 E# y! V* X当依据轮盘赌方式进行选择时,则概率越大的越容易被选择到。
+ S, T8 I2 G) L6 ]% k+ X7 W
+ A$ w3 X  V, W+ C3.4 交叉操作, Q) i  B( A3 S  \
交叉操作也有许多种:单点交叉,两点交叉等。此处仅讲解一下两点交叉。首先利用选择操作从种群中选择两个父辈个体parent1和parent2,然后随机产生两个位置pos1和pos2,将这两个位置中间的基因位信息进行交换,便得到下图所示的off1和off2两个个体,但是这两个个体中一般会存在基因位信息冲突的现象(整数编码时),此时需要对off1和off2个体进行调整:off1中的冲突基因根据parent1中的基因调整为parent2中的相同位置处的基因。如off1中的“1”出现了两次,则第二处的“1”需要调整为parent1中“1”对应的parent2中的“4”,依次类推处理off1中的相冲突的基因。需要注意的是,调整off2,则需要参考parent2。
+ ]1 @- g' V$ r' ~
8 L0 Q2 }. R/ s5 F) ~ 6.png
' G. A7 }/ j7 V/ {0 C- ?; t7 X. k: T
3.5 变异操作
7 C  ?& e, E: p8 G) J; K3 E变异操作的话,根据不同的编码方式有不同的变异操作。+ p8 W7 k) H6 B  e' G8 G& }

* U( S! K( [: |& @如果是浮点数编码,则变异可以就染色体中间的某一个基因位的信息进行变异(重新生成或者其他调整方案)。
! C0 W% f+ o" [' a  c" V' e. p- [$ `9 E9 [* k4 u, g
7.png ) z0 E# [5 J! U1 Z
如果是采用整数编码方案,则一般有多种变异方法:位置变异和符号变异。) B, X: v2 `% [7 N' B- n: [1 J% Y2 q
  D& U7 J+ B! z0 B4 W
位置变异: 9 S$ k2 z7 Q6 E
8.png
% m- F: C0 K+ \* P6 O5 C4 i
  d, C3 \, W; D0 Z4 j& L符号变异:
3 l/ X' A! d2 _2 o# a8 { 9.png # V+ Y0 b% ]+ f( ]

9 C$ L6 ^9 S( R8 ?9 [: s4 I4、Python代码) H1 s$ r, n$ U' n/ X( @
#-*- coding:utf-8 -*-: w# g+ N: G6 M! z7 }# q
# M; J* f- o: p% _! N
import random/ z+ P, T! a4 n4 a
import math6 l$ _& H' u; N6 V7 Y) h
from operator import itemgetter
& X9 d8 `+ h/ t) X( Q* \# v
8 x/ u9 Z& Q9 e" W8 l; ~" _class Gene:; w0 f* r$ Z/ b+ l3 l+ }( h
    '''
3 T9 A" y* n% L! D, [3 E    This is a class to represent individual(Gene) in GA algorithom
. ]- S; |) }0 [    each object of this class have two attribute: data, size: c4 h+ ~( T0 I( l, Q4 z
    '''6 J0 {& F7 O3 y+ d
    def __init__(self,**data):$ K) k7 O0 X- O. w7 R5 o" ?3 ^, J: y
        self.__dict__.update(data)       , u! I: P* K* Y# g
        self.size = len(data['data'])#length of gene
' w, l5 B2 p. n  `1 x" \+ j2 P  }) R$ [

+ j) ]  S) v0 Eclass GA:
5 W4 q) `1 A; u, G7 Z& m& B    '''
+ y% b7 Q/ h( d) R    This is a class of GA algorithm. 5 F8 U* M" c* f: F+ I
    '''
( ]. S1 L0 d. @( }7 o7 w  v6 G    def __init__(self,parameter):
& A2 u2 i/ o, l) q. |        '''. J. x4 @( ?( `8 h  H6 A, a
        Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .7 h9 b+ F; ~6 w2 \2 V0 \5 ~6 n
        The data structure of pop is composed of several individuals which has the form like that:* X: G0 Y, [8 Y4 q; V0 r
. W# O# `1 H, D' y
        {'Gene':a object of class Gene, 'fitness': 1.02(for example)}
" x- V9 V! s7 M0 G$ }        Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]* W' V# F# N$ T- R) x
: D* ]" w0 \0 [) Q8 P) {
        '''
" Z) K; |% Q( T; {" ^9 z; n! ]        #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]& |* N! a) }7 M0 B  Q  X" \6 K
        self.parameter = parameter3 Y% g: r- r& }/ a# v, R" |
* C3 T9 r+ X0 _
        low = self.parameter[4]! D* I: ]& K& G7 s3 z
        up = self.parameter[5]
5 v8 n- m! B# c
# Y$ r1 g- \, t        self.bound = []  _5 ?, M3 `, }, z) }5 H" }+ v. k0 F
        self.bound.append(low)
) b: V# t# Z5 ~5 u        self.bound.append(up)6 z1 J6 V: l7 ]6 X9 |5 e

, ?3 d% N) H$ k( }        pop = []. Q# [: p& l7 \" ^1 _" ]
        for i in range(self.parameter[3]):9 g8 x0 O3 @4 q7 s% y1 A
            geneinfo = []
$ S/ M& R# W( j2 w' e) r+ F            for pos in range(len(low)):
; n* X* a8 a. B( B& J' g                geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation
) w2 g7 {: J% \' x6 ?! u
! K) }% |6 y! `  v% B+ B+ O            fitness = evaluate(geneinfo)#evaluate each chromosome$ M0 z2 |" i' P* `# t8 X
            pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness
6 D% Y1 ~+ l& j  g8 Y$ v1 u6 M8 P: a1 B1 z  d4 J
        self.pop = pop
- g) B* y$ t1 T2 ]/ c$ C1 v2 K        self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population
$ |) b) U. q  v9 L4 E3 ]# C/ W, I" i. a7 u: P5 E  C* {
    def selectBest(self, pop):2 X. d, {  m# `  D$ H
        '''
# N  R+ n8 M+ U4 C        select the best individual from pop
4 U& o) M' S" m6 U" R9 Z        '''9 Q5 A# ]# H# N* M, R
        s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)
# I/ P5 q: p; O' z        return s_inds[0]
- ~, E, y" J5 ^9 k$ S" v5 ^, m5 v. Z' ]0 v# s+ v3 Q
    def selection(self, individuals, k):% X# I8 |3 r( H' B
        '''& A/ |+ F1 f1 H7 N0 q; O; t( e+ Q
        select two individuals from pop
8 ~8 }2 ~% Y' T: V" c4 A        '''9 [( F) j. P$ T' @( Z
        s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness
* N; U0 t3 V# G: K, T        sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop
! G! A1 \* N. Y# d
+ V9 n# d" p8 H0 ?9 N        chosen = []! U' P; d0 s# ~# J; \
        for i in xrange(k):
! F" R/ z- `) t$ Y% `* Q            u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]5 \% J# l; A( b" T! ]9 M8 P
            sum_ = 0
! I2 |# E. S0 q9 ~6 G            for ind in s_inds:
& ?- G3 J. v/ U' ~$ ]/ c% ^                sum_ += 1/ind['fitness']#sum up the 1/fitness
1 ^8 _/ b0 @" T$ G: [; S                if sum_ > u:
$ D5 W& |. l$ }1 }                    #when the sum of 1/fitness is bigger than u, choose the one, which means u is in the range of [sum(1,2,...,n-1),sum(1,2,...,n)] and is time to choose the one ,namely n-th individual in the pop( b8 j/ j& c5 b. L% \$ q; W# D0 }$ H
                    chosen.append(ind)
- ?1 i. w, D/ x4 j6 P1 o                    break
; n8 B/ M2 c( ]
5 `: |6 o! H( J. r( S        return chosen    & O7 _4 e) y7 T; N2 J. `, T
* S! D3 Q( a4 k9 u+ w" B$ T5 ^! B+ P

' {$ I  G. ?* i; _    def crossoperate(self, offspring):
4 L7 X  E; k4 c        '''2 \1 g$ o0 |% i/ X7 x% O
        cross operation
( L0 |, }/ O% i. }6 d        '''# C  Y$ [3 [- k* l/ Q  D8 i7 M
        dim = len(offspring[0]['Gene'].data)
& `9 V& a. y- y1 X' `! G7 N/ E% [
        geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop
% G: \6 M' y+ ?% q# r        geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop: e' B! H6 J9 U! T% T; e, C2 e( t& p

9 Y2 I% T8 q9 {0 @9 q/ U) ^9 b" m        pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1, 3 }4 q, V" ]* _1 S" Y# b8 T; g
        pos2 = random.randrange(1,dim)
! [7 O. y  k' m$ T9 H* T6 Z7 O
: g1 f$ U) R0 I' m  z- O$ b% X        newoff = Gene(data = [])#offspring produced by cross operation5 g3 S7 P) Z* J
        temp = []
: G- F9 W% q: m3 g# g2 ]- J  x; ?6 b        for i in range(dim):0 X9 h4 z3 Z# \9 ~9 w
            if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):
) Z6 Q$ n( h) A3 O6 o4 `! p1 y                temp.append(geninfo2)
3 A% c. h) R7 k3 F4 [8 x' J. t! B                #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)], n/ i  a' x  E
            else:
/ a0 C1 R% C) S                temp.append(geninfo1)" Z7 j$ [- {, w  p) S. f( y. L) G% t
                #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]
3 ^. G1 O, z. z* E3 B0 C/ M8 ]* A4 z        newoff.data = temp
! s% d( v$ ?+ e) K7 b& e2 s) j
' R: P6 Y( G, p        return newoff. j- [" o& D. b! a  Y4 U( r9 k

% l5 Y0 l1 w0 Q8 C9 \( E  d7 I" I; `% G% H: h9 z
    def mutation(self, crossoff, bound):1 Z+ w6 ?, z5 M0 j6 H3 S: F
        '''
4 T' ?, |: b/ p( J& F7 K+ o8 Z        mutation operation: l+ @! n1 {; C) k/ C. k
        '''+ q9 s) P) I4 e9 i3 u) q
5 v' O2 N  U  B2 A, C
        dim = len(crossoff.data)$ Z  E  E7 g) U+ D( g

) z6 L$ j. \5 p* _9 M- o0 {        pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.* x, Q, \1 q6 l, o6 n& K/ X9 q
$ L. x  A0 X/ _3 N/ \+ u
        crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])
- e8 J5 L6 O4 c1 r; o        return crossoff* V9 B* r$ J2 ?
7 v6 w6 x* R$ ^2 c; D* p$ ~) \
    def GA_main(self):
: ^' U3 `# I# W. n; V        '''
( X% R+ q- O# B% a; W        main frame work of GA6 L$ j' ~$ @! _) l5 @
        '''. N( S* G- u' y) L2 r& X( |$ N( ^

& g- x: X# {2 o& v7 K        popsize = self.parameter[3]4 d& w' f" w% C6 H* x/ [- Q
! e4 P/ Y& y  m# z
        print("Start of evolution"): R! S( F2 E5 _8 ^! H- J. R
6 x8 n4 S# }/ C5 r: P, C
        # Begin the evolution
" v" q# |0 s1 s$ W/ h- Q+ u        for g in range(NGEN):
/ T5 A' o/ v" P
0 E' H+ h. T2 v) q2 n            print("-- Generation %i --" % g)      . W' V, ]: b4 E* E2 @4 Z7 ^
- \2 U9 ?* f! S% X! |/ }6 k# n9 G
            #Apply selection based on their converted fitness
5 \/ M! g& @1 O8 U- a( @            selectpop = self.selection(self.pop, popsize)   
5 G+ ]8 W0 {2 C: T/ r! p
( n# m! p0 n/ M/ I  N5 p! f3 j            nextoff = []    * [: k6 t9 o2 ^4 e$ a2 R
            while len(nextoff) != popsize:      - v2 e3 `/ d+ D0 e4 Z; I
                # Apply crossover and mutation on the offspring            
! B8 n* P; Q: @) v# G; p# I! u' X% T; }8 H4 V& s
                # Select two individuals1 V6 q3 B% I& h& V9 F
                offspring = [random.choice(selectpop) for i in xrange(2)]3 ^% U- G- m; H. c" |2 F8 Z

" g: q+ \. X' f* M; Q  j                if random.random() < CXPB: # cross two individuals with probability CXPB
7 ?$ G$ C+ s8 k; ~                    crossoff = self.crossoperate(offspring)
4 z. a/ K$ E* p  h/ g) |                    fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals           " p' ~: `) a/ q3 S4 ?1 |" H

% L5 }7 U& s/ q8 P5 J                    if random.random() < MUTPB: # mutate an individual with probability MUTPB
* s9 y7 z+ M' X7 \  h* O                        muteoff = self.mutation(crossoff,self.bound). z% z5 R3 Q5 T# R8 t
                        fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals
6 O% q1 b$ {! i: S) i+ r1 c. C- C                        nextoff.append({'Gene':muteoff,'fitness':fit_muteoff})
1 N. k4 @: j" x3 p' T
7 O2 g* s2 C+ N) X; A5 i) w* @- U            # The population is entirely replaced by the offspring
7 n, F$ C9 |% q2 P( x2 s            self.pop = nextoff4 Q% X* i2 [9 K; z

9 C! h, s- ^# t# j, P            # Gather all the fitnesses in one list and print the stats
; e7 z& d, c/ ~; |) u            fits = [ind['fitness'] for ind in self.pop]9 z# d3 d& e" l9 `# v
2 L9 h6 r1 c1 V  _+ B+ K. t" m
            length = len(self.pop)7 E" P" K! O: d! K+ z* ?2 p4 g- s
            mean = sum(fits) / length6 o! k" I# g5 \( a
            sum2 = sum(x*x for x in fits)
, O' s/ k0 W9 `& w: r            std = abs(sum2 / length - mean**2)**0.5' v' x( m: @( ^# c  [  t6 n" p& `) e" B8 X
            best_ind = self.selectBest(self.pop)$ W! s. i0 U$ o9 k

0 Q9 V/ a9 I% e% S            if best_ind['fitness'] < self.bestindividual['fitness']:
. b# u! M0 |$ s# T! P& t                self.bestindividual = best_ind
8 r$ x5 s! S/ F8 \# M. L- E
0 y' O" R" s$ l" y            print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))
8 d3 y3 y9 v2 T! `            print("  Min fitness of current pop: %s" % min(fits))- M# y) b0 e  i7 X
            print("  Max fitness of current pop: %s" % max(fits))
6 J; K# j7 y! X( b            print("  Avg fitness of current pop: %s" % mean)
) [* M; T6 |3 t            print("  Std of currrent pop: %s" % std)
5 ]  V8 z6 V7 p" R% _! z/ j( X2 `, }, F/ F$ f- l
        print("-- End of (successful) evolution --")   
: Y' d- [# P1 ]2 }, {( k
) a: V) m3 ?1 ?* t1 U' S, j: ]if __name__ == "__main__":
' E) ]2 h& ?- v  H7 F; ~6 I- B% Z' o! s$ q' k, n- {$ w, Y
    CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters
- K. W6 h8 Z8 O9 R4 |: n. X$ L
    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables
/ N$ g' X' \* Y. ^) _% k) ]    low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables
% a4 F- [2 }/ R/ |    parameter = [CXPB, MUTPB, NGEN, popsize, low, up]
0 p8 Q- i  J( m
/ g. ~7 a) r; c4 ?% J* \# j    run = GA(parameter)' r- |# m" ~6 A( J( ~, `
    run.GA_main()
7 T, I, O- I/ g7 t————————————————
) d! ~4 L9 a( s5 a7 ?: v4 j版权声明:本文为CSDN博主「bible_reader」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。; ?  f4 {0 j5 U3 x& d3 O7 _$ @
原文链接:https://blog.csdn.net/bible_reader/article/details/72782675
4 A" Q& L! b, F# ]1 I, }1 d% \* T  w1 n4 Z; O; e! V( i4 d2 J4 x

5 h, n. `  r  `
作者: 1034228464    时间: 2021-10-12 18:46
python实现遗传算法易懂
" \0 f6 k6 [6 @
作者: lifekokool    时间: 2022-1-17 16:05
可能我有点笨吧,看了之后还是不知道该怎么应用某个问题% d/ o: b6 s- ^

作者: 738391227    时间: 2022-2-19 16:36
00000000000000000000000008 g# u4 c: O/ P2 b( i3 D4 b/ K& ]

作者: 852952290    时间: 2022-8-10 20:25
111111111111111111
/ @. x$ ^. c# B/ S- S
作者: 2275929388    时间: 2022-10-9 14:14
遗传退货怎么都看不懂% D! C' `4 F& J' a5 J+ c* a( c

作者: wwyx。    时间: 2022-10-9 18:28
赞赞赞赞
4 ]2 b* d/ p9 v1 p
作者: 2275929388    时间: 2022-10-10 09:08
566666666666666666666
1 D! U3 s& ]2 \) Q8 b0 {
作者: 2580684929    时间: 2022-10-12 23:19
牛蛙,最近在看这个
/ s7 X" T+ u7 I9 O/ P




欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5