数学建模社区-数学中国

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

作者: 1440359316    时间: 2021-6-19 15:17
标题: 遗传算法(python版)
1.png
; }3 J( R" I3 |' U遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基本法则的智能搜索算法。该法则很好地诠释了生物进化的自然选择过程。遗传算法也是借鉴该基本法则,通过基于种群的思想,将问题的解通过编码的方式转化为种群中的个体,并让这些个体不断地通过选择、交叉和变异算子模拟生物的进化过程,然后利用“优胜劣汰”法则选择种群中适应性较强的个体构成子种群,然后让子种群重复类似的进化过程,直到找到问题的最优解或者到达一定的进化(运算)时间。
4 [4 Q1 d" ~% z1 h/ k! E- x3 h+ B
Ga算法中的几个重要名词概念。
! U- C0 @' n+ _1 q
* ^: w6 N; Z" d8 n1 J3 g个体(染色体):自然界中一个个体(染色体)代表一个生物,在GA算法中,个体(染色体)代表了具体问题的一个解。% `5 ^& z/ H% N9 {
2.png . n" A1 ~3 [. A" ]' B

8 V5 K/ H& ^0 @% s( X5 ~基因:在GA算法中,基因代表了具体问题解的一个决策变量,问题解和染色体中基因的对应关系如下所示:
( ~: y- {2 l5 e' X+ E) {5 V, p( {) {4 J
3.png
7 n! V8 P& i% }# m* U2 @种群:多个个体即组成一个种群。GA算法中,一个问题的多组解即构成了问题的解的种群。
/ K# C  p1 L0 C
7 i' Z6 H8 e( `9 u% h. e- C2、主要步骤4 L4 k$ Y/ Z6 i% d% R
GA算法的基本步骤如下:
% e9 j5 y5 [% f/ h. g- R
# v. {& V' p5 pStep 1. 种群初始化。选择一种编码方案然后在解空间内通过随机生成的方式初始化一定数量的个体构成GA的种群。
( K5 a6 v; ^3 S7 h+ V# j& o' d& ~. R; d" B  T
Step 2. 评估种群。利用启发式算法对种群中的个体(矩形件的排入顺序)生成排样图并依此计算个体的适应函数值(利用率),然后保存当前种群中的最优个体作为搜索到的最优解。6 s( }$ D( p0 b2 B; _: `: Y+ I/ j

6 E: i/ u' z# E, U3 I+ \7 yStep 3. 选择操作。根据种群中个体的适应度的大小,通过轮盘赌或者期望值方法,将适应度高的个体从当前种群中选择出来。$ e) F/ j' e% A+ d0 D9 k+ w0 A
  L# s1 R% W' t: I
Step 4. 交叉操作。将上一步骤选择的个体,用一定的概率阀值Pc控制是否利用单点交叉、多点交叉或者其他交叉方式生成新的交叉个体。7 e: h! G4 n/ d4 ~

7 c4 W, l' |8 AStep 5. 变异操作。用一定的概率阀值Pm控制是否对个体的部分基因执行单点变异或多点变异。# a6 ^5 g9 O: o( q0 y
. c. u5 P+ A% k6 [3 D
Step 6. 终止判断。若满足终止条件,则终止算法,否则返回Step 2。
3 w! [% g4 v( S4 Y( H) c
' E2 C2 a1 r  l  l" A3 _! ~. s流程图如下所示:5 S$ R, Z* w7 ~) T9 J
4.png
( I/ l5 F+ ]" w; w6 B7 T: _6 V1 C& B; Z$ j
3、主要操作介绍
- d" q, {" x& ^; C. i. x" @0 k3.1 种群初始化/ i5 X7 j0 |' ]+ J; V
种群的初始化和具体的问题有关。比如一个问题有n个决策变量{x1,x2,…,xn}。每个决策变量有取值范围:下界{L1,L2,…,Ln}和上界{U1,U2,…,Un},则种群中个体的初始化即随机地在决策变量的取值范围内生成各个决策变量的值:Xj={x1,x2,...,xn},其中xi属于范围(Li,Ui)内。所有的个体即构成种群。当每个个体都初始化后,即种群完成初始化。
0 r" `# C* s7 t6 W: G( @: D3 V6 t$ a$ E
3.2 评价种群* D$ @2 Y2 w+ A
种群的评价即计算种群中个体的适应度值。假设种群population有popsize个个体。依次计算每个个体的适应度值及评价种群。
# }4 U: G( }- r; G1 a/ c- Z) T8 I* I+ ]* D  x6 P6 C
3.3 选择操作
/ [6 o/ @) D% x" p/ t. a- IGA算法中常见的选择操作有轮盘赌方式:种群中适应度值更优的个体被选择的概率越大。假设popsize=4,按照如下表达式计算各个个体的被选择概率的大小,然后用圆饼图表示如下。
: o! w. l+ L, \$ v+ l) u- J% m3 b# G) M. v1 t: }' `0 Q
P(Xj) = fit(Xj)/(fit(X1)+fit(X2)+fit(X3)+fit(X4)),j=1,2,3,4
+ K1 l8 }1 l1 P 5.png 3 C: X1 u; \* u3 G/ Z' s5 H

; F( F7 O- w9 A9 P9 t) Z5 l当依据轮盘赌方式进行选择时,则概率越大的越容易被选择到。
3 v% S/ t7 S6 Y0 D
% k$ u0 U0 y9 I# p6 \5 t" {- O8 ~& {# U3.4 交叉操作$ q+ Q8 p1 E: ]% R5 B- H
交叉操作也有许多种:单点交叉,两点交叉等。此处仅讲解一下两点交叉。首先利用选择操作从种群中选择两个父辈个体parent1和parent2,然后随机产生两个位置pos1和pos2,将这两个位置中间的基因位信息进行交换,便得到下图所示的off1和off2两个个体,但是这两个个体中一般会存在基因位信息冲突的现象(整数编码时),此时需要对off1和off2个体进行调整:off1中的冲突基因根据parent1中的基因调整为parent2中的相同位置处的基因。如off1中的“1”出现了两次,则第二处的“1”需要调整为parent1中“1”对应的parent2中的“4”,依次类推处理off1中的相冲突的基因。需要注意的是,调整off2,则需要参考parent2。
* H, w; }" d; U& u, z  Y
# ]) h; Q3 a5 W3 _) I1 k& H 6.png 6 r0 Z8 |8 Q: x+ x! Y
2 f& R- R* H6 X1 L+ g* s+ g# m
3.5 变异操作
8 Z* E8 [0 m% @* y6 Q变异操作的话,根据不同的编码方式有不同的变异操作。, W0 v5 f. X# ~+ E* P0 h

( H! T* K2 I: W9 k如果是浮点数编码,则变异可以就染色体中间的某一个基因位的信息进行变异(重新生成或者其他调整方案)。2 e& I& f& T6 L+ c( D% {. u5 t4 \; n
& `# b& [1 r/ J, r+ O, p2 p4 n
7.png
7 \- v5 H( o8 H5 u% H如果是采用整数编码方案,则一般有多种变异方法:位置变异和符号变异。" q  V. s4 _- W7 c; m/ P

5 [8 k% ]- P+ g9 W0 z, @位置变异:
$ S# p/ P4 i- s3 w 8.png
- w: Y0 f4 z$ l6 U
( L! h8 T" y5 }符号变异:
8 l% ]* n/ ^( d& a" m8 @ 9.png ' d/ C9 r: J% P+ ~* P

: L8 m6 S! O8 Q9 p- y) S4、Python代码6 z4 o' o0 Z7 R, n5 H' H! O
#-*- coding:utf-8 -*-
2 @4 u* Z+ l1 @! ~+ [( J4 @) P; G& Y* u5 S
import random
, x" x% l2 K) e4 }% {2 Bimport math
0 F9 A7 ~( l# z* |: d8 Dfrom operator import itemgetter
% Q/ V( H1 x* H& l/ L: [' s' c0 {$ J
2 J/ f7 w% I8 L. @, \7 yclass Gene:
, T( E- A1 d- Q- M: p; l5 C    '''
) j$ d% a6 c/ R& m% k: C    This is a class to represent individual(Gene) in GA algorithom
% W0 P* `3 w. d    each object of this class have two attribute: data, size, e* E* [, b# ]2 r
    '''7 C6 q9 {  ]  V
    def __init__(self,**data):. Q( L/ K  x& n3 K0 W$ `
        self.__dict__.update(data)      
+ Q; _, I+ E( d. w8 P: J        self.size = len(data['data'])#length of gene+ S$ w; E0 V2 p' M
0 X( m& ~. E$ I. i! q$ D( w

+ e! t) b0 M3 \7 x) X7 z. m  yclass GA:
4 ~4 x& E& z$ }1 }# P    '''2 F3 [' f9 h5 h4 _
    This is a class of GA algorithm. $ R3 h3 ]: e4 e2 E4 ~8 }) G8 D- e
    '''
; T4 W2 _# @/ U) n6 u    def __init__(self,parameter):6 ~/ Z- [/ w& i; U
        '''
# \; D5 U: X% C# L        Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .( F' D" q+ p5 n
        The data structure of pop is composed of several individuals which has the form like that:% ]- L5 ]5 |, ~$ {( q0 A. X& p

8 g+ J' e9 h" ]# ]& V5 q        {'Gene':a object of class Gene, 'fitness': 1.02(for example)}9 t% A' D7 i3 p3 p, x- H) C  ^, T
        Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]
3 e% b- d% t+ c& D  P
" S% X1 z  _# [        '''4 B$ W8 S( U# K* [% ~$ o, A
        #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]
* w4 s2 D3 Y0 O( T( I5 m( G; s        self.parameter = parameter) r! a4 q0 M: X: J, `9 T

" y& R5 n4 I+ S; I        low = self.parameter[4]2 t6 P3 F3 |$ T. z+ p1 q
        up = self.parameter[5]. [' b& B. R2 o% y& u+ S2 S: C  I3 c

& ~" f5 e- Z6 i8 t2 p) o( b7 d9 Q        self.bound = []
2 s5 w& q# J$ y: }5 V; x7 a        self.bound.append(low)
- K: k* _8 Q) Q8 o. S# I8 S        self.bound.append(up)
, v( y$ J3 o7 a! Z( b! z" R6 Y' I  ?0 v
        pop = []
9 O/ T3 Y- W" \9 j, V5 Y/ z) p        for i in range(self.parameter[3]):" Q, w+ G. N& @
            geneinfo = []3 L- O7 M' I" s# j% S  {
            for pos in range(len(low)):
- R: \' t) ^2 I5 z3 l' Q                geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation2 ]% K! ^4 {# E

. `+ l1 f7 S* C0 w% e            fitness = evaluate(geneinfo)#evaluate each chromosome
# U! N: h: v7 v7 _2 x) F, f- c            pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness9 }8 M$ P7 x1 F% S2 o0 E% K: ?
- ]+ U; h3 m0 h! N
        self.pop = pop% h+ ?) U7 h9 P* ~! A7 i( l0 Z
        self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population
! y" [' o: m1 n
  m% O; O, R* _$ S7 L4 y2 x" N    def selectBest(self, pop):: e% F+ \6 k/ o- S: a: W) i$ _
        '''
$ t% u) y& w6 |% j7 L        select the best individual from pop( Y4 g% h% @! Y. u7 H) ^
        '''
' U/ j5 A& E! w& w        s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)
* {/ {4 v) T! }0 Q- ^% x        return s_inds[0]' I( d" l) R: l1 ~" z1 j

5 ?# d) N' w' O  m" r6 M    def selection(self, individuals, k):- a6 x* {% m  }0 }
        '''/ u( j" v+ A7 P  a
        select two individuals from pop% p7 N' h$ y( o0 u) K& Q% Y8 p: i
        '''0 Z% j, F; D, w; T( ~" a' N
        s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness
5 X; p$ R1 g2 m) c' ^( T        sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop7 P  M0 w0 C! @6 X6 S9 i

' p- u! o/ W  v% C        chosen = []& Q+ q; `6 t6 G* N- g
        for i in xrange(k):
' Z5 a3 g  C( I, ^: ~" H            u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]2 K) a* a( [3 H
            sum_ = 09 v# r8 r, t, ?8 g
            for ind in s_inds:  K0 i0 o8 l% B! X9 f# A/ U: A$ p- x9 D  h
                sum_ += 1/ind['fitness']#sum up the 1/fitness* B8 X/ A, _  |6 a9 v4 O% v4 t
                if sum_ > u:
/ R! s- S4 Y, k9 w% H                    #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 pop6 e% {/ U/ ^0 B- z2 O8 P
                    chosen.append(ind)5 u$ m" i& ]8 k7 n! G
                    break  s- P* D) O* M- k% s+ y* L7 o

% d4 ]4 b' ^0 N$ j5 z# O        return chosen   
! h# ]' R! U, G: f; B, d7 M5 v/ \1 z" Z# Q9 w" V2 t

  K0 k# u" Q. |( E' Q" C  U    def crossoperate(self, offspring):. o4 K9 ?/ x5 u/ i9 O; V
        '''
. d' ?6 T6 u4 |% W  S/ a- {. G        cross operation
6 F2 K7 c+ P: P- q        '''( n2 ^$ B/ D8 K$ s3 c
        dim = len(offspring[0]['Gene'].data)7 I5 z# Z/ K5 B5 R2 e" ?$ ~

$ B& ?/ T! B/ t7 W( Q        geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop
: i! k2 y2 Y( E, |/ E/ r; Z; [1 b        geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop+ Z3 `7 X3 D  i; w' M
3 z1 Y2 s; a/ L+ {
        pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1,
; I& d. ^% f$ D( G3 C9 n        pos2 = random.randrange(1,dim)1 [, }6 h1 O: {, ?1 Y

3 y+ Z* t; ]7 Y% b/ q& v( c9 _, n9 w9 y        newoff = Gene(data = [])#offspring produced by cross operation, p5 `3 o9 J* [" |% k. V
        temp = []
$ ~. }$ B6 \4 n  X  u+ r# p        for i in range(dim):
- u$ q5 J% {8 S& D7 t- y. l5 K            if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):9 @3 Z' B# i; F' `! z# p
                temp.append(geninfo2)& p8 _3 U$ j2 p9 M( p3 X3 X
                #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)]
6 U* M) a3 q" z            else:8 U! Z5 u8 \; {" E
                temp.append(geninfo1): R+ i3 v8 C$ V& U2 \
                #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]
7 ?/ |' [9 ^7 _, @        newoff.data = temp
+ m9 ~: U$ b4 h; _4 b" y6 a' V- u& U$ j" d  Y. x+ x
        return newoff! l% n0 p/ G4 V1 ]( a; n+ L' T& p

! l+ A3 b* {6 }. I0 k! h" q
  ]: r3 o" J; Y, a1 k. ?/ X    def mutation(self, crossoff, bound):
# M( p1 X; Q3 H2 y0 Q% y7 ~$ K7 \        '''9 K. u, z9 l# @1 c
        mutation operation' \+ X( O0 B8 [4 H- k
        '''
. u9 Y0 f$ {* o1 [1 |& o7 [' x5 A0 ~9 S& j' b1 m
        dim = len(crossoff.data)/ l. @: E( ?% }: d

; N: c. e* N0 u  ?9 w$ k: i& C0 t        pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.
" E, I2 u; b' v4 x+ N
2 J; ^" ~  e# P2 j, [" J1 p5 ~0 |        crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])
6 E( n% S& h1 t0 E( T/ F: `8 G# N8 \        return crossoff5 T3 L7 k( L, C% e" F! ]: E9 o. X
* Z1 |0 u( g& A/ T7 z3 I
    def GA_main(self):# t' U' V# `! i/ [
        '''
7 B) _0 ~( W8 O1 G! `4 y9 ]        main frame work of GA
* M, |* N5 Q4 J, E3 l9 F4 M: z        '''" H$ K% `7 B+ B2 `6 g9 D- g

# C, k3 Z! P& C        popsize = self.parameter[3]
+ o6 ~0 v. q' a* O. K* F" m7 ?8 v4 U6 p" L7 q3 O% `8 @( |7 S. c
        print("Start of evolution")
% R. I- }0 |3 b
8 \1 k" ]8 b3 I" a/ L        # Begin the evolution
1 n6 p! @9 P: r0 j" R% \7 g/ U        for g in range(NGEN):3 U2 H0 x( D! o9 U9 Q

; x9 [) g- S; J" {$ z3 h4 w! A            print("-- Generation %i --" % g)      ' _+ q, d2 T: ~0 i9 }. X

4 l5 q% m* ~' z6 u. ^: q2 f            #Apply selection based on their converted fitness
5 K% y) Z" S2 Y5 c! v3 L  v" g            selectpop = self.selection(self.pop, popsize)   
& u1 {0 P- Q* U+ E, }
& i, Z+ d: {' S            nextoff = []    ( b2 h7 Z$ ~: ?
            while len(nextoff) != popsize:      # p- K2 n0 Y0 \% s% s0 C' K7 O. `
                # Apply crossover and mutation on the offspring            # X5 ?- f2 H! G/ w
8 A$ I  k2 A9 D% U
                # Select two individuals
/ Z6 j  i0 f2 N; k- {7 v( q" L$ _0 Y6 {                offspring = [random.choice(selectpop) for i in xrange(2)]( [- o9 U; v6 u( y+ C
) s( ?% E5 A' m) H
                if random.random() < CXPB: # cross two individuals with probability CXPB( S* O: e$ s0 b& I; G( j8 p6 ^& L
                    crossoff = self.crossoperate(offspring)+ c1 d  e+ p8 Q! B: h
                    fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals           1 n& z% ~5 H$ b
: d: l$ {# H; S, E9 m. U
                    if random.random() < MUTPB: # mutate an individual with probability MUTPB+ r/ d1 O% [! ~" q+ Q  Q" c2 h
                        muteoff = self.mutation(crossoff,self.bound)
9 o! X$ e/ n4 m# C2 ?                        fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals5 p& j$ R9 y1 R, `0 ]+ `/ V0 C' n
                        nextoff.append({'Gene':muteoff,'fitness':fit_muteoff})
7 ]$ e- t  P; y1 d
/ `- @& y  d1 S2 \0 D            # The population is entirely replaced by the offspring9 x$ O8 Z5 s) V3 Y3 E
            self.pop = nextoff
: H$ b$ F9 B. C7 _* l+ [/ K1 V2 J4 K& ~
            # Gather all the fitnesses in one list and print the stats6 B, y. s" }5 \/ A
            fits = [ind['fitness'] for ind in self.pop]
5 x) P3 D( E" T) e
  {8 O. D; L  x: b2 T# U            length = len(self.pop)9 q0 ~# |7 m: p+ H/ }
            mean = sum(fits) / length/ @- I5 v; ]8 ]4 R
            sum2 = sum(x*x for x in fits)# K, K3 M- a8 M" j( Z3 c. R4 P$ m5 d
            std = abs(sum2 / length - mean**2)**0.5
- Z$ G+ f0 ]2 h/ U/ N0 b            best_ind = self.selectBest(self.pop)
5 K2 Y4 s- g4 ^/ A
1 ]6 p- k1 R+ F9 f  I0 E  ~) R            if best_ind['fitness'] < self.bestindividual['fitness']:
  ^. S/ M' j0 Q* X                self.bestindividual = best_ind" h  h! o& |3 m' I
# w, H3 ]! ], U" l  F# K; s
            print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))
% y! E0 G, n5 u8 w& l            print("  Min fitness of current pop: %s" % min(fits))
/ Z" a- j! u- Z- i            print("  Max fitness of current pop: %s" % max(fits))
  E* y% i6 l: N0 J8 }! X            print("  Avg fitness of current pop: %s" % mean)6 N7 P: [; R- n6 ]" I$ Z
            print("  Std of currrent pop: %s" % std)
/ F& d3 i1 p; r: Q& S2 Y$ F1 x, n2 y% E0 X; K+ C+ E
        print("-- End of (successful) evolution --")   
2 |/ r* n' q7 L5 P7 A6 A  n' [% ^% r7 L1 q* I$ R- z
if __name__ == "__main__":
/ H; p$ ?+ O6 `4 U2 b, w& r% n$ {; G8 z2 a
    CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters
) |" a6 i/ z( b3 c1 l/ @- x9 E! ?8 `4 x4 \5 I" p7 c" {  e* f
    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables
- x0 U* O& Z+ J3 _8 H6 u    low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables, L% }- ?& N! F: A/ [! g
    parameter = [CXPB, MUTPB, NGEN, popsize, low, up], A. y. t1 T8 ?1 L
7 `8 U- A& l9 Q$ j( U
    run = GA(parameter); [: E. L: @2 s7 R! Q. X1 J
    run.GA_main()8 u8 G0 ]% A- g5 x: E
————————————————! O" Q# z% G* g8 m' u
版权声明:本文为CSDN博主「bible_reader」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。2 I+ n# _+ N  v& E+ @- O
原文链接:https://blog.csdn.net/bible_reader/article/details/72782675
- Z: m1 g8 R( t: t7 C2 W! j3 c# @( g
- D7 u" W, y! B, G. h/ y

作者: 1034228464    时间: 2021-10-12 18:46
python实现遗传算法易懂
, b5 \5 w& l0 e" h4 m$ E: W
作者: lifekokool    时间: 2022-1-17 16:05
可能我有点笨吧,看了之后还是不知道该怎么应用某个问题% A$ f% g2 ?- J) ?) |

作者: 738391227    时间: 2022-2-19 16:36
0000000000000000000000000
3 X: S7 t8 ^" f! K: @8 \' T$ b/ Q
作者: 852952290    时间: 2022-8-10 20:25
111111111111111111" \( W  k% X% s& x& G1 d; D9 C

作者: 2275929388    时间: 2022-10-9 14:14
遗传退货怎么都看不懂. z' z6 N+ T7 r6 s* s

作者: wwyx。    时间: 2022-10-9 18:28
赞赞赞赞$ p, h: u3 M  G2 ]4 m

作者: 2275929388    时间: 2022-10-10 09:08
566666666666666666666* v: C7 b, d6 i# Q. t

作者: 2580684929    时间: 2022-10-12 23:19
牛蛙,最近在看这个
5 Q4 e; Z9 m/ L) Y9 a6 @% \$ I, B1 e1 w




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